1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
38 using namespace clang;
41 /// A convenience routine for creating a decayed reference to a function.
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
45 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
62 S.MarkDeclRefReferenced(DRE);
65 E = S.DefaultFunctionArrayConversion(E.get());
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
73 StandardConversionSequence &SCS,
75 bool AllowObjCWritebackConversion);
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
87 bool AllowObjCConversionOnExplicit);
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
105 /// GetConversionRank - Retrieve the implicit conversion rank
106 /// corresponding to the given implicit conversion kind.
107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
130 ICR_Complex_Real_Conversion,
133 ICR_Writeback_Conversion
135 return Rank[(int)Kind];
138 /// GetImplicitConversionName - Return the name of this kind of
139 /// implicit conversion.
140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
145 "Function-to-pointer",
146 "Noreturn adjustment",
148 "Integral promotion",
149 "Floating point promotion",
151 "Integral conversion",
152 "Floating conversion",
153 "Complex conversion",
154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
157 "Boolean conversion",
158 "Compatible-types conversion",
159 "Derived-to-base conversion",
162 "Complex-real conversion",
163 "Block Pointer conversion",
164 "Transparent Union Conversion",
165 "Writeback conversion"
170 /// StandardConversionSequence - Set the standard conversion
171 /// sequence to the identity conversion.
172 void StandardConversionSequence::setAsIdentityConversion() {
173 First = ICK_Identity;
174 Second = ICK_Identity;
175 Third = ICK_Identity;
176 DeprecatedStringLiteralToCharPtr = false;
177 QualificationIncludesObjCLifetime = false;
178 ReferenceBinding = false;
179 DirectBinding = false;
180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
184 ObjCLifetimeConversionBinding = false;
185 CopyConstructor = nullptr;
188 /// getRank - Retrieve the rank of this standard conversion sequence
189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190 /// implicit conversions.
191 ImplicitConversionRank StandardConversionSequence::getRank() const {
192 ImplicitConversionRank Rank = ICR_Exact_Match;
193 if (GetConversionRank(First) > Rank)
194 Rank = GetConversionRank(First);
195 if (GetConversionRank(Second) > Rank)
196 Rank = GetConversionRank(Second);
197 if (GetConversionRank(Third) > Rank)
198 Rank = GetConversionRank(Third);
202 /// isPointerConversionToBool - Determines whether this conversion is
203 /// a conversion of a pointer or pointer-to-member to bool. This is
204 /// used as part of the ranking of standard conversion sequences
205 /// (C++ 13.3.3.2p4).
206 bool StandardConversionSequence::isPointerConversionToBool() const {
207 // Note that FromType has not necessarily been transformed by the
208 // array-to-pointer or function-to-pointer implicit conversions, so
209 // check for their presence as well as checking whether FromType is
211 if (getToType(1)->isBooleanType() &&
212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
215 getFromType()->isNullPtrType() ||
216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 /// isPointerConversionToVoidPointer - Determines whether this
223 /// conversion is a conversion of a pointer to a void pointer. This is
224 /// used as part of the ranking of standard conversion sequences (C++
227 StandardConversionSequence::
228 isPointerConversionToVoidPointer(ASTContext& Context) const {
229 QualType FromType = getFromType();
230 QualType ToType = getToType(1);
232 // Note that FromType has not necessarily been transformed by the
233 // array-to-pointer implicit conversion, so check for its presence
234 // and redo the conversion to get a pointer.
235 if (First == ICK_Array_To_Pointer)
236 FromType = Context.getArrayDecayedType(FromType);
238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
240 return ToPtrType->getPointeeType()->isVoidType();
245 /// Skip any implicit casts which could be either part of a narrowing conversion
246 /// or after one in an implicit conversion.
247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249 switch (ICE->getCastKind()) {
251 case CK_IntegralCast:
252 case CK_IntegralToBoolean:
253 case CK_IntegralToFloating:
254 case CK_FloatingToIntegral:
255 case CK_FloatingToBoolean:
256 case CK_FloatingCast:
257 Converted = ICE->getSubExpr();
268 /// Check if this standard conversion sequence represents a narrowing
269 /// conversion, according to C++11 [dcl.init.list]p7.
271 /// \param Ctx The AST context.
272 /// \param Converted The result of applying this standard conversion sequence.
273 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
274 /// value of the expression prior to the narrowing conversion.
275 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
276 /// type of the expression prior to the narrowing conversion.
278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
280 APValue &ConstantValue,
281 QualType &ConstantType) const {
282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
284 // C++11 [dcl.init.list]p7:
285 // A narrowing conversion is an implicit conversion ...
286 QualType FromType = getToType(0);
287 QualType ToType = getToType(1);
289 // 'bool' is an integral type; dispatch to the right place to handle it.
290 case ICK_Boolean_Conversion:
291 if (FromType->isRealFloatingType())
292 goto FloatingIntegralConversion;
293 if (FromType->isIntegralOrUnscopedEnumerationType())
294 goto IntegralConversion;
295 // Boolean conversions can be from pointers and pointers to members
296 // [conv.bool], and those aren't considered narrowing conversions.
297 return NK_Not_Narrowing;
299 // -- from a floating-point type to an integer type, or
301 // -- from an integer type or unscoped enumeration type to a floating-point
302 // type, except where the source is a constant expression and the actual
303 // value after conversion will fit into the target type and will produce
304 // the original value when converted back to the original type, or
305 case ICK_Floating_Integral:
306 FloatingIntegralConversion:
307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308 return NK_Type_Narrowing;
309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310 llvm::APSInt IntConstantValue;
311 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314 // Convert the integer to the floating type.
315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317 llvm::APFloat::rmNearestTiesToEven);
319 llvm::APSInt ConvertedValue = IntConstantValue;
321 Result.convertToInteger(ConvertedValue,
322 llvm::APFloat::rmTowardZero, &ignored);
323 // If the resulting value is different, this was a narrowing conversion.
324 if (IntConstantValue != ConvertedValue) {
325 ConstantValue = APValue(IntConstantValue);
326 ConstantType = Initializer->getType();
327 return NK_Constant_Narrowing;
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
334 return NK_Not_Narrowing;
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
358 return NK_Constant_Narrowing;
361 return NK_Variable_Narrowing;
364 return NK_Not_Narrowing;
366 // -- from an integer type or unscoped enumeration type to an integer type
367 // that cannot represent all the values of the original type, except where
368 // the source is a constant expression and the actual value after
369 // conversion will fit into the target type and will produce the original
370 // value when converted back to the original type.
371 case ICK_Integral_Conversion:
372 IntegralConversion: {
373 assert(FromType->isIntegralOrUnscopedEnumerationType());
374 assert(ToType->isIntegralOrUnscopedEnumerationType());
375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376 const unsigned FromWidth = Ctx.getIntWidth(FromType);
377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378 const unsigned ToWidth = Ctx.getIntWidth(ToType);
380 if (FromWidth > ToWidth ||
381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
383 // Not all values of FromType can be represented in ToType.
384 llvm::APSInt InitializerValue;
385 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387 // Such conversions on variables are always narrowing.
388 return NK_Variable_Narrowing;
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
397 // Add a bit to the InitializerValue so we don't have to worry about
398 // signed vs. unsigned comparisons.
399 InitializerValue = InitializerValue.extend(
400 InitializerValue.getBitWidth() + 1);
401 // Convert the initializer to and from the target width and signed-ness.
402 llvm::APSInt ConvertedValue = InitializerValue;
403 ConvertedValue = ConvertedValue.trunc(ToWidth);
404 ConvertedValue.setIsSigned(ToSigned);
405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406 ConvertedValue.setIsSigned(InitializerValue.isSigned());
407 // If the result is different, this was a narrowing conversion.
408 if (ConvertedValue != InitializerValue)
412 ConstantType = Initializer->getType();
413 ConstantValue = APValue(InitializerValue);
414 return NK_Constant_Narrowing;
417 return NK_Not_Narrowing;
421 // Other kinds of conversions are not narrowings.
422 return NK_Not_Narrowing;
426 /// dump - Print this standard conversion sequence to standard
427 /// error. Useful for debugging overloading issues.
428 void StandardConversionSequence::dump() const {
429 raw_ostream &OS = llvm::errs();
430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
432 OS << GetImplicitConversionName(First);
433 PrintedSomething = true;
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
440 OS << GetImplicitConversionName(Second);
442 if (CopyConstructor) {
443 OS << " (by copy constructor)";
444 } else if (DirectBinding) {
445 OS << " (direct reference binding)";
446 } else if (ReferenceBinding) {
447 OS << " (reference binding)";
449 PrintedSomething = true;
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
456 OS << GetImplicitConversionName(Third);
457 PrintedSomething = true;
460 if (!PrintedSomething) {
461 OS << "No conversions required";
465 /// dump - Print this user-defined conversion sequence to standard
466 /// error. Useful for debugging overloading issues.
467 void UserDefinedConversionSequence::dump() const {
468 raw_ostream &OS = llvm::errs();
469 if (Before.First || Before.Second || Before.Third) {
473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
476 OS << "aggregate initialization";
477 if (After.First || After.Second || After.Third) {
483 /// dump - Print this implicit conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 void ImplicitConversionSequence::dump() const {
486 raw_ostream &OS = llvm::errs();
487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
489 switch (ConversionKind) {
490 case StandardConversion:
491 OS << "Standard conversion: ";
494 case UserDefinedConversion:
495 OS << "User-defined conversion: ";
498 case EllipsisConversion:
499 OS << "Ellipsis conversion";
501 case AmbiguousConversion:
502 OS << "Ambiguous conversion";
505 OS << "Bad conversion";
512 void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
516 void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
528 // Structure used by DeductionFailureInfo to store
529 // template argument information.
530 struct DFIArguments {
531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
534 // Structure used by DeductionFailureInfo to store
535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
541 /// \brief Convert from Sema's representation of template deduction information
542 /// to the form used in overload-candidate information.
544 clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
547 DeductionFailureInfo Result;
548 Result.Result = static_cast<unsigned>(TDK);
549 Result.HasDiagnostic = false;
550 Result.Data = nullptr;
552 case Sema::TDK_Success:
553 case Sema::TDK_Invalid:
554 case Sema::TDK_InstantiationDepth:
555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
559 case Sema::TDK_Incomplete:
560 case Sema::TDK_InvalidExplicitArguments:
561 Result.Data = Info.Param.getOpaqueValue();
564 case Sema::TDK_NonDeducedMismatch: {
565 // FIXME: Should allocate from normal heap so that we can free this later.
566 DFIArguments *Saved = new (Context) DFIArguments;
567 Saved->FirstArg = Info.FirstArg;
568 Saved->SecondArg = Info.SecondArg;
573 case Sema::TDK_Inconsistent:
574 case Sema::TDK_Underqualified: {
575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
577 Saved->Param = Info.Param;
578 Saved->FirstArg = Info.FirstArg;
579 Saved->SecondArg = Info.SecondArg;
584 case Sema::TDK_SubstitutionFailure:
585 Result.Data = Info.take();
586 if (Info.hasSFINAEDiagnostic()) {
587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588 SourceLocation(), PartialDiagnostic::NullDiagnostic());
589 Info.takeSFINAEDiagnostic(*Diag);
590 Result.HasDiagnostic = true;
594 case Sema::TDK_FailedOverloadResolution:
595 Result.Data = Info.Expression;
598 case Sema::TDK_MiscellaneousDeductionFailure:
605 void DeductionFailureInfo::Destroy() {
606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
608 case Sema::TDK_Invalid:
609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
613 case Sema::TDK_InvalidExplicitArguments:
614 case Sema::TDK_FailedOverloadResolution:
617 case Sema::TDK_Inconsistent:
618 case Sema::TDK_Underqualified:
619 case Sema::TDK_NonDeducedMismatch:
620 // FIXME: Destroy the data?
624 case Sema::TDK_SubstitutionFailure:
625 // FIXME: Destroy the template argument list?
627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
634 case Sema::TDK_MiscellaneousDeductionFailure:
639 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
645 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
648 case Sema::TDK_Invalid:
649 case Sema::TDK_InstantiationDepth:
650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
652 case Sema::TDK_SubstitutionFailure:
653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
655 return TemplateParameter();
657 case Sema::TDK_Incomplete:
658 case Sema::TDK_InvalidExplicitArguments:
659 return TemplateParameter::getFromOpaqueValue(Data);
661 case Sema::TDK_Inconsistent:
662 case Sema::TDK_Underqualified:
663 return static_cast<DFIParamWithArguments*>(Data)->Param;
666 case Sema::TDK_MiscellaneousDeductionFailure:
670 return TemplateParameter();
673 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
675 case Sema::TDK_Success:
676 case Sema::TDK_Invalid:
677 case Sema::TDK_InstantiationDepth:
678 case Sema::TDK_TooManyArguments:
679 case Sema::TDK_TooFewArguments:
680 case Sema::TDK_Incomplete:
681 case Sema::TDK_InvalidExplicitArguments:
682 case Sema::TDK_Inconsistent:
683 case Sema::TDK_Underqualified:
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
692 case Sema::TDK_MiscellaneousDeductionFailure:
699 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_SubstitutionFailure:
709 case Sema::TDK_FailedOverloadResolution:
712 case Sema::TDK_Inconsistent:
713 case Sema::TDK_Underqualified:
714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
718 case Sema::TDK_MiscellaneousDeductionFailure:
725 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
728 case Sema::TDK_Invalid:
729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
733 case Sema::TDK_InvalidExplicitArguments:
734 case Sema::TDK_SubstitutionFailure:
735 case Sema::TDK_FailedOverloadResolution:
738 case Sema::TDK_Inconsistent:
739 case Sema::TDK_Underqualified:
740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
744 case Sema::TDK_MiscellaneousDeductionFailure:
751 Expr *DeductionFailureInfo::getExpr() {
752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
759 void OverloadCandidateSet::destroyCandidates() {
760 for (iterator i = begin(), e = end(); i != e; ++i) {
761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
768 void OverloadCandidateSet::clear() {
770 NumInlineSequences = 0;
776 class UnbridgedCastsSet {
781 SmallVector<Entry, 2> Entries;
784 void save(Sema &S, Expr *&E) {
785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786 Entry entry = { &E, E };
787 Entries.push_back(entry);
788 E = S.stripARCUnbridgedCast(E);
792 for (SmallVectorImpl<Entry>::iterator
793 i = Entries.begin(), e = Entries.end(); i != e; ++i)
799 /// checkPlaceholderForOverload - Do any interesting placeholder-like
800 /// preprocessing on the given expression.
802 /// \param unbridgedCasts a collection to which to add unbridged casts;
803 /// without this, they will be immediately diagnosed as errors
805 /// Return true on unrecoverable error.
807 checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
810 // We can't handle overloaded expressions here because overload
811 // resolution might reasonably tweak them.
812 if (placeholder->getKind() == BuiltinType::Overload) return false;
814 // If the context potentially accepts unbridged ARC casts, strip
815 // the unbridged cast and add it to the collection for later restoration.
816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
818 unbridgedCasts->save(S, E);
822 // Go ahead and check everything else.
823 ExprResult result = S.CheckPlaceholderExpr(E);
824 if (result.isInvalid())
835 /// checkArgPlaceholdersForOverload - Check a set of call operands for
837 static bool checkArgPlaceholdersForOverload(Sema &S,
839 UnbridgedCastsSet &unbridged) {
840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
847 // IsOverload - Determine whether the given New declaration is an
848 // overload of the declarations in Old. This routine returns false if
849 // New and Old cannot be overloaded, e.g., if New has the same
850 // signature as some function in Old (C++ 1.3.10) or if the Old
851 // declarations aren't functions (or function templates) at all. When
852 // it does return false, MatchedDecl will point to the decl that New
853 // cannot be overloaded with. This decl may be a UsingShadowDecl on
854 // top of the underlying declaration.
856 // Example: Given the following input:
858 // void f(int, float); // #1
859 // void f(int, int); // #2
860 // int f(int, int); // #3
862 // When we process #1, there is no previous declaration of "f",
863 // so IsOverload will not be used.
865 // When we process #2, Old contains only the FunctionDecl for #1. By
866 // comparing the parameter types, we see that #1 and #2 are overloaded
867 // (since they have different signatures), so this routine returns
868 // false; MatchedDecl is unchanged.
870 // When we process #3, Old is an overload set containing #1 and #2. We
871 // compare the signatures of #3 to #1 (they're overloaded, so we do
872 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873 // identical (return types of functions are not part of the
874 // signature), IsOverload returns false and MatchedDecl will be set to
875 // point to the FunctionDecl for #2.
877 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878 // into a class by a using declaration. The rules for whether to hide
879 // shadow declarations ignore some properties which otherwise figure
880 // into a function template's signature.
882 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
886 NamedDecl *OldD = *I;
888 bool OldIsUsingDecl = false;
889 if (isa<UsingShadowDecl>(OldD)) {
890 OldIsUsingDecl = true;
892 // We can always introduce two using declarations into the same
893 // context, even if they have identical signatures.
894 if (NewIsUsingDecl) continue;
896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
899 // If either declaration was introduced by a using declaration,
900 // we'll need to use slightly different rules for matching.
901 // Essentially, these rules are the normal rules, except that
902 // function templates hide function templates with different
903 // return types or template parameter lists.
904 bool UseMemberUsingDeclRules =
905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906 !New->getFriendObjectKind();
908 if (FunctionDecl *OldF = OldD->getAsFunction()) {
909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
910 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
915 if (!isa<FunctionTemplateDecl>(OldD) &&
916 !shouldLinkPossiblyHiddenDecl(*I, New))
922 } else if (isa<UsingDecl>(OldD)) {
923 // We can overload with these, which can show up when doing
924 // redeclaration checks for UsingDecls.
925 assert(Old.getLookupKind() == LookupUsingDeclName);
926 } else if (isa<TagDecl>(OldD)) {
927 // We can always overload with tags by hiding them.
928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
929 // Optimistically assume that an unresolved using decl will
930 // overload; if it doesn't, we'll have to diagnose during
931 // template instantiation.
934 // Only function declarations can be overloaded; object and type
935 // declarations cannot be overloaded.
937 return Ovl_NonFunction;
944 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
945 bool UseUsingDeclRules) {
946 // C++ [basic.start.main]p2: This function shall not be overloaded.
950 // MSVCRT user defined entry points cannot be overloaded.
951 if (New->isMSVCRTEntryPoint())
954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
958 // A function template can be overloaded with other function templates
959 // and with normal (non-template) functions.
960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
963 // Is the function New an overload of the function Old?
964 QualType OldQType = Context.getCanonicalType(Old->getType());
965 QualType NewQType = Context.getCanonicalType(New->getType());
967 // Compare the signatures (C++ 1.3.10) of the two functions to
968 // determine whether they are overloads. If we find any mismatch
969 // in the signature, they are overloads.
971 // If either of these functions is a K&R-style function (no
972 // prototype), then we consider them to have matching signatures.
973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
974 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
980 // The signature of a function includes the types of its
981 // parameters (C++ 1.3.10), which includes the presence or absence
982 // of the ellipsis; see C++ DR 357).
983 if (OldQType != NewQType &&
984 (OldType->getNumParams() != NewType->getNumParams() ||
985 OldType->isVariadic() != NewType->isVariadic() ||
986 !FunctionParamTypesAreEqual(OldType, NewType)))
989 // C++ [temp.over.link]p4:
990 // The signature of a function template consists of its function
991 // signature, its return type and its template parameter list. The names
992 // of the template parameters are significant only for establishing the
993 // relationship between the template parameters and the rest of the
996 // We check the return type and template parameter lists for function
997 // templates first; the remaining checks follow.
999 // However, we don't consider either of these when deciding whether
1000 // a member introduced by a shadow declaration is hidden.
1001 if (!UseUsingDeclRules && NewTemplate &&
1002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003 OldTemplate->getTemplateParameters(),
1004 false, TPL_TemplateMatch) ||
1005 OldType->getReturnType() != NewType->getReturnType()))
1008 // If the function is a class member, its signature includes the
1009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1011 // As part of this, also check whether one of the member functions
1012 // is static, in which case they are not overloads (C++
1013 // 13.1p2). While not part of the definition of the signature,
1014 // this check is important to determine whether these functions
1015 // can be overloaded.
1016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1018 if (OldMethod && NewMethod &&
1019 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1021 if (!UseUsingDeclRules &&
1022 (OldMethod->getRefQualifier() == RQ_None ||
1023 NewMethod->getRefQualifier() == RQ_None)) {
1024 // C++0x [over.load]p2:
1025 // - Member function declarations with the same name and the same
1026 // parameter-type-list as well as member function template
1027 // declarations with the same name, the same parameter-type-list, and
1028 // the same template parameter lists cannot be overloaded if any of
1029 // them, but not all, have a ref-qualifier (8.3.5).
1030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1032 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1037 // We may not have applied the implicit const for a constexpr member
1038 // function yet (because we haven't yet resolved whether this is a static
1039 // or non-static member function). Add it now, on the assumption that this
1040 // is a redeclaration of OldMethod.
1041 unsigned OldQuals = OldMethod->getTypeQualifiers();
1042 unsigned NewQuals = NewMethod->getTypeQualifiers();
1043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1044 !isa<CXXConstructorDecl>(NewMethod))
1045 NewQuals |= Qualifiers::Const;
1047 // We do not allow overloading based off of '__restrict'.
1048 OldQuals &= ~Qualifiers::Restrict;
1049 NewQuals &= ~Qualifiers::Restrict;
1050 if (OldQuals != NewQuals)
1054 // enable_if attributes are an order-sensitive part of the signature.
1055 for (specific_attr_iterator<EnableIfAttr>
1056 NewI = New->specific_attr_begin<EnableIfAttr>(),
1057 NewE = New->specific_attr_end<EnableIfAttr>(),
1058 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1059 OldE = Old->specific_attr_end<EnableIfAttr>();
1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1061 if (NewI == NewE || OldI == OldE)
1063 llvm::FoldingSetNodeID NewID, OldID;
1064 NewI->getCond()->Profile(NewID, Context, true);
1065 OldI->getCond()->Profile(OldID, Context, true);
1070 // The signatures match; this is not an overload.
1074 /// \brief Checks availability of the function depending on the current
1075 /// function context. Inside an unavailable function, unavailability is ignored.
1077 /// \returns true if \arg FD is unavailable and current context is inside
1078 /// an available function, false otherwise.
1079 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1083 /// \brief Tries a user-defined conversion from From to ToType.
1085 /// Produces an implicit conversion sequence for when a standard conversion
1086 /// is not an option. See TryImplicitConversion for more information.
1087 static ImplicitConversionSequence
1088 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1089 bool SuppressUserConversions,
1091 bool InOverloadResolution,
1093 bool AllowObjCWritebackConversion,
1094 bool AllowObjCConversionOnExplicit) {
1095 ImplicitConversionSequence ICS;
1097 if (SuppressUserConversions) {
1098 // We're not in the case above, so there is no conversion that
1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1104 // Attempt user-defined conversion.
1105 OverloadCandidateSet Conversions(From->getExprLoc(),
1106 OverloadCandidateSet::CSK_Normal);
1107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108 Conversions, AllowExplicit,
1109 AllowObjCConversionOnExplicit)) {
1112 ICS.setUserDefined();
1113 ICS.UserDefined.Before.setAsIdentityConversion();
1114 // C++ [over.ics.user]p4:
1115 // A conversion of an expression of class type to the same class
1116 // type is given Exact Match rank, and a conversion of an
1117 // expression of class type to a base class of that type is
1118 // given Conversion rank, in spite of the fact that a copy
1119 // constructor (i.e., a user-defined conversion function) is
1120 // called for those cases.
1121 if (CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1127 if (Constructor->isCopyConstructor() &&
1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1129 // Turn this into a "standard" conversion sequence, so that it
1130 // gets ranked with standard conversion sequences.
1132 ICS.Standard.setAsIdentityConversion();
1133 ICS.Standard.setFromType(From->getType());
1134 ICS.Standard.setAllToTypes(ToType);
1135 ICS.Standard.CopyConstructor = Constructor;
1136 if (ToCanon != FromCanon)
1137 ICS.Standard.Second = ICK_Derived_To_Base;
1144 ICS.Ambiguous.setFromType(From->getType());
1145 ICS.Ambiguous.setToType(ToType);
1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1147 Cand != Conversions.end(); ++Cand)
1149 ICS.Ambiguous.addConversion(Cand->Function);
1153 case OR_No_Viable_Function:
1154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1161 /// TryImplicitConversion - Attempt to perform an implicit conversion
1162 /// from the given expression (Expr) to the given type (ToType). This
1163 /// function returns an implicit conversion sequence that can be used
1164 /// to perform the initialization. Given
1166 /// void f(float f);
1167 /// void g(int i) { f(i); }
1169 /// this routine would produce an implicit conversion sequence to
1170 /// describe the initialization of f from i, which will be a standard
1171 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1172 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1174 /// Note that this routine only determines how the conversion can be
1175 /// performed; it does not actually perform the conversion. As such,
1176 /// it will not produce any diagnostics if no conversion is available,
1177 /// but will instead return an implicit conversion sequence of kind
1178 /// "BadConversion".
1180 /// If @p SuppressUserConversions, then user-defined conversions are
1182 /// If @p AllowExplicit, then explicit user-defined conversions are
1185 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1186 /// writeback conversion, which allows __autoreleasing id* parameters to
1187 /// be initialized with __strong id* or __weak id* arguments.
1188 static ImplicitConversionSequence
1189 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
1192 bool InOverloadResolution,
1194 bool AllowObjCWritebackConversion,
1195 bool AllowObjCConversionOnExplicit) {
1196 ImplicitConversionSequence ICS;
1197 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1203 if (!S.getLangOpts().CPlusPlus) {
1204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1208 // C++ [over.ics.user]p4:
1209 // A conversion of an expression of class type to the same class
1210 // type is given Exact Match rank, and a conversion of an
1211 // expression of class type to a base class of that type is
1212 // given Conversion rank, in spite of the fact that a copy/move
1213 // constructor (i.e., a user-defined conversion function) is
1214 // called for those cases.
1215 QualType FromType = From->getType();
1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1217 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218 S.IsDerivedFrom(FromType, ToType))) {
1220 ICS.Standard.setAsIdentityConversion();
1221 ICS.Standard.setFromType(FromType);
1222 ICS.Standard.setAllToTypes(ToType);
1224 // We don't actually check at this point whether there is a valid
1225 // copy/move constructor, since overloading just assumes that it
1226 // exists. When we actually perform initialization, we'll find the
1227 // appropriate constructor to copy the returned object, if needed.
1228 ICS.Standard.CopyConstructor = nullptr;
1230 // Determine whether this is considered a derived-to-base conversion.
1231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1232 ICS.Standard.Second = ICK_Derived_To_Base;
1237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238 AllowExplicit, InOverloadResolution, CStyle,
1239 AllowObjCWritebackConversion,
1240 AllowObjCConversionOnExplicit);
1243 ImplicitConversionSequence
1244 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1245 bool SuppressUserConversions,
1247 bool InOverloadResolution,
1249 bool AllowObjCWritebackConversion) {
1250 return ::TryImplicitConversion(*this, From, ToType,
1251 SuppressUserConversions, AllowExplicit,
1252 InOverloadResolution, CStyle,
1253 AllowObjCWritebackConversion,
1254 /*AllowObjCConversionOnExplicit=*/false);
1257 /// PerformImplicitConversion - Perform an implicit conversion of the
1258 /// expression From to the type ToType. Returns the
1259 /// converted expression. Flavor is the kind of conversion we're
1260 /// performing, used in the error message. If @p AllowExplicit,
1261 /// explicit user-defined conversions are permitted.
1263 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1264 AssignmentAction Action, bool AllowExplicit) {
1265 ImplicitConversionSequence ICS;
1266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1270 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1271 AssignmentAction Action, bool AllowExplicit,
1272 ImplicitConversionSequence& ICS) {
1273 if (checkPlaceholderForOverload(*this, From))
1276 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277 bool AllowObjCWritebackConversion
1278 = getLangOpts().ObjCAutoRefCount &&
1279 (Action == AA_Passing || Action == AA_Sending);
1280 if (getLangOpts().ObjC1)
1281 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282 ToType, From->getType(), From);
1283 ICS = ::TryImplicitConversion(*this, From, ToType,
1284 /*SuppressUserConversions=*/false,
1286 /*InOverloadResolution=*/false,
1288 AllowObjCWritebackConversion,
1289 /*AllowObjCConversionOnExplicit=*/false);
1290 return PerformImplicitConversion(From, ToType, ICS, Action);
1293 /// \brief Determine whether the conversion from FromType to ToType is a valid
1294 /// conversion that strips "noreturn" off the nested function type.
1295 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296 QualType &ResultTy) {
1297 if (Context.hasSameUnqualifiedType(FromType, ToType))
1300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1301 // where F adds one of the following at most once:
1303 // - a member pointer
1304 // - a block pointer
1305 CanQualType CanTo = Context.getCanonicalType(ToType);
1306 CanQualType CanFrom = Context.getCanonicalType(FromType);
1307 Type::TypeClass TyClass = CanTo->getTypeClass();
1308 if (TyClass != CanFrom->getTypeClass()) return false;
1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1310 if (TyClass == Type::Pointer) {
1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1313 } else if (TyClass == Type::BlockPointer) {
1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1316 } else if (TyClass == Type::MemberPointer) {
1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1323 TyClass = CanTo->getTypeClass();
1324 if (TyClass != CanFrom->getTypeClass()) return false;
1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1331 if (!EInfo.getNoReturn()) return false;
1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1334 assert(QualType(FromFn, 0).isCanonical());
1335 if (QualType(FromFn, 0) != CanTo) return false;
1341 /// \brief Determine whether the conversion from FromType to ToType is a valid
1342 /// vector conversion.
1344 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1346 static bool IsVectorConversion(Sema &S, QualType FromType,
1347 QualType ToType, ImplicitConversionKind &ICK) {
1348 // We need at least one of these types to be a vector type to have a vector
1350 if (!ToType->isVectorType() && !FromType->isVectorType())
1353 // Identical types require no conversions.
1354 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1357 // There are no conversions between extended vector types, only identity.
1358 if (ToType->isExtVectorType()) {
1359 // There are no conversions between extended vector types other than the
1360 // identity conversion.
1361 if (FromType->isExtVectorType())
1364 // Vector splat from any arithmetic type to a vector.
1365 if (FromType->isArithmeticType()) {
1366 ICK = ICK_Vector_Splat;
1371 // We can perform the conversion between vector types in the following cases:
1372 // 1)vector types are equivalent AltiVec and GCC vector types
1373 // 2)lax vector conversions are permitted and the vector types are of the
1375 if (ToType->isVectorType() && FromType->isVectorType()) {
1376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377 S.isLaxVectorConversion(FromType, ToType)) {
1378 ICK = ICK_Vector_Conversion;
1386 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387 bool InOverloadResolution,
1388 StandardConversionSequence &SCS,
1391 /// IsStandardConversion - Determines whether there is a standard
1392 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1393 /// expression From to the type ToType. Standard conversion sequences
1394 /// only consider non-class types; for conversions that involve class
1395 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1396 /// contain the standard conversion sequence required to perform this
1397 /// conversion and this routine will return true. Otherwise, this
1398 /// routine will return false and the value of SCS is unspecified.
1399 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400 bool InOverloadResolution,
1401 StandardConversionSequence &SCS,
1403 bool AllowObjCWritebackConversion) {
1404 QualType FromType = From->getType();
1406 // Standard conversions (C++ [conv])
1407 SCS.setAsIdentityConversion();
1408 SCS.IncompatibleObjC = false;
1409 SCS.setFromType(FromType);
1410 SCS.CopyConstructor = nullptr;
1412 // There are no standard conversions for class types in C++, so
1413 // abort early. When overloading in C, however, we do permit
1414 if (FromType->isRecordType() || ToType->isRecordType()) {
1415 if (S.getLangOpts().CPlusPlus)
1418 // When we're overloading in C, we allow, as standard conversions,
1421 // The first conversion can be an lvalue-to-rvalue conversion,
1422 // array-to-pointer conversion, or function-to-pointer conversion
1425 if (FromType == S.Context.OverloadTy) {
1426 DeclAccessPair AccessPair;
1427 if (FunctionDecl *Fn
1428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1430 // We were able to resolve the address of the overloaded function,
1431 // so we can convert to the type of that function.
1432 FromType = Fn->getType();
1433 SCS.setFromType(FromType);
1435 // we can sometimes resolve &foo<int> regardless of ToType, so check
1436 // if the type matches (identity) or we are converting to bool
1437 if (!S.Context.hasSameUnqualifiedType(
1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1440 // if the function type matches except for [[noreturn]], it's ok
1441 if (!S.IsNoReturnConversion(FromType,
1442 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1443 // otherwise, only a boolean conversion is standard
1444 if (!ToType->isBooleanType())
1448 // Check if the "from" expression is taking the address of an overloaded
1449 // function and recompute the FromType accordingly. Take advantage of the
1450 // fact that non-static member functions *must* have such an address-of
1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1453 if (Method && !Method->isStatic()) {
1454 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1455 "Non-unary operator on non-static member address");
1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1458 "Non-address-of operator on non-static member address");
1459 const Type *ClassType
1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1461 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1462 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1465 "Non-address-of operator for overloaded function expression");
1466 FromType = S.Context.getPointerType(FromType);
1469 // Check that we've computed the proper type after overload resolution.
1470 assert(S.Context.hasSameType(
1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1477 // Lvalue-to-rvalue conversion (C++11 4.1):
1478 // A glvalue (3.10) of a non-function, non-array type T can
1479 // be converted to a prvalue.
1480 bool argIsLValue = From->isGLValue();
1482 !FromType->isFunctionType() && !FromType->isArrayType() &&
1483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1484 SCS.First = ICK_Lvalue_To_Rvalue;
1487 // ... if the lvalue has atomic type, the value has the non-atomic version
1488 // of the type of the lvalue ...
1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1490 FromType = Atomic->getValueType();
1492 // If T is a non-class type, the type of the rvalue is the
1493 // cv-unqualified version of T. Otherwise, the type of the rvalue
1494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1495 // just strip the qualifiers because they don't matter.
1496 FromType = FromType.getUnqualifiedType();
1497 } else if (FromType->isArrayType()) {
1498 // Array-to-pointer conversion (C++ 4.2)
1499 SCS.First = ICK_Array_To_Pointer;
1501 // An lvalue or rvalue of type "array of N T" or "array of unknown
1502 // bound of T" can be converted to an rvalue of type "pointer to
1504 FromType = S.Context.getArrayDecayedType(FromType);
1506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1507 // This conversion is deprecated in C++03 (D.4)
1508 SCS.DeprecatedStringLiteralToCharPtr = true;
1510 // For the purpose of ranking in overload resolution
1511 // (13.3.3.1.1), this conversion is considered an
1512 // array-to-pointer conversion followed by a qualification
1513 // conversion (4.4). (C++ 4.2p2)
1514 SCS.Second = ICK_Identity;
1515 SCS.Third = ICK_Qualification;
1516 SCS.QualificationIncludesObjCLifetime = false;
1517 SCS.setAllToTypes(FromType);
1520 } else if (FromType->isFunctionType() && argIsLValue) {
1521 // Function-to-pointer conversion (C++ 4.3).
1522 SCS.First = ICK_Function_To_Pointer;
1524 // An lvalue of function type T can be converted to an rvalue of
1525 // type "pointer to T." The result is a pointer to the
1526 // function. (C++ 4.3p1).
1527 FromType = S.Context.getPointerType(FromType);
1529 // We don't require any conversions for the first step.
1530 SCS.First = ICK_Identity;
1532 SCS.setToType(0, FromType);
1534 // The second conversion can be an integral promotion, floating
1535 // point promotion, integral conversion, floating point conversion,
1536 // floating-integral conversion, pointer conversion,
1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1538 // For overloading in C, this can also be a "compatible-type"
1540 bool IncompatibleObjC = false;
1541 ImplicitConversionKind SecondICK = ICK_Identity;
1542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1543 // The unqualified versions of the types are the same: there's no
1544 // conversion to do.
1545 SCS.Second = ICK_Identity;
1546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1547 // Integral promotion (C++ 4.5).
1548 SCS.Second = ICK_Integral_Promotion;
1549 FromType = ToType.getUnqualifiedType();
1550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1551 // Floating point promotion (C++ 4.6).
1552 SCS.Second = ICK_Floating_Promotion;
1553 FromType = ToType.getUnqualifiedType();
1554 } else if (S.IsComplexPromotion(FromType, ToType)) {
1555 // Complex promotion (Clang extension)
1556 SCS.Second = ICK_Complex_Promotion;
1557 FromType = ToType.getUnqualifiedType();
1558 } else if (ToType->isBooleanType() &&
1559 (FromType->isArithmeticType() ||
1560 FromType->isAnyPointerType() ||
1561 FromType->isBlockPointerType() ||
1562 FromType->isMemberPointerType() ||
1563 FromType->isNullPtrType())) {
1564 // Boolean conversions (C++ 4.12).
1565 SCS.Second = ICK_Boolean_Conversion;
1566 FromType = S.Context.BoolTy;
1567 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1568 ToType->isIntegralType(S.Context)) {
1569 // Integral conversions (C++ 4.7).
1570 SCS.Second = ICK_Integral_Conversion;
1571 FromType = ToType.getUnqualifiedType();
1572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1573 // Complex conversions (C99 6.3.1.6)
1574 SCS.Second = ICK_Complex_Conversion;
1575 FromType = ToType.getUnqualifiedType();
1576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1578 // Complex-real conversions (C99 6.3.1.7)
1579 SCS.Second = ICK_Complex_Real;
1580 FromType = ToType.getUnqualifiedType();
1581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1582 // Floating point conversions (C++ 4.8).
1583 SCS.Second = ICK_Floating_Conversion;
1584 FromType = ToType.getUnqualifiedType();
1585 } else if ((FromType->isRealFloatingType() &&
1586 ToType->isIntegralType(S.Context)) ||
1587 (FromType->isIntegralOrUnscopedEnumerationType() &&
1588 ToType->isRealFloatingType())) {
1589 // Floating-integral conversions (C++ 4.9).
1590 SCS.Second = ICK_Floating_Integral;
1591 FromType = ToType.getUnqualifiedType();
1592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1593 SCS.Second = ICK_Block_Pointer_Conversion;
1594 } else if (AllowObjCWritebackConversion &&
1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1596 SCS.Second = ICK_Writeback_Conversion;
1597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598 FromType, IncompatibleObjC)) {
1599 // Pointer conversions (C++ 4.10).
1600 SCS.Second = ICK_Pointer_Conversion;
1601 SCS.IncompatibleObjC = IncompatibleObjC;
1602 FromType = FromType.getUnqualifiedType();
1603 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1604 InOverloadResolution, FromType)) {
1605 // Pointer to member conversions (4.11).
1606 SCS.Second = ICK_Pointer_Member;
1607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1608 SCS.Second = SecondICK;
1609 FromType = ToType.getUnqualifiedType();
1610 } else if (!S.getLangOpts().CPlusPlus &&
1611 S.Context.typesAreCompatible(ToType, FromType)) {
1612 // Compatible conversions (Clang extension for C function overloading)
1613 SCS.Second = ICK_Compatible_Conversion;
1614 FromType = ToType.getUnqualifiedType();
1615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1616 // Treat a conversion that strips "noreturn" as an identity conversion.
1617 SCS.Second = ICK_NoReturn_Adjustment;
1618 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1619 InOverloadResolution,
1621 SCS.Second = ICK_TransparentUnionConversion;
1623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1625 // tryAtomicConversion has updated the standard conversion sequence
1628 } else if (ToType->isEventT() &&
1629 From->isIntegerConstantExpr(S.getASTContext()) &&
1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1631 SCS.Second = ICK_Zero_Event_Conversion;
1634 // No second conversion required.
1635 SCS.Second = ICK_Identity;
1637 SCS.setToType(1, FromType);
1641 // The third conversion can be a qualification conversion (C++ 4p1).
1642 bool ObjCLifetimeConversion;
1643 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644 ObjCLifetimeConversion)) {
1645 SCS.Third = ICK_Qualification;
1646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1648 CanonFrom = S.Context.getCanonicalType(FromType);
1649 CanonTo = S.Context.getCanonicalType(ToType);
1651 // No conversion required
1652 SCS.Third = ICK_Identity;
1654 // C++ [over.best.ics]p6:
1655 // [...] Any difference in top-level cv-qualification is
1656 // subsumed by the initialization itself and does not constitute
1657 // a conversion. [...]
1658 CanonFrom = S.Context.getCanonicalType(FromType);
1659 CanonTo = S.Context.getCanonicalType(ToType);
1660 if (CanonFrom.getLocalUnqualifiedType()
1661 == CanonTo.getLocalUnqualifiedType() &&
1662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1664 CanonFrom = CanonTo;
1667 SCS.setToType(2, FromType);
1669 // If we have not converted the argument type to the parameter type,
1670 // this is a bad conversion sequence.
1671 if (CanonFrom != CanonTo)
1678 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1680 bool InOverloadResolution,
1681 StandardConversionSequence &SCS,
1684 const RecordType *UT = ToType->getAsUnionType();
1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1687 // The field to initialize within the transparent union.
1688 RecordDecl *UD = UT->getDecl();
1689 // It's compatible if the expression matches any of the fields.
1690 for (const auto *it : UD->fields()) {
1691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692 CStyle, /*ObjCWritebackConversion=*/false)) {
1693 ToType = it->getType();
1700 /// IsIntegralPromotion - Determines whether the conversion from the
1701 /// expression From (whose potentially-adjusted type is FromType) to
1702 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1703 /// sets PromotedType to the promoted type.
1704 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1705 const BuiltinType *To = ToType->getAs<BuiltinType>();
1706 // All integers are built-in.
1711 // An rvalue of type char, signed char, unsigned char, short int, or
1712 // unsigned short int can be converted to an rvalue of type int if
1713 // int can represent all the values of the source type; otherwise,
1714 // the source rvalue can be converted to an rvalue of type unsigned
1716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717 !FromType->isEnumeralType()) {
1718 if (// We can promote any signed, promotable integer type to an int
1719 (FromType->isSignedIntegerType() ||
1720 // We can promote any unsigned integer type whose size is
1721 // less than int to an int.
1722 (!FromType->isSignedIntegerType() &&
1723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1724 return To->getKind() == BuiltinType::Int;
1727 return To->getKind() == BuiltinType::UInt;
1730 // C++11 [conv.prom]p3:
1731 // A prvalue of an unscoped enumeration type whose underlying type is not
1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1733 // following types that can represent all the values of the enumeration
1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1735 // unsigned int, long int, unsigned long int, long long int, or unsigned
1736 // long long int. If none of the types in that list can represent all the
1737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1738 // type can be converted to an rvalue a prvalue of the extended integer type
1739 // with lowest integer conversion rank (4.13) greater than the rank of long
1740 // long in which all the values of the enumeration can be represented. If
1741 // there are two such extended types, the signed one is chosen.
1742 // C++11 [conv.prom]p4:
1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1744 // can be converted to a prvalue of its underlying type. Moreover, if
1745 // integral promotion can be applied to its underlying type, a prvalue of an
1746 // unscoped enumeration type whose underlying type is fixed can also be
1747 // converted to a prvalue of the promoted underlying type.
1748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1750 // provided for a scoped enumeration.
1751 if (FromEnumType->getDecl()->isScoped())
1754 // We can perform an integral promotion to the underlying type of the enum,
1755 // even if that's not the promoted type. Note that the check for promoting
1756 // the underlying type is based on the type alone, and does not consider
1757 // the bitfield-ness of the actual source expression.
1758 if (FromEnumType->getDecl()->isFixed()) {
1759 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1760 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1761 IsIntegralPromotion(nullptr, Underlying, ToType);
1764 // We have already pre-calculated the promotion type, so this is trivial.
1765 if (ToType->isIntegerType() &&
1766 !RequireCompleteType(From->getLocStart(), FromType, 0))
1767 return Context.hasSameUnqualifiedType(
1768 ToType, FromEnumType->getDecl()->getPromotionType());
1771 // C++0x [conv.prom]p2:
1772 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1773 // to an rvalue a prvalue of the first of the following types that can
1774 // represent all the values of its underlying type: int, unsigned int,
1775 // long int, unsigned long int, long long int, or unsigned long long int.
1776 // If none of the types in that list can represent all the values of its
1777 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1778 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1780 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1781 ToType->isIntegerType()) {
1782 // Determine whether the type we're converting from is signed or
1784 bool FromIsSigned = FromType->isSignedIntegerType();
1785 uint64_t FromSize = Context.getTypeSize(FromType);
1787 // The types we'll try to promote to, in the appropriate
1788 // order. Try each of these types.
1789 QualType PromoteTypes[6] = {
1790 Context.IntTy, Context.UnsignedIntTy,
1791 Context.LongTy, Context.UnsignedLongTy ,
1792 Context.LongLongTy, Context.UnsignedLongLongTy
1794 for (int Idx = 0; Idx < 6; ++Idx) {
1795 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1796 if (FromSize < ToSize ||
1797 (FromSize == ToSize &&
1798 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1799 // We found the type that we can promote to. If this is the
1800 // type we wanted, we have a promotion. Otherwise, no
1802 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1807 // An rvalue for an integral bit-field (9.6) can be converted to an
1808 // rvalue of type int if int can represent all the values of the
1809 // bit-field; otherwise, it can be converted to unsigned int if
1810 // unsigned int can represent all the values of the bit-field. If
1811 // the bit-field is larger yet, no integral promotion applies to
1812 // it. If the bit-field has an enumerated type, it is treated as any
1813 // other value of that type for promotion purposes (C++ 4.5p3).
1814 // FIXME: We should delay checking of bit-fields until we actually perform the
1817 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1818 llvm::APSInt BitWidth;
1819 if (FromType->isIntegralType(Context) &&
1820 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1821 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1822 ToSize = Context.getTypeSize(ToType);
1824 // Are we promoting to an int from a bitfield that fits in an int?
1825 if (BitWidth < ToSize ||
1826 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1827 return To->getKind() == BuiltinType::Int;
1830 // Are we promoting to an unsigned int from an unsigned bitfield
1831 // that fits into an unsigned int?
1832 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1833 return To->getKind() == BuiltinType::UInt;
1841 // An rvalue of type bool can be converted to an rvalue of type int,
1842 // with false becoming zero and true becoming one (C++ 4.5p4).
1843 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1850 /// IsFloatingPointPromotion - Determines whether the conversion from
1851 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1852 /// returns true and sets PromotedType to the promoted type.
1853 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1854 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1855 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1856 /// An rvalue of type float can be converted to an rvalue of type
1857 /// double. (C++ 4.6p1).
1858 if (FromBuiltin->getKind() == BuiltinType::Float &&
1859 ToBuiltin->getKind() == BuiltinType::Double)
1863 // When a float is promoted to double or long double, or a
1864 // double is promoted to long double [...].
1865 if (!getLangOpts().CPlusPlus &&
1866 (FromBuiltin->getKind() == BuiltinType::Float ||
1867 FromBuiltin->getKind() == BuiltinType::Double) &&
1868 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1871 // Half can be promoted to float.
1872 if (!getLangOpts().NativeHalfType &&
1873 FromBuiltin->getKind() == BuiltinType::Half &&
1874 ToBuiltin->getKind() == BuiltinType::Float)
1881 /// \brief Determine if a conversion is a complex promotion.
1883 /// A complex promotion is defined as a complex -> complex conversion
1884 /// where the conversion between the underlying real types is a
1885 /// floating-point or integral promotion.
1886 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1887 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1891 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1895 return IsFloatingPointPromotion(FromComplex->getElementType(),
1896 ToComplex->getElementType()) ||
1897 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1898 ToComplex->getElementType());
1901 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1902 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1903 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1904 /// if non-empty, will be a pointer to ToType that may or may not have
1905 /// the right set of qualifiers on its pointee.
1908 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1909 QualType ToPointee, QualType ToType,
1910 ASTContext &Context,
1911 bool StripObjCLifetime = false) {
1912 assert((FromPtr->getTypeClass() == Type::Pointer ||
1913 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1914 "Invalid similarly-qualified pointer type");
1916 /// Conversions to 'id' subsume cv-qualifier conversions.
1917 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1918 return ToType.getUnqualifiedType();
1920 QualType CanonFromPointee
1921 = Context.getCanonicalType(FromPtr->getPointeeType());
1922 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1923 Qualifiers Quals = CanonFromPointee.getQualifiers();
1925 if (StripObjCLifetime)
1926 Quals.removeObjCLifetime();
1928 // Exact qualifier match -> return the pointer type we're converting to.
1929 if (CanonToPointee.getLocalQualifiers() == Quals) {
1930 // ToType is exactly what we need. Return it.
1931 if (!ToType.isNull())
1932 return ToType.getUnqualifiedType();
1934 // Build a pointer to ToPointee. It has the right qualifiers
1936 if (isa<ObjCObjectPointerType>(ToType))
1937 return Context.getObjCObjectPointerType(ToPointee);
1938 return Context.getPointerType(ToPointee);
1941 // Just build a canonical type that has the right qualifiers.
1942 QualType QualifiedCanonToPointee
1943 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1945 if (isa<ObjCObjectPointerType>(ToType))
1946 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1947 return Context.getPointerType(QualifiedCanonToPointee);
1950 static bool isNullPointerConstantForConversion(Expr *Expr,
1951 bool InOverloadResolution,
1952 ASTContext &Context) {
1953 // Handle value-dependent integral null pointer constants correctly.
1954 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1955 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1956 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1957 return !InOverloadResolution;
1959 return Expr->isNullPointerConstant(Context,
1960 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1961 : Expr::NPC_ValueDependentIsNull);
1964 /// IsPointerConversion - Determines whether the conversion of the
1965 /// expression From, which has the (possibly adjusted) type FromType,
1966 /// can be converted to the type ToType via a pointer conversion (C++
1967 /// 4.10). If so, returns true and places the converted type (that
1968 /// might differ from ToType in its cv-qualifiers at some level) into
1971 /// This routine also supports conversions to and from block pointers
1972 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1973 /// pointers to interfaces. FIXME: Once we've determined the
1974 /// appropriate overloading rules for Objective-C, we may want to
1975 /// split the Objective-C checks into a different routine; however,
1976 /// GCC seems to consider all of these conversions to be pointer
1977 /// conversions, so for now they live here. IncompatibleObjC will be
1978 /// set if the conversion is an allowed Objective-C conversion that
1979 /// should result in a warning.
1980 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1981 bool InOverloadResolution,
1982 QualType& ConvertedType,
1983 bool &IncompatibleObjC) {
1984 IncompatibleObjC = false;
1985 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1989 // Conversion from a null pointer constant to any Objective-C pointer type.
1990 if (ToType->isObjCObjectPointerType() &&
1991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1992 ConvertedType = ToType;
1996 // Blocks: Block pointers can be converted to void*.
1997 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1998 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1999 ConvertedType = ToType;
2002 // Blocks: A null pointer constant can be converted to a block
2004 if (ToType->isBlockPointerType() &&
2005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2006 ConvertedType = ToType;
2010 // If the left-hand-side is nullptr_t, the right side can be a null
2011 // pointer constant.
2012 if (ToType->isNullPtrType() &&
2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2014 ConvertedType = ToType;
2018 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2022 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2023 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2024 ConvertedType = ToType;
2028 // Beyond this point, both types need to be pointers
2029 // , including objective-c pointers.
2030 QualType ToPointeeType = ToTypePtr->getPointeeType();
2031 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2032 !getLangOpts().ObjCAutoRefCount) {
2033 ConvertedType = BuildSimilarlyQualifiedPointerType(
2034 FromType->getAs<ObjCObjectPointerType>(),
2039 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2043 QualType FromPointeeType = FromTypePtr->getPointeeType();
2045 // If the unqualified pointee types are the same, this can't be a
2046 // pointer conversion, so don't do all of the work below.
2047 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2050 // An rvalue of type "pointer to cv T," where T is an object type,
2051 // can be converted to an rvalue of type "pointer to cv void" (C++
2053 if (FromPointeeType->isIncompleteOrObjectType() &&
2054 ToPointeeType->isVoidType()) {
2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2058 /*StripObjCLifetime=*/true);
2062 // MSVC allows implicit function to void* type conversion.
2063 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2064 ToPointeeType->isVoidType()) {
2065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2071 // When we're overloading in C, we allow a special kind of pointer
2072 // conversion for compatible-but-not-identical pointee types.
2073 if (!getLangOpts().CPlusPlus &&
2074 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2081 // C++ [conv.ptr]p3:
2083 // An rvalue of type "pointer to cv D," where D is a class type,
2084 // can be converted to an rvalue of type "pointer to cv B," where
2085 // B is a base class (clause 10) of D. If B is an inaccessible
2086 // (clause 11) or ambiguous (10.2) base class of D, a program that
2087 // necessitates this conversion is ill-formed. The result of the
2088 // conversion is a pointer to the base class sub-object of the
2089 // derived class object. The null pointer value is converted to
2090 // the null pointer value of the destination type.
2092 // Note that we do not check for ambiguity or inaccessibility
2093 // here. That is handled by CheckPointerConversion.
2094 if (getLangOpts().CPlusPlus &&
2095 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2096 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2097 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2098 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2105 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2106 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2116 /// \brief Adopt the given qualifiers for the given type.
2117 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2118 Qualifiers TQs = T.getQualifiers();
2120 // Check whether qualifiers already match.
2124 if (Qs.compatiblyIncludes(TQs))
2125 return Context.getQualifiedType(T, Qs);
2127 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2130 /// isObjCPointerConversion - Determines whether this is an
2131 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2132 /// with the same arguments and return values.
2133 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2134 QualType& ConvertedType,
2135 bool &IncompatibleObjC) {
2136 if (!getLangOpts().ObjC1)
2139 // The set of qualifiers on the type we're converting from.
2140 Qualifiers FromQualifiers = FromType.getQualifiers();
2142 // First, we handle all conversions on ObjC object pointer types.
2143 const ObjCObjectPointerType* ToObjCPtr =
2144 ToType->getAs<ObjCObjectPointerType>();
2145 const ObjCObjectPointerType *FromObjCPtr =
2146 FromType->getAs<ObjCObjectPointerType>();
2148 if (ToObjCPtr && FromObjCPtr) {
2149 // If the pointee types are the same (ignoring qualifications),
2150 // then this is not a pointer conversion.
2151 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2152 FromObjCPtr->getPointeeType()))
2155 // Conversion between Objective-C pointers.
2156 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2157 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2158 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2159 if (getLangOpts().CPlusPlus && LHS && RHS &&
2160 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2161 FromObjCPtr->getPointeeType()))
2163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2164 ToObjCPtr->getPointeeType(),
2166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2170 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2171 // Okay: this is some kind of implicit downcast of Objective-C
2172 // interfaces, which is permitted. However, we're going to
2173 // complain about it.
2174 IncompatibleObjC = true;
2175 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2176 ToObjCPtr->getPointeeType(),
2178 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2182 // Beyond this point, both types need to be C pointers or block pointers.
2183 QualType ToPointeeType;
2184 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2185 ToPointeeType = ToCPtr->getPointeeType();
2186 else if (const BlockPointerType *ToBlockPtr =
2187 ToType->getAs<BlockPointerType>()) {
2188 // Objective C++: We're able to convert from a pointer to any object
2189 // to a block pointer type.
2190 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2191 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2194 ToPointeeType = ToBlockPtr->getPointeeType();
2196 else if (FromType->getAs<BlockPointerType>() &&
2197 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2198 // Objective C++: We're able to convert from a block pointer type to a
2199 // pointer to any object.
2200 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2206 QualType FromPointeeType;
2207 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2208 FromPointeeType = FromCPtr->getPointeeType();
2209 else if (const BlockPointerType *FromBlockPtr =
2210 FromType->getAs<BlockPointerType>())
2211 FromPointeeType = FromBlockPtr->getPointeeType();
2215 // If we have pointers to pointers, recursively check whether this
2216 // is an Objective-C conversion.
2217 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2219 IncompatibleObjC)) {
2220 // We always complain about this conversion.
2221 IncompatibleObjC = true;
2222 ConvertedType = Context.getPointerType(ConvertedType);
2223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2226 // Allow conversion of pointee being objective-c pointer to another one;
2228 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2229 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2230 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2231 IncompatibleObjC)) {
2233 ConvertedType = Context.getPointerType(ConvertedType);
2234 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2238 // If we have pointers to functions or blocks, check whether the only
2239 // differences in the argument and result types are in Objective-C
2240 // pointer conversions. If so, we permit the conversion (but
2241 // complain about it).
2242 const FunctionProtoType *FromFunctionType
2243 = FromPointeeType->getAs<FunctionProtoType>();
2244 const FunctionProtoType *ToFunctionType
2245 = ToPointeeType->getAs<FunctionProtoType>();
2246 if (FromFunctionType && ToFunctionType) {
2247 // If the function types are exactly the same, this isn't an
2248 // Objective-C pointer conversion.
2249 if (Context.getCanonicalType(FromPointeeType)
2250 == Context.getCanonicalType(ToPointeeType))
2253 // Perform the quick checks that will tell us whether these
2254 // function types are obviously different.
2255 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2256 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2257 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2260 bool HasObjCConversion = false;
2261 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2262 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2263 // Okay, the types match exactly. Nothing to do.
2264 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2265 ToFunctionType->getReturnType(),
2266 ConvertedType, IncompatibleObjC)) {
2267 // Okay, we have an Objective-C pointer conversion.
2268 HasObjCConversion = true;
2270 // Function types are too different. Abort.
2274 // Check argument types.
2275 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2276 ArgIdx != NumArgs; ++ArgIdx) {
2277 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2278 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2279 if (Context.getCanonicalType(FromArgType)
2280 == Context.getCanonicalType(ToArgType)) {
2281 // Okay, the types match exactly. Nothing to do.
2282 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2283 ConvertedType, IncompatibleObjC)) {
2284 // Okay, we have an Objective-C pointer conversion.
2285 HasObjCConversion = true;
2287 // Argument types are too different. Abort.
2292 if (HasObjCConversion) {
2293 // We had an Objective-C conversion. Allow this pointer
2294 // conversion, but complain about it.
2295 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2296 IncompatibleObjC = true;
2304 /// \brief Determine whether this is an Objective-C writeback conversion,
2305 /// used for parameter passing when performing automatic reference counting.
2307 /// \param FromType The type we're converting form.
2309 /// \param ToType The type we're converting to.
2311 /// \param ConvertedType The type that will be produced after applying
2312 /// this conversion.
2313 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2314 QualType &ConvertedType) {
2315 if (!getLangOpts().ObjCAutoRefCount ||
2316 Context.hasSameUnqualifiedType(FromType, ToType))
2319 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2321 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2322 ToPointee = ToPointer->getPointeeType();
2326 Qualifiers ToQuals = ToPointee.getQualifiers();
2327 if (!ToPointee->isObjCLifetimeType() ||
2328 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2329 !ToQuals.withoutObjCLifetime().empty())
2332 // Argument must be a pointer to __strong to __weak.
2333 QualType FromPointee;
2334 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2335 FromPointee = FromPointer->getPointeeType();
2339 Qualifiers FromQuals = FromPointee.getQualifiers();
2340 if (!FromPointee->isObjCLifetimeType() ||
2341 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2342 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2345 // Make sure that we have compatible qualifiers.
2346 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2347 if (!ToQuals.compatiblyIncludes(FromQuals))
2350 // Remove qualifiers from the pointee type we're converting from; they
2351 // aren't used in the compatibility check belong, and we'll be adding back
2352 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2353 FromPointee = FromPointee.getUnqualifiedType();
2355 // The unqualified form of the pointee types must be compatible.
2356 ToPointee = ToPointee.getUnqualifiedType();
2357 bool IncompatibleObjC;
2358 if (Context.typesAreCompatible(FromPointee, ToPointee))
2359 FromPointee = ToPointee;
2360 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2364 /// \brief Construct the type we're converting to, which is a pointer to
2365 /// __autoreleasing pointee.
2366 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2367 ConvertedType = Context.getPointerType(FromPointee);
2371 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2372 QualType& ConvertedType) {
2373 QualType ToPointeeType;
2374 if (const BlockPointerType *ToBlockPtr =
2375 ToType->getAs<BlockPointerType>())
2376 ToPointeeType = ToBlockPtr->getPointeeType();
2380 QualType FromPointeeType;
2381 if (const BlockPointerType *FromBlockPtr =
2382 FromType->getAs<BlockPointerType>())
2383 FromPointeeType = FromBlockPtr->getPointeeType();
2386 // We have pointer to blocks, check whether the only
2387 // differences in the argument and result types are in Objective-C
2388 // pointer conversions. If so, we permit the conversion.
2390 const FunctionProtoType *FromFunctionType
2391 = FromPointeeType->getAs<FunctionProtoType>();
2392 const FunctionProtoType *ToFunctionType
2393 = ToPointeeType->getAs<FunctionProtoType>();
2395 if (!FromFunctionType || !ToFunctionType)
2398 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2401 // Perform the quick checks that will tell us whether these
2402 // function types are obviously different.
2403 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2404 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2407 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2408 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2409 if (FromEInfo != ToEInfo)
2412 bool IncompatibleObjC = false;
2413 if (Context.hasSameType(FromFunctionType->getReturnType(),
2414 ToFunctionType->getReturnType())) {
2415 // Okay, the types match exactly. Nothing to do.
2417 QualType RHS = FromFunctionType->getReturnType();
2418 QualType LHS = ToFunctionType->getReturnType();
2419 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2420 !RHS.hasQualifiers() && LHS.hasQualifiers())
2421 LHS = LHS.getUnqualifiedType();
2423 if (Context.hasSameType(RHS,LHS)) {
2425 } else if (isObjCPointerConversion(RHS, LHS,
2426 ConvertedType, IncompatibleObjC)) {
2427 if (IncompatibleObjC)
2429 // Okay, we have an Objective-C pointer conversion.
2435 // Check argument types.
2436 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2437 ArgIdx != NumArgs; ++ArgIdx) {
2438 IncompatibleObjC = false;
2439 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2440 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2441 if (Context.hasSameType(FromArgType, ToArgType)) {
2442 // Okay, the types match exactly. Nothing to do.
2443 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2444 ConvertedType, IncompatibleObjC)) {
2445 if (IncompatibleObjC)
2447 // Okay, we have an Objective-C pointer conversion.
2449 // Argument types are too different. Abort.
2452 if (LangOpts.ObjCAutoRefCount &&
2453 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2457 ConvertedType = ToType;
2465 ft_parameter_mismatch,
2467 ft_qualifer_mismatch
2470 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2471 /// function types. Catches different number of parameter, mismatch in
2472 /// parameter types, and different return types.
2473 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2474 QualType FromType, QualType ToType) {
2475 // If either type is not valid, include no extra info.
2476 if (FromType.isNull() || ToType.isNull()) {
2477 PDiag << ft_default;
2481 // Get the function type from the pointers.
2482 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2483 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2484 *ToMember = ToType->getAs<MemberPointerType>();
2485 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2486 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2487 << QualType(FromMember->getClass(), 0);
2490 FromType = FromMember->getPointeeType();
2491 ToType = ToMember->getPointeeType();
2494 if (FromType->isPointerType())
2495 FromType = FromType->getPointeeType();
2496 if (ToType->isPointerType())
2497 ToType = ToType->getPointeeType();
2499 // Remove references.
2500 FromType = FromType.getNonReferenceType();
2501 ToType = ToType.getNonReferenceType();
2503 // Don't print extra info for non-specialized template functions.
2504 if (FromType->isInstantiationDependentType() &&
2505 !FromType->getAs<TemplateSpecializationType>()) {
2506 PDiag << ft_default;
2510 // No extra info for same types.
2511 if (Context.hasSameType(FromType, ToType)) {
2512 PDiag << ft_default;
2516 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2517 *ToFunction = ToType->getAs<FunctionProtoType>();
2519 // Both types need to be function types.
2520 if (!FromFunction || !ToFunction) {
2521 PDiag << ft_default;
2525 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2526 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2527 << FromFunction->getNumParams();
2531 // Handle different parameter types.
2533 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2534 PDiag << ft_parameter_mismatch << ArgPos + 1
2535 << ToFunction->getParamType(ArgPos)
2536 << FromFunction->getParamType(ArgPos);
2540 // Handle different return type.
2541 if (!Context.hasSameType(FromFunction->getReturnType(),
2542 ToFunction->getReturnType())) {
2543 PDiag << ft_return_type << ToFunction->getReturnType()
2544 << FromFunction->getReturnType();
2548 unsigned FromQuals = FromFunction->getTypeQuals(),
2549 ToQuals = ToFunction->getTypeQuals();
2550 if (FromQuals != ToQuals) {
2551 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2555 // Unable to find a difference, so add no extra info.
2556 PDiag << ft_default;
2559 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2560 /// for equality of their argument types. Caller has already checked that
2561 /// they have same number of arguments. If the parameters are different,
2562 /// ArgPos will have the parameter index of the first different parameter.
2563 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2564 const FunctionProtoType *NewType,
2566 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2567 N = NewType->param_type_begin(),
2568 E = OldType->param_type_end();
2569 O && (O != E); ++O, ++N) {
2570 if (!Context.hasSameType(O->getUnqualifiedType(),
2571 N->getUnqualifiedType())) {
2573 *ArgPos = O - OldType->param_type_begin();
2580 /// CheckPointerConversion - Check the pointer conversion from the
2581 /// expression From to the type ToType. This routine checks for
2582 /// ambiguous or inaccessible derived-to-base pointer
2583 /// conversions for which IsPointerConversion has already returned
2584 /// true. It returns true and produces a diagnostic if there was an
2585 /// error, or returns false otherwise.
2586 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2588 CXXCastPath& BasePath,
2589 bool IgnoreBaseAccess) {
2590 QualType FromType = From->getType();
2591 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2595 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2596 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2597 Expr::NPCK_ZeroExpression) {
2598 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2599 DiagRuntimeBehavior(From->getExprLoc(), From,
2600 PDiag(diag::warn_impcast_bool_to_null_pointer)
2601 << ToType << From->getSourceRange());
2602 else if (!isUnevaluatedContext())
2603 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2604 << ToType << From->getSourceRange();
2606 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2607 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2608 QualType FromPointeeType = FromPtrType->getPointeeType(),
2609 ToPointeeType = ToPtrType->getPointeeType();
2611 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2612 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2613 // We must have a derived-to-base conversion. Check an
2614 // ambiguous or inaccessible conversion.
2615 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2617 From->getSourceRange(), &BasePath,
2621 // The conversion was successful.
2622 Kind = CK_DerivedToBase;
2625 } else if (const ObjCObjectPointerType *ToPtrType =
2626 ToType->getAs<ObjCObjectPointerType>()) {
2627 if (const ObjCObjectPointerType *FromPtrType =
2628 FromType->getAs<ObjCObjectPointerType>()) {
2629 // Objective-C++ conversions are always okay.
2630 // FIXME: We should have a different class of conversions for the
2631 // Objective-C++ implicit conversions.
2632 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2634 } else if (FromType->isBlockPointerType()) {
2635 Kind = CK_BlockPointerToObjCPointerCast;
2637 Kind = CK_CPointerToObjCPointerCast;
2639 } else if (ToType->isBlockPointerType()) {
2640 if (!FromType->isBlockPointerType())
2641 Kind = CK_AnyPointerToBlockPointerCast;
2644 // We shouldn't fall into this case unless it's valid for other
2646 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2647 Kind = CK_NullToPointer;
2652 /// IsMemberPointerConversion - Determines whether the conversion of the
2653 /// expression From, which has the (possibly adjusted) type FromType, can be
2654 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2655 /// If so, returns true and places the converted type (that might differ from
2656 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2657 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2659 bool InOverloadResolution,
2660 QualType &ConvertedType) {
2661 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2665 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2666 if (From->isNullPointerConstant(Context,
2667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2668 : Expr::NPC_ValueDependentIsNull)) {
2669 ConvertedType = ToType;
2673 // Otherwise, both types have to be member pointers.
2674 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2678 // A pointer to member of B can be converted to a pointer to member of D,
2679 // where D is derived from B (C++ 4.11p2).
2680 QualType FromClass(FromTypePtr->getClass(), 0);
2681 QualType ToClass(ToTypePtr->getClass(), 0);
2683 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2684 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2685 IsDerivedFrom(ToClass, FromClass)) {
2686 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2687 ToClass.getTypePtr());
2694 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2695 /// expression From to the type ToType. This routine checks for ambiguous or
2696 /// virtual or inaccessible base-to-derived member pointer conversions
2697 /// for which IsMemberPointerConversion has already returned true. It returns
2698 /// true and produces a diagnostic if there was an error, or returns false
2700 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2702 CXXCastPath &BasePath,
2703 bool IgnoreBaseAccess) {
2704 QualType FromType = From->getType();
2705 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2707 // This must be a null pointer to member pointer conversion
2708 assert(From->isNullPointerConstant(Context,
2709 Expr::NPC_ValueDependentIsNull) &&
2710 "Expr must be null pointer constant!");
2711 Kind = CK_NullToMemberPointer;
2715 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2716 assert(ToPtrType && "No member pointer cast has a target type "
2717 "that is not a member pointer.");
2719 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2720 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2722 // FIXME: What about dependent types?
2723 assert(FromClass->isRecordType() && "Pointer into non-class.");
2724 assert(ToClass->isRecordType() && "Pointer into non-class.");
2726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2727 /*DetectVirtual=*/true);
2728 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2729 assert(DerivationOkay &&
2730 "Should not have been called if derivation isn't OK.");
2731 (void)DerivationOkay;
2733 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2734 getUnqualifiedType())) {
2735 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2736 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2737 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2741 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2742 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2743 << FromClass << ToClass << QualType(VBase, 0)
2744 << From->getSourceRange();
2748 if (!IgnoreBaseAccess)
2749 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2751 diag::err_downcast_from_inaccessible_base);
2753 // Must be a base to derived member conversion.
2754 BuildBasePathArray(Paths, BasePath);
2755 Kind = CK_BaseToDerivedMemberPointer;
2759 /// Determine whether the lifetime conversion between the two given
2760 /// qualifiers sets is nontrivial.
2761 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2762 Qualifiers ToQuals) {
2763 // Converting anything to const __unsafe_unretained is trivial.
2764 if (ToQuals.hasConst() &&
2765 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2771 /// IsQualificationConversion - Determines whether the conversion from
2772 /// an rvalue of type FromType to ToType is a qualification conversion
2775 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2776 /// when the qualification conversion involves a change in the Objective-C
2777 /// object lifetime.
2779 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2780 bool CStyle, bool &ObjCLifetimeConversion) {
2781 FromType = Context.getCanonicalType(FromType);
2782 ToType = Context.getCanonicalType(ToType);
2783 ObjCLifetimeConversion = false;
2785 // If FromType and ToType are the same type, this is not a
2786 // qualification conversion.
2787 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2791 // A conversion can add cv-qualifiers at levels other than the first
2792 // in multi-level pointers, subject to the following rules: [...]
2793 bool PreviousToQualsIncludeConst = true;
2794 bool UnwrappedAnyPointer = false;
2795 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2796 // Within each iteration of the loop, we check the qualifiers to
2797 // determine if this still looks like a qualification
2798 // conversion. Then, if all is well, we unwrap one more level of
2799 // pointers or pointers-to-members and do it all again
2800 // until there are no more pointers or pointers-to-members left to
2802 UnwrappedAnyPointer = true;
2804 Qualifiers FromQuals = FromType.getQualifiers();
2805 Qualifiers ToQuals = ToType.getQualifiers();
2808 // Check Objective-C lifetime conversions.
2809 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2810 UnwrappedAnyPointer) {
2811 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2812 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2813 ObjCLifetimeConversion = true;
2814 FromQuals.removeObjCLifetime();
2815 ToQuals.removeObjCLifetime();
2817 // Qualification conversions cannot cast between different
2818 // Objective-C lifetime qualifiers.
2823 // Allow addition/removal of GC attributes but not changing GC attributes.
2824 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2825 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2826 FromQuals.removeObjCGCAttr();
2827 ToQuals.removeObjCGCAttr();
2830 // -- for every j > 0, if const is in cv 1,j then const is in cv
2831 // 2,j, and similarly for volatile.
2832 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2835 // -- if the cv 1,j and cv 2,j are different, then const is in
2836 // every cv for 0 < k < j.
2837 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2838 && !PreviousToQualsIncludeConst)
2841 // Keep track of whether all prior cv-qualifiers in the "to" type
2843 PreviousToQualsIncludeConst
2844 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2847 // We are left with FromType and ToType being the pointee types
2848 // after unwrapping the original FromType and ToType the same number
2849 // of types. If we unwrapped any pointers, and if FromType and
2850 // ToType have the same unqualified type (since we checked
2851 // qualifiers above), then this is a qualification conversion.
2852 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2855 /// \brief - Determine whether this is a conversion from a scalar type to an
2858 /// If successful, updates \c SCS's second and third steps in the conversion
2859 /// sequence to finish the conversion.
2860 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2861 bool InOverloadResolution,
2862 StandardConversionSequence &SCS,
2864 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2868 StandardConversionSequence InnerSCS;
2869 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2870 InOverloadResolution, InnerSCS,
2871 CStyle, /*AllowObjCWritebackConversion=*/false))
2874 SCS.Second = InnerSCS.Second;
2875 SCS.setToType(1, InnerSCS.getToType(1));
2876 SCS.Third = InnerSCS.Third;
2877 SCS.QualificationIncludesObjCLifetime
2878 = InnerSCS.QualificationIncludesObjCLifetime;
2879 SCS.setToType(2, InnerSCS.getToType(2));
2883 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2884 CXXConstructorDecl *Constructor,
2886 const FunctionProtoType *CtorType =
2887 Constructor->getType()->getAs<FunctionProtoType>();
2888 if (CtorType->getNumParams() > 0) {
2889 QualType FirstArg = CtorType->getParamType(0);
2890 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2896 static OverloadingResult
2897 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2899 UserDefinedConversionSequence &User,
2900 OverloadCandidateSet &CandidateSet,
2901 bool AllowExplicit) {
2902 DeclContext::lookup_result R = S.LookupConstructors(To);
2903 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2904 Con != ConEnd; ++Con) {
2905 NamedDecl *D = *Con;
2906 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2908 // Find the constructor (which may be a template).
2909 CXXConstructorDecl *Constructor = nullptr;
2910 FunctionTemplateDecl *ConstructorTmpl
2911 = dyn_cast<FunctionTemplateDecl>(D);
2912 if (ConstructorTmpl)
2914 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2916 Constructor = cast<CXXConstructorDecl>(D);
2918 bool Usable = !Constructor->isInvalidDecl() &&
2919 S.isInitListConstructor(Constructor) &&
2920 (AllowExplicit || !Constructor->isExplicit());
2922 // If the first argument is (a reference to) the target type,
2923 // suppress conversions.
2924 bool SuppressUserConversions =
2925 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2926 if (ConstructorTmpl)
2927 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2928 /*ExplicitArgs*/ nullptr,
2930 SuppressUserConversions);
2932 S.AddOverloadCandidate(Constructor, FoundDecl,
2934 SuppressUserConversions);
2938 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2940 OverloadCandidateSet::iterator Best;
2941 switch (auto Result =
2942 CandidateSet.BestViableFunction(S, From->getLocStart(),
2946 // Record the standard conversion we used and the conversion function.
2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2948 QualType ThisType = Constructor->getThisType(S.Context);
2949 // Initializer lists don't have conversions as such.
2950 User.Before.setAsIdentityConversion();
2951 User.HadMultipleCandidates = HadMultipleCandidates;
2952 User.ConversionFunction = Constructor;
2953 User.FoundConversionFunction = Best->FoundDecl;
2954 User.After.setAsIdentityConversion();
2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2956 User.After.setAllToTypes(ToType);
2960 case OR_No_Viable_Function:
2961 return OR_No_Viable_Function;
2963 return OR_Ambiguous;
2966 llvm_unreachable("Invalid OverloadResult!");
2969 /// Determines whether there is a user-defined conversion sequence
2970 /// (C++ [over.ics.user]) that converts expression From to the type
2971 /// ToType. If such a conversion exists, User will contain the
2972 /// user-defined conversion sequence that performs such a conversion
2973 /// and this routine will return true. Otherwise, this routine returns
2974 /// false and User is unspecified.
2976 /// \param AllowExplicit true if the conversion should consider C++0x
2977 /// "explicit" conversion functions as well as non-explicit conversion
2978 /// functions (C++0x [class.conv.fct]p2).
2980 /// \param AllowObjCConversionOnExplicit true if the conversion should
2981 /// allow an extra Objective-C pointer conversion on uses of explicit
2982 /// constructors. Requires \c AllowExplicit to also be set.
2983 static OverloadingResult
2984 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2985 UserDefinedConversionSequence &User,
2986 OverloadCandidateSet &CandidateSet,
2988 bool AllowObjCConversionOnExplicit) {
2989 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
2991 // Whether we will only visit constructors.
2992 bool ConstructorsOnly = false;
2994 // If the type we are conversion to is a class type, enumerate its
2996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2997 // C++ [over.match.ctor]p1:
2998 // When objects of class type are direct-initialized (8.5), or
2999 // copy-initialized from an expression of the same or a
3000 // derived class type (8.5), overload resolution selects the
3001 // constructor. [...] For copy-initialization, the candidate
3002 // functions are all the converting constructors (12.3.1) of
3003 // that class. The argument list is the expression-list within
3004 // the parentheses of the initializer.
3005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3006 (From->getType()->getAs<RecordType>() &&
3007 S.IsDerivedFrom(From->getType(), ToType)))
3008 ConstructorsOnly = true;
3010 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3011 // RequireCompleteType may have returned true due to some invalid decl
3012 // during template instantiation, but ToType may be complete enough now
3013 // to try to recover.
3014 if (ToType->isIncompleteType()) {
3015 // We're not going to find any constructors.
3016 } else if (CXXRecordDecl *ToRecordDecl
3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3019 Expr **Args = &From;
3020 unsigned NumArgs = 1;
3021 bool ListInitializing = false;
3022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3023 // But first, see if there is an init-list-constructor that will work.
3024 OverloadingResult Result = IsInitializerListConstructorConversion(
3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3026 if (Result != OR_No_Viable_Function)
3029 CandidateSet.clear();
3031 // If we're list-initializing, we pass the individual elements as
3032 // arguments, not the entire list.
3033 Args = InitList->getInits();
3034 NumArgs = InitList->getNumInits();
3035 ListInitializing = true;
3038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3040 Con != ConEnd; ++Con) {
3041 NamedDecl *D = *Con;
3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3044 // Find the constructor (which may be a template).
3045 CXXConstructorDecl *Constructor = nullptr;
3046 FunctionTemplateDecl *ConstructorTmpl
3047 = dyn_cast<FunctionTemplateDecl>(D);
3048 if (ConstructorTmpl)
3050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3052 Constructor = cast<CXXConstructorDecl>(D);
3054 bool Usable = !Constructor->isInvalidDecl();
3055 if (ListInitializing)
3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3060 bool SuppressUserConversions = !ConstructorsOnly;
3061 if (SuppressUserConversions && ListInitializing) {
3062 SuppressUserConversions = false;
3064 // If the first argument is (a reference to) the target type,
3065 // suppress conversions.
3066 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3067 S.Context, Constructor, ToType);
3070 if (ConstructorTmpl)
3071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3072 /*ExplicitArgs*/ nullptr,
3073 llvm::makeArrayRef(Args, NumArgs),
3074 CandidateSet, SuppressUserConversions);
3076 // Allow one user-defined conversion when user specifies a
3077 // From->ToType conversion via an static cast (c-style, etc).
3078 S.AddOverloadCandidate(Constructor, FoundDecl,
3079 llvm::makeArrayRef(Args, NumArgs),
3080 CandidateSet, SuppressUserConversions);
3086 // Enumerate conversion functions, if we're allowed to.
3087 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3089 // No conversion functions from incomplete types.
3090 } else if (const RecordType *FromRecordType
3091 = From->getType()->getAs<RecordType>()) {
3092 if (CXXRecordDecl *FromRecordDecl
3093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3094 // Add all of the conversion functions as candidates.
3095 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3096 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3097 DeclAccessPair FoundDecl = I.getPair();
3098 NamedDecl *D = FoundDecl.getDecl();
3099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3100 if (isa<UsingShadowDecl>(D))
3101 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3103 CXXConversionDecl *Conv;
3104 FunctionTemplateDecl *ConvTemplate;
3105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3108 Conv = cast<CXXConversionDecl>(D);
3110 if (AllowExplicit || !Conv->isExplicit()) {
3112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3113 ActingContext, From, ToType,
3115 AllowObjCConversionOnExplicit);
3117 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3118 From, ToType, CandidateSet,
3119 AllowObjCConversionOnExplicit);
3125 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3127 OverloadCandidateSet::iterator Best;
3128 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3132 // Record the standard conversion we used and the conversion function.
3133 if (CXXConstructorDecl *Constructor
3134 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3135 // C++ [over.ics.user]p1:
3136 // If the user-defined conversion is specified by a
3137 // constructor (12.3.1), the initial standard conversion
3138 // sequence converts the source type to the type required by
3139 // the argument of the constructor.
3141 QualType ThisType = Constructor->getThisType(S.Context);
3142 if (isa<InitListExpr>(From)) {
3143 // Initializer lists don't have conversions as such.
3144 User.Before.setAsIdentityConversion();
3146 if (Best->Conversions[0].isEllipsis())
3147 User.EllipsisConversion = true;
3149 User.Before = Best->Conversions[0].Standard;
3150 User.EllipsisConversion = false;
3153 User.HadMultipleCandidates = HadMultipleCandidates;
3154 User.ConversionFunction = Constructor;
3155 User.FoundConversionFunction = Best->FoundDecl;
3156 User.After.setAsIdentityConversion();
3157 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3158 User.After.setAllToTypes(ToType);
3161 if (CXXConversionDecl *Conversion
3162 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3163 // C++ [over.ics.user]p1:
3165 // [...] If the user-defined conversion is specified by a
3166 // conversion function (12.3.2), the initial standard
3167 // conversion sequence converts the source type to the
3168 // implicit object parameter of the conversion function.
3169 User.Before = Best->Conversions[0].Standard;
3170 User.HadMultipleCandidates = HadMultipleCandidates;
3171 User.ConversionFunction = Conversion;
3172 User.FoundConversionFunction = Best->FoundDecl;
3173 User.EllipsisConversion = false;
3175 // C++ [over.ics.user]p2:
3176 // The second standard conversion sequence converts the
3177 // result of the user-defined conversion to the target type
3178 // for the sequence. Since an implicit conversion sequence
3179 // is an initialization, the special rules for
3180 // initialization by user-defined conversion apply when
3181 // selecting the best user-defined conversion for a
3182 // user-defined conversion sequence (see 13.3.3 and
3184 User.After = Best->FinalConversion;
3187 llvm_unreachable("Not a constructor or conversion function?");
3189 case OR_No_Viable_Function:
3190 return OR_No_Viable_Function;
3193 return OR_Ambiguous;
3196 llvm_unreachable("Invalid OverloadResult!");
3200 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3201 ImplicitConversionSequence ICS;
3202 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3203 OverloadCandidateSet::CSK_Normal);
3204 OverloadingResult OvResult =
3205 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3206 CandidateSet, false, false);
3207 if (OvResult == OR_Ambiguous)
3208 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3209 << From->getType() << ToType << From->getSourceRange();
3210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3211 if (!RequireCompleteType(From->getLocStart(), ToType,
3212 diag::err_typecheck_nonviable_condition_incomplete,
3213 From->getType(), From->getSourceRange()))
3214 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3215 << From->getType() << From->getSourceRange() << ToType;
3218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3222 /// \brief Compare the user-defined conversion functions or constructors
3223 /// of two user-defined conversion sequences to determine whether any ordering
3225 static ImplicitConversionSequence::CompareKind
3226 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3227 FunctionDecl *Function2) {
3228 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3229 return ImplicitConversionSequence::Indistinguishable;
3232 // If both conversion functions are implicitly-declared conversions from
3233 // a lambda closure type to a function pointer and a block pointer,
3234 // respectively, always prefer the conversion to a function pointer,
3235 // because the function pointer is more lightweight and is more likely
3236 // to keep code working.
3237 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3239 return ImplicitConversionSequence::Indistinguishable;
3241 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3243 return ImplicitConversionSequence::Indistinguishable;
3245 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3246 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3247 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3248 if (Block1 != Block2)
3249 return Block1 ? ImplicitConversionSequence::Worse
3250 : ImplicitConversionSequence::Better;
3253 return ImplicitConversionSequence::Indistinguishable;
3256 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3257 const ImplicitConversionSequence &ICS) {
3258 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3259 (ICS.isUserDefined() &&
3260 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3263 /// CompareImplicitConversionSequences - Compare two implicit
3264 /// conversion sequences to determine whether one is better than the
3265 /// other or if they are indistinguishable (C++ 13.3.3.2).
3266 static ImplicitConversionSequence::CompareKind
3267 CompareImplicitConversionSequences(Sema &S,
3268 const ImplicitConversionSequence& ICS1,
3269 const ImplicitConversionSequence& ICS2)
3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3272 // conversion sequences (as defined in 13.3.3.1)
3273 // -- a standard conversion sequence (13.3.3.1.1) is a better
3274 // conversion sequence than a user-defined conversion sequence or
3275 // an ellipsis conversion sequence, and
3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3277 // conversion sequence than an ellipsis conversion sequence
3280 // C++0x [over.best.ics]p10:
3281 // For the purpose of ranking implicit conversion sequences as
3282 // described in 13.3.3.2, the ambiguous conversion sequence is
3283 // treated as a user-defined sequence that is indistinguishable
3284 // from any other user-defined conversion sequence.
3286 // String literal to 'char *' conversion has been deprecated in C++03. It has
3287 // been removed from C++11. We still accept this conversion, if it happens at
3288 // the best viable function. Otherwise, this conversion is considered worse
3289 // than ellipsis conversion. Consider this as an extension; this is not in the
3290 // standard. For example:
3292 // int &f(...); // #1
3293 // void f(char*); // #2
3294 // void g() { int &r = f("foo"); }
3296 // In C++03, we pick #2 as the best viable function.
3297 // In C++11, we pick #1 as the best viable function, because ellipsis
3298 // conversion is better than string-literal to char* conversion (since there
3299 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3300 // convert arguments, #2 would be the best viable function in C++11.
3301 // If the best viable function has this conversion, a warning will be issued
3302 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3304 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3305 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3306 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3307 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3308 ? ImplicitConversionSequence::Worse
3309 : ImplicitConversionSequence::Better;
3311 if (ICS1.getKindRank() < ICS2.getKindRank())
3312 return ImplicitConversionSequence::Better;
3313 if (ICS2.getKindRank() < ICS1.getKindRank())
3314 return ImplicitConversionSequence::Worse;
3316 // The following checks require both conversion sequences to be of
3318 if (ICS1.getKind() != ICS2.getKind())
3319 return ImplicitConversionSequence::Indistinguishable;
3321 ImplicitConversionSequence::CompareKind Result =
3322 ImplicitConversionSequence::Indistinguishable;
3324 // Two implicit conversion sequences of the same form are
3325 // indistinguishable conversion sequences unless one of the
3326 // following rules apply: (C++ 13.3.3.2p3):
3328 // List-initialization sequence L1 is a better conversion sequence than
3329 // list-initialization sequence L2 if:
3330 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3332 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3333 // and N1 is smaller than N2.,
3334 // even if one of the other rules in this paragraph would otherwise apply.
3335 if (!ICS1.isBad()) {
3336 if (ICS1.isStdInitializerListElement() &&
3337 !ICS2.isStdInitializerListElement())
3338 return ImplicitConversionSequence::Better;
3339 if (!ICS1.isStdInitializerListElement() &&
3340 ICS2.isStdInitializerListElement())
3341 return ImplicitConversionSequence::Worse;
3344 if (ICS1.isStandard())
3345 // Standard conversion sequence S1 is a better conversion sequence than
3346 // standard conversion sequence S2 if [...]
3347 Result = CompareStandardConversionSequences(S,
3348 ICS1.Standard, ICS2.Standard);
3349 else if (ICS1.isUserDefined()) {
3350 // User-defined conversion sequence U1 is a better conversion
3351 // sequence than another user-defined conversion sequence U2 if
3352 // they contain the same user-defined conversion function or
3353 // constructor and if the second standard conversion sequence of
3354 // U1 is better than the second standard conversion sequence of
3355 // U2 (C++ 13.3.3.2p3).
3356 if (ICS1.UserDefined.ConversionFunction ==
3357 ICS2.UserDefined.ConversionFunction)
3358 Result = CompareStandardConversionSequences(S,
3359 ICS1.UserDefined.After,
3360 ICS2.UserDefined.After);
3362 Result = compareConversionFunctions(S,
3363 ICS1.UserDefined.ConversionFunction,
3364 ICS2.UserDefined.ConversionFunction);
3370 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3371 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3373 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3374 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3377 return Context.hasSameUnqualifiedType(T1, T2);
3380 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3381 // determine if one is a proper subset of the other.
3382 static ImplicitConversionSequence::CompareKind
3383 compareStandardConversionSubsets(ASTContext &Context,
3384 const StandardConversionSequence& SCS1,
3385 const StandardConversionSequence& SCS2) {
3386 ImplicitConversionSequence::CompareKind Result
3387 = ImplicitConversionSequence::Indistinguishable;
3389 // the identity conversion sequence is considered to be a subsequence of
3390 // any non-identity conversion sequence
3391 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3392 return ImplicitConversionSequence::Better;
3393 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3394 return ImplicitConversionSequence::Worse;
3396 if (SCS1.Second != SCS2.Second) {
3397 if (SCS1.Second == ICK_Identity)
3398 Result = ImplicitConversionSequence::Better;
3399 else if (SCS2.Second == ICK_Identity)
3400 Result = ImplicitConversionSequence::Worse;
3402 return ImplicitConversionSequence::Indistinguishable;
3403 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3404 return ImplicitConversionSequence::Indistinguishable;
3406 if (SCS1.Third == SCS2.Third) {
3407 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3408 : ImplicitConversionSequence::Indistinguishable;
3411 if (SCS1.Third == ICK_Identity)
3412 return Result == ImplicitConversionSequence::Worse
3413 ? ImplicitConversionSequence::Indistinguishable
3414 : ImplicitConversionSequence::Better;
3416 if (SCS2.Third == ICK_Identity)
3417 return Result == ImplicitConversionSequence::Better
3418 ? ImplicitConversionSequence::Indistinguishable
3419 : ImplicitConversionSequence::Worse;
3421 return ImplicitConversionSequence::Indistinguishable;
3424 /// \brief Determine whether one of the given reference bindings is better
3425 /// than the other based on what kind of bindings they are.
3427 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3428 const StandardConversionSequence &SCS2) {
3429 // C++0x [over.ics.rank]p3b4:
3430 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3431 // implicit object parameter of a non-static member function declared
3432 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3433 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3434 // lvalue reference to a function lvalue and S2 binds an rvalue
3437 // FIXME: Rvalue references. We're going rogue with the above edits,
3438 // because the semantics in the current C++0x working paper (N3225 at the
3439 // time of this writing) break the standard definition of std::forward
3440 // and std::reference_wrapper when dealing with references to functions.
3441 // Proposed wording changes submitted to CWG for consideration.
3442 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3443 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3446 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3447 SCS2.IsLvalueReference) ||
3448 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3449 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3452 /// CompareStandardConversionSequences - Compare two standard
3453 /// conversion sequences to determine whether one is better than the
3454 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3455 static ImplicitConversionSequence::CompareKind
3456 CompareStandardConversionSequences(Sema &S,
3457 const StandardConversionSequence& SCS1,
3458 const StandardConversionSequence& SCS2)
3460 // Standard conversion sequence S1 is a better conversion sequence
3461 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3463 // -- S1 is a proper subsequence of S2 (comparing the conversion
3464 // sequences in the canonical form defined by 13.3.3.1.1,
3465 // excluding any Lvalue Transformation; the identity conversion
3466 // sequence is considered to be a subsequence of any
3467 // non-identity conversion sequence) or, if not that,
3468 if (ImplicitConversionSequence::CompareKind CK
3469 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3472 // -- the rank of S1 is better than the rank of S2 (by the rules
3473 // defined below), or, if not that,
3474 ImplicitConversionRank Rank1 = SCS1.getRank();
3475 ImplicitConversionRank Rank2 = SCS2.getRank();
3477 return ImplicitConversionSequence::Better;
3478 else if (Rank2 < Rank1)
3479 return ImplicitConversionSequence::Worse;
3481 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3482 // are indistinguishable unless one of the following rules
3485 // A conversion that is not a conversion of a pointer, or
3486 // pointer to member, to bool is better than another conversion
3487 // that is such a conversion.
3488 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3489 return SCS2.isPointerConversionToBool()
3490 ? ImplicitConversionSequence::Better
3491 : ImplicitConversionSequence::Worse;
3493 // C++ [over.ics.rank]p4b2:
3495 // If class B is derived directly or indirectly from class A,
3496 // conversion of B* to A* is better than conversion of B* to
3497 // void*, and conversion of A* to void* is better than conversion
3499 bool SCS1ConvertsToVoid
3500 = SCS1.isPointerConversionToVoidPointer(S.Context);
3501 bool SCS2ConvertsToVoid
3502 = SCS2.isPointerConversionToVoidPointer(S.Context);
3503 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3504 // Exactly one of the conversion sequences is a conversion to
3505 // a void pointer; it's the worse conversion.
3506 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3507 : ImplicitConversionSequence::Worse;
3508 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3509 // Neither conversion sequence converts to a void pointer; compare
3510 // their derived-to-base conversions.
3511 if (ImplicitConversionSequence::CompareKind DerivedCK
3512 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3514 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3515 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3516 // Both conversion sequences are conversions to void
3517 // pointers. Compare the source types to determine if there's an
3518 // inheritance relationship in their sources.
3519 QualType FromType1 = SCS1.getFromType();
3520 QualType FromType2 = SCS2.getFromType();
3522 // Adjust the types we're converting from via the array-to-pointer
3523 // conversion, if we need to.
3524 if (SCS1.First == ICK_Array_To_Pointer)
3525 FromType1 = S.Context.getArrayDecayedType(FromType1);
3526 if (SCS2.First == ICK_Array_To_Pointer)
3527 FromType2 = S.Context.getArrayDecayedType(FromType2);
3529 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3530 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3532 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3533 return ImplicitConversionSequence::Better;
3534 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3535 return ImplicitConversionSequence::Worse;
3537 // Objective-C++: If one interface is more specific than the
3538 // other, it is the better one.
3539 const ObjCObjectPointerType* FromObjCPtr1
3540 = FromType1->getAs<ObjCObjectPointerType>();
3541 const ObjCObjectPointerType* FromObjCPtr2
3542 = FromType2->getAs<ObjCObjectPointerType>();
3543 if (FromObjCPtr1 && FromObjCPtr2) {
3544 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3546 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3548 if (AssignLeft != AssignRight) {
3549 return AssignLeft? ImplicitConversionSequence::Better
3550 : ImplicitConversionSequence::Worse;
3555 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3557 if (ImplicitConversionSequence::CompareKind QualCK
3558 = CompareQualificationConversions(S, SCS1, SCS2))
3561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3562 // Check for a better reference binding based on the kind of bindings.
3563 if (isBetterReferenceBindingKind(SCS1, SCS2))
3564 return ImplicitConversionSequence::Better;
3565 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3566 return ImplicitConversionSequence::Worse;
3568 // C++ [over.ics.rank]p3b4:
3569 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3570 // which the references refer are the same type except for
3571 // top-level cv-qualifiers, and the type to which the reference
3572 // initialized by S2 refers is more cv-qualified than the type
3573 // to which the reference initialized by S1 refers.
3574 QualType T1 = SCS1.getToType(2);
3575 QualType T2 = SCS2.getToType(2);
3576 T1 = S.Context.getCanonicalType(T1);
3577 T2 = S.Context.getCanonicalType(T2);
3578 Qualifiers T1Quals, T2Quals;
3579 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3580 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3581 if (UnqualT1 == UnqualT2) {
3582 // Objective-C++ ARC: If the references refer to objects with different
3583 // lifetimes, prefer bindings that don't change lifetime.
3584 if (SCS1.ObjCLifetimeConversionBinding !=
3585 SCS2.ObjCLifetimeConversionBinding) {
3586 return SCS1.ObjCLifetimeConversionBinding
3587 ? ImplicitConversionSequence::Worse
3588 : ImplicitConversionSequence::Better;
3591 // If the type is an array type, promote the element qualifiers to the
3592 // type for comparison.
3593 if (isa<ArrayType>(T1) && T1Quals)
3594 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3595 if (isa<ArrayType>(T2) && T2Quals)
3596 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3597 if (T2.isMoreQualifiedThan(T1))
3598 return ImplicitConversionSequence::Better;
3599 else if (T1.isMoreQualifiedThan(T2))
3600 return ImplicitConversionSequence::Worse;
3604 // In Microsoft mode, prefer an integral conversion to a
3605 // floating-to-integral conversion if the integral conversion
3606 // is between types of the same size.
3614 // Here, MSVC will call f(int) instead of generating a compile error
3615 // as clang will do in standard mode.
3616 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3617 SCS2.Second == ICK_Floating_Integral &&
3618 S.Context.getTypeSize(SCS1.getFromType()) ==
3619 S.Context.getTypeSize(SCS1.getToType(2)))
3620 return ImplicitConversionSequence::Better;
3622 return ImplicitConversionSequence::Indistinguishable;
3625 /// CompareQualificationConversions - Compares two standard conversion
3626 /// sequences to determine whether they can be ranked based on their
3627 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3628 static ImplicitConversionSequence::CompareKind
3629 CompareQualificationConversions(Sema &S,
3630 const StandardConversionSequence& SCS1,
3631 const StandardConversionSequence& SCS2) {
3633 // -- S1 and S2 differ only in their qualification conversion and
3634 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3635 // cv-qualification signature of type T1 is a proper subset of
3636 // the cv-qualification signature of type T2, and S1 is not the
3637 // deprecated string literal array-to-pointer conversion (4.2).
3638 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3639 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3640 return ImplicitConversionSequence::Indistinguishable;
3642 // FIXME: the example in the standard doesn't use a qualification
3644 QualType T1 = SCS1.getToType(2);
3645 QualType T2 = SCS2.getToType(2);
3646 T1 = S.Context.getCanonicalType(T1);
3647 T2 = S.Context.getCanonicalType(T2);
3648 Qualifiers T1Quals, T2Quals;
3649 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3650 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3652 // If the types are the same, we won't learn anything by unwrapped
3654 if (UnqualT1 == UnqualT2)
3655 return ImplicitConversionSequence::Indistinguishable;
3657 // If the type is an array type, promote the element qualifiers to the type
3659 if (isa<ArrayType>(T1) && T1Quals)
3660 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3661 if (isa<ArrayType>(T2) && T2Quals)
3662 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3664 ImplicitConversionSequence::CompareKind Result
3665 = ImplicitConversionSequence::Indistinguishable;
3667 // Objective-C++ ARC:
3668 // Prefer qualification conversions not involving a change in lifetime
3669 // to qualification conversions that do not change lifetime.
3670 if (SCS1.QualificationIncludesObjCLifetime !=
3671 SCS2.QualificationIncludesObjCLifetime) {
3672 Result = SCS1.QualificationIncludesObjCLifetime
3673 ? ImplicitConversionSequence::Worse
3674 : ImplicitConversionSequence::Better;
3677 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3678 // Within each iteration of the loop, we check the qualifiers to
3679 // determine if this still looks like a qualification
3680 // conversion. Then, if all is well, we unwrap one more level of
3681 // pointers or pointers-to-members and do it all again
3682 // until there are no more pointers or pointers-to-members left
3683 // to unwrap. This essentially mimics what
3684 // IsQualificationConversion does, but here we're checking for a
3685 // strict subset of qualifiers.
3686 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3687 // The qualifiers are the same, so this doesn't tell us anything
3688 // about how the sequences rank.
3690 else if (T2.isMoreQualifiedThan(T1)) {
3691 // T1 has fewer qualifiers, so it could be the better sequence.
3692 if (Result == ImplicitConversionSequence::Worse)
3693 // Neither has qualifiers that are a subset of the other's
3695 return ImplicitConversionSequence::Indistinguishable;
3697 Result = ImplicitConversionSequence::Better;
3698 } else if (T1.isMoreQualifiedThan(T2)) {
3699 // T2 has fewer qualifiers, so it could be the better sequence.
3700 if (Result == ImplicitConversionSequence::Better)
3701 // Neither has qualifiers that are a subset of the other's
3703 return ImplicitConversionSequence::Indistinguishable;
3705 Result = ImplicitConversionSequence::Worse;
3707 // Qualifiers are disjoint.
3708 return ImplicitConversionSequence::Indistinguishable;
3711 // If the types after this point are equivalent, we're done.
3712 if (S.Context.hasSameUnqualifiedType(T1, T2))
3716 // Check that the winning standard conversion sequence isn't using
3717 // the deprecated string literal array to pointer conversion.
3719 case ImplicitConversionSequence::Better:
3720 if (SCS1.DeprecatedStringLiteralToCharPtr)
3721 Result = ImplicitConversionSequence::Indistinguishable;
3724 case ImplicitConversionSequence::Indistinguishable:
3727 case ImplicitConversionSequence::Worse:
3728 if (SCS2.DeprecatedStringLiteralToCharPtr)
3729 Result = ImplicitConversionSequence::Indistinguishable;
3736 /// CompareDerivedToBaseConversions - Compares two standard conversion
3737 /// sequences to determine whether they can be ranked based on their
3738 /// various kinds of derived-to-base conversions (C++
3739 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3740 /// conversions between Objective-C interface types.
3741 static ImplicitConversionSequence::CompareKind
3742 CompareDerivedToBaseConversions(Sema &S,
3743 const StandardConversionSequence& SCS1,
3744 const StandardConversionSequence& SCS2) {
3745 QualType FromType1 = SCS1.getFromType();
3746 QualType ToType1 = SCS1.getToType(1);
3747 QualType FromType2 = SCS2.getFromType();
3748 QualType ToType2 = SCS2.getToType(1);
3750 // Adjust the types we're converting from via the array-to-pointer
3751 // conversion, if we need to.
3752 if (SCS1.First == ICK_Array_To_Pointer)
3753 FromType1 = S.Context.getArrayDecayedType(FromType1);
3754 if (SCS2.First == ICK_Array_To_Pointer)
3755 FromType2 = S.Context.getArrayDecayedType(FromType2);
3757 // Canonicalize all of the types.
3758 FromType1 = S.Context.getCanonicalType(FromType1);
3759 ToType1 = S.Context.getCanonicalType(ToType1);
3760 FromType2 = S.Context.getCanonicalType(FromType2);
3761 ToType2 = S.Context.getCanonicalType(ToType2);
3763 // C++ [over.ics.rank]p4b3:
3765 // If class B is derived directly or indirectly from class A and
3766 // class C is derived directly or indirectly from B,
3768 // Compare based on pointer conversions.
3769 if (SCS1.Second == ICK_Pointer_Conversion &&
3770 SCS2.Second == ICK_Pointer_Conversion &&
3771 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3772 FromType1->isPointerType() && FromType2->isPointerType() &&
3773 ToType1->isPointerType() && ToType2->isPointerType()) {
3774 QualType FromPointee1
3775 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3777 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3778 QualType FromPointee2
3779 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3781 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3783 // -- conversion of C* to B* is better than conversion of C* to A*,
3784 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3785 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3786 return ImplicitConversionSequence::Better;
3787 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3788 return ImplicitConversionSequence::Worse;
3791 // -- conversion of B* to A* is better than conversion of C* to A*,
3792 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3793 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3794 return ImplicitConversionSequence::Better;
3795 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3796 return ImplicitConversionSequence::Worse;
3798 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3799 SCS2.Second == ICK_Pointer_Conversion) {
3800 const ObjCObjectPointerType *FromPtr1
3801 = FromType1->getAs<ObjCObjectPointerType>();
3802 const ObjCObjectPointerType *FromPtr2
3803 = FromType2->getAs<ObjCObjectPointerType>();
3804 const ObjCObjectPointerType *ToPtr1
3805 = ToType1->getAs<ObjCObjectPointerType>();
3806 const ObjCObjectPointerType *ToPtr2
3807 = ToType2->getAs<ObjCObjectPointerType>();
3809 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3810 // Apply the same conversion ranking rules for Objective-C pointer types
3811 // that we do for C++ pointers to class types. However, we employ the
3812 // Objective-C pseudo-subtyping relationship used for assignment of
3813 // Objective-C pointer types.
3815 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3816 bool FromAssignRight
3817 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3819 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3821 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3823 // A conversion to an a non-id object pointer type or qualified 'id'
3824 // type is better than a conversion to 'id'.
3825 if (ToPtr1->isObjCIdType() &&
3826 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3827 return ImplicitConversionSequence::Worse;
3828 if (ToPtr2->isObjCIdType() &&
3829 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3830 return ImplicitConversionSequence::Better;
3832 // A conversion to a non-id object pointer type is better than a
3833 // conversion to a qualified 'id' type
3834 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3835 return ImplicitConversionSequence::Worse;
3836 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3837 return ImplicitConversionSequence::Better;
3839 // A conversion to an a non-Class object pointer type or qualified 'Class'
3840 // type is better than a conversion to 'Class'.
3841 if (ToPtr1->isObjCClassType() &&
3842 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3843 return ImplicitConversionSequence::Worse;
3844 if (ToPtr2->isObjCClassType() &&
3845 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3846 return ImplicitConversionSequence::Better;
3848 // A conversion to a non-Class object pointer type is better than a
3849 // conversion to a qualified 'Class' type.
3850 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3851 return ImplicitConversionSequence::Worse;
3852 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3853 return ImplicitConversionSequence::Better;
3855 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3856 if (S.Context.hasSameType(FromType1, FromType2) &&
3857 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3858 (ToAssignLeft != ToAssignRight))
3859 return ToAssignLeft? ImplicitConversionSequence::Worse
3860 : ImplicitConversionSequence::Better;
3862 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3863 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3864 (FromAssignLeft != FromAssignRight))
3865 return FromAssignLeft? ImplicitConversionSequence::Better
3866 : ImplicitConversionSequence::Worse;
3870 // Ranking of member-pointer types.
3871 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3872 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3873 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3874 const MemberPointerType * FromMemPointer1 =
3875 FromType1->getAs<MemberPointerType>();
3876 const MemberPointerType * ToMemPointer1 =
3877 ToType1->getAs<MemberPointerType>();
3878 const MemberPointerType * FromMemPointer2 =
3879 FromType2->getAs<MemberPointerType>();
3880 const MemberPointerType * ToMemPointer2 =
3881 ToType2->getAs<MemberPointerType>();
3882 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3883 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3884 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3885 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3886 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3887 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3888 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3889 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3890 // conversion of A::* to B::* is better than conversion of A::* to C::*,
3891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3892 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3893 return ImplicitConversionSequence::Worse;
3894 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3895 return ImplicitConversionSequence::Better;
3897 // conversion of B::* to C::* is better than conversion of A::* to C::*
3898 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3899 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3900 return ImplicitConversionSequence::Better;
3901 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3902 return ImplicitConversionSequence::Worse;
3906 if (SCS1.Second == ICK_Derived_To_Base) {
3907 // -- conversion of C to B is better than conversion of C to A,
3908 // -- binding of an expression of type C to a reference of type
3909 // B& is better than binding an expression of type C to a
3910 // reference of type A&,
3911 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3912 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3913 if (S.IsDerivedFrom(ToType1, ToType2))
3914 return ImplicitConversionSequence::Better;
3915 else if (S.IsDerivedFrom(ToType2, ToType1))
3916 return ImplicitConversionSequence::Worse;
3919 // -- conversion of B to A is better than conversion of C to A.
3920 // -- binding of an expression of type B to a reference of type
3921 // A& is better than binding an expression of type C to a
3922 // reference of type A&,
3923 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3924 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3925 if (S.IsDerivedFrom(FromType2, FromType1))
3926 return ImplicitConversionSequence::Better;
3927 else if (S.IsDerivedFrom(FromType1, FromType2))
3928 return ImplicitConversionSequence::Worse;
3932 return ImplicitConversionSequence::Indistinguishable;
3935 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3937 static bool isTypeValid(QualType T) {
3938 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3939 return !Record->isInvalidDecl();
3944 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3945 /// determine whether they are reference-related,
3946 /// reference-compatible, reference-compatible with added
3947 /// qualification, or incompatible, for use in C++ initialization by
3948 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3949 /// type, and the first type (T1) is the pointee type of the reference
3950 /// type being initialized.
3951 Sema::ReferenceCompareResult
3952 Sema::CompareReferenceRelationship(SourceLocation Loc,
3953 QualType OrigT1, QualType OrigT2,
3954 bool &DerivedToBase,
3955 bool &ObjCConversion,
3956 bool &ObjCLifetimeConversion) {
3957 assert(!OrigT1->isReferenceType() &&
3958 "T1 must be the pointee type of the reference type");
3959 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3961 QualType T1 = Context.getCanonicalType(OrigT1);
3962 QualType T2 = Context.getCanonicalType(OrigT2);
3963 Qualifiers T1Quals, T2Quals;
3964 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3965 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3967 // C++ [dcl.init.ref]p4:
3968 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3969 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3970 // T1 is a base class of T2.
3971 DerivedToBase = false;
3972 ObjCConversion = false;
3973 ObjCLifetimeConversion = false;
3974 if (UnqualT1 == UnqualT2) {
3976 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
3977 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3978 IsDerivedFrom(UnqualT2, UnqualT1))
3979 DerivedToBase = true;
3980 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3981 UnqualT2->isObjCObjectOrInterfaceType() &&
3982 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3983 ObjCConversion = true;
3985 return Ref_Incompatible;
3987 // At this point, we know that T1 and T2 are reference-related (at
3990 // If the type is an array type, promote the element qualifiers to the type
3992 if (isa<ArrayType>(T1) && T1Quals)
3993 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3994 if (isa<ArrayType>(T2) && T2Quals)
3995 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3997 // C++ [dcl.init.ref]p4:
3998 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3999 // reference-related to T2 and cv1 is the same cv-qualification
4000 // as, or greater cv-qualification than, cv2. For purposes of
4001 // overload resolution, cases for which cv1 is greater
4002 // cv-qualification than cv2 are identified as
4003 // reference-compatible with added qualification (see 13.3.3.2).
4005 // Note that we also require equivalence of Objective-C GC and address-space
4006 // qualifiers when performing these computations, so that e.g., an int in
4007 // address space 1 is not reference-compatible with an int in address
4009 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4010 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4011 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4012 ObjCLifetimeConversion = true;
4014 T1Quals.removeObjCLifetime();
4015 T2Quals.removeObjCLifetime();
4018 if (T1Quals == T2Quals)
4019 return Ref_Compatible;
4020 else if (T1Quals.compatiblyIncludes(T2Quals))
4021 return Ref_Compatible_With_Added_Qualification;
4026 /// \brief Look for a user-defined conversion to an value reference-compatible
4027 /// with DeclType. Return true if something definite is found.
4029 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4030 QualType DeclType, SourceLocation DeclLoc,
4031 Expr *Init, QualType T2, bool AllowRvalues,
4032 bool AllowExplicit) {
4033 assert(T2->isRecordType() && "Can only find conversions of record types.");
4034 CXXRecordDecl *T2RecordDecl
4035 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4037 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4038 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4039 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4041 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4042 if (isa<UsingShadowDecl>(D))
4043 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4045 FunctionTemplateDecl *ConvTemplate
4046 = dyn_cast<FunctionTemplateDecl>(D);
4047 CXXConversionDecl *Conv;
4049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4051 Conv = cast<CXXConversionDecl>(D);
4053 // If this is an explicit conversion, and we're not allowed to consider
4054 // explicit conversions, skip it.
4055 if (!AllowExplicit && Conv->isExplicit())
4059 bool DerivedToBase = false;
4060 bool ObjCConversion = false;
4061 bool ObjCLifetimeConversion = false;
4063 // If we are initializing an rvalue reference, don't permit conversion
4064 // functions that return lvalues.
4065 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4066 const ReferenceType *RefType
4067 = Conv->getConversionType()->getAs<LValueReferenceType>();
4068 if (RefType && !RefType->getPointeeType()->isFunctionType())
4072 if (!ConvTemplate &&
4073 S.CompareReferenceRelationship(
4075 Conv->getConversionType().getNonReferenceType()
4076 .getUnqualifiedType(),
4077 DeclType.getNonReferenceType().getUnqualifiedType(),
4078 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4079 Sema::Ref_Incompatible)
4082 // If the conversion function doesn't return a reference type,
4083 // it can't be considered for this conversion. An rvalue reference
4084 // is only acceptable if its referencee is a function type.
4086 const ReferenceType *RefType =
4087 Conv->getConversionType()->getAs<ReferenceType>();
4089 (!RefType->isLValueReferenceType() &&
4090 !RefType->getPointeeType()->isFunctionType()))
4095 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4096 Init, DeclType, CandidateSet,
4097 /*AllowObjCConversionOnExplicit=*/false);
4099 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4100 DeclType, CandidateSet,
4101 /*AllowObjCConversionOnExplicit=*/false);
4104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4106 OverloadCandidateSet::iterator Best;
4107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4109 // C++ [over.ics.ref]p1:
4111 // [...] If the parameter binds directly to the result of
4112 // applying a conversion function to the argument
4113 // expression, the implicit conversion sequence is a
4114 // user-defined conversion sequence (13.3.3.1.2), with the
4115 // second standard conversion sequence either an identity
4116 // conversion or, if the conversion function returns an
4117 // entity of a type that is a derived class of the parameter
4118 // type, a derived-to-base Conversion.
4119 if (!Best->FinalConversion.DirectBinding)
4122 ICS.setUserDefined();
4123 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4124 ICS.UserDefined.After = Best->FinalConversion;
4125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4126 ICS.UserDefined.ConversionFunction = Best->Function;
4127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4128 ICS.UserDefined.EllipsisConversion = false;
4129 assert(ICS.UserDefined.After.ReferenceBinding &&
4130 ICS.UserDefined.After.DirectBinding &&
4131 "Expected a direct reference binding!");
4136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4137 Cand != CandidateSet.end(); ++Cand)
4139 ICS.Ambiguous.addConversion(Cand->Function);
4142 case OR_No_Viable_Function:
4144 // There was no suitable conversion, or we found a deleted
4145 // conversion; continue with other checks.
4149 llvm_unreachable("Invalid OverloadResult!");
4152 /// \brief Compute an implicit conversion sequence for reference
4154 static ImplicitConversionSequence
4155 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4156 SourceLocation DeclLoc,
4157 bool SuppressUserConversions,
4158 bool AllowExplicit) {
4159 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4161 // Most paths end in a failed conversion.
4162 ImplicitConversionSequence ICS;
4163 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4165 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4166 QualType T2 = Init->getType();
4168 // If the initializer is the address of an overloaded function, try
4169 // to resolve the overloaded function. If all goes well, T2 is the
4170 // type of the resulting function.
4171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4172 DeclAccessPair Found;
4173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4178 // Compute some basic properties of the types and the initializer.
4179 bool isRValRef = DeclType->isRValueReferenceType();
4180 bool DerivedToBase = false;
4181 bool ObjCConversion = false;
4182 bool ObjCLifetimeConversion = false;
4183 Expr::Classification InitCategory = Init->Classify(S.Context);
4184 Sema::ReferenceCompareResult RefRelationship
4185 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4186 ObjCConversion, ObjCLifetimeConversion);
4189 // C++0x [dcl.init.ref]p5:
4190 // A reference to type "cv1 T1" is initialized by an expression
4191 // of type "cv2 T2" as follows:
4193 // -- If reference is an lvalue reference and the initializer expression
4195 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4196 // reference-compatible with "cv2 T2," or
4198 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4199 if (InitCategory.isLValue() &&
4200 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4201 // C++ [over.ics.ref]p1:
4202 // When a parameter of reference type binds directly (8.5.3)
4203 // to an argument expression, the implicit conversion sequence
4204 // is the identity conversion, unless the argument expression
4205 // has a type that is a derived class of the parameter type,
4206 // in which case the implicit conversion sequence is a
4207 // derived-to-base Conversion (13.3.3.1).
4209 ICS.Standard.First = ICK_Identity;
4210 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4211 : ObjCConversion? ICK_Compatible_Conversion
4213 ICS.Standard.Third = ICK_Identity;
4214 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4215 ICS.Standard.setToType(0, T2);
4216 ICS.Standard.setToType(1, T1);
4217 ICS.Standard.setToType(2, T1);
4218 ICS.Standard.ReferenceBinding = true;
4219 ICS.Standard.DirectBinding = true;
4220 ICS.Standard.IsLvalueReference = !isRValRef;
4221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4222 ICS.Standard.BindsToRvalue = false;
4223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4224 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4225 ICS.Standard.CopyConstructor = nullptr;
4226 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4228 // Nothing more to do: the inaccessibility/ambiguity check for
4229 // derived-to-base conversions is suppressed when we're
4230 // computing the implicit conversion sequence (C++
4231 // [over.best.ics]p2).
4235 // -- has a class type (i.e., T2 is a class type), where T1 is
4236 // not reference-related to T2, and can be implicitly
4237 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4238 // is reference-compatible with "cv3 T3" 92) (this
4239 // conversion is selected by enumerating the applicable
4240 // conversion functions (13.3.1.6) and choosing the best
4241 // one through overload resolution (13.3)),
4242 if (!SuppressUserConversions && T2->isRecordType() &&
4243 !S.RequireCompleteType(DeclLoc, T2, 0) &&
4244 RefRelationship == Sema::Ref_Incompatible) {
4245 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4246 Init, T2, /*AllowRvalues=*/false,
4252 // -- Otherwise, the reference shall be an lvalue reference to a
4253 // non-volatile const type (i.e., cv1 shall be const), or the reference
4254 // shall be an rvalue reference.
4255 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4258 // -- If the initializer expression
4260 // -- is an xvalue, class prvalue, array prvalue or function
4261 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4262 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4263 (InitCategory.isXValue() ||
4264 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4265 (InitCategory.isLValue() && T2->isFunctionType()))) {
4267 ICS.Standard.First = ICK_Identity;
4268 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4269 : ObjCConversion? ICK_Compatible_Conversion
4271 ICS.Standard.Third = ICK_Identity;
4272 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4273 ICS.Standard.setToType(0, T2);
4274 ICS.Standard.setToType(1, T1);
4275 ICS.Standard.setToType(2, T1);
4276 ICS.Standard.ReferenceBinding = true;
4277 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4278 // binding unless we're binding to a class prvalue.
4279 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4280 // allow the use of rvalue references in C++98/03 for the benefit of
4281 // standard library implementors; therefore, we need the xvalue check here.
4282 ICS.Standard.DirectBinding =
4283 S.getLangOpts().CPlusPlus11 ||
4284 !(InitCategory.isPRValue() || T2->isRecordType());
4285 ICS.Standard.IsLvalueReference = !isRValRef;
4286 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4287 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4288 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4289 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4290 ICS.Standard.CopyConstructor = nullptr;
4291 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4295 // -- has a class type (i.e., T2 is a class type), where T1 is not
4296 // reference-related to T2, and can be implicitly converted to
4297 // an xvalue, class prvalue, or function lvalue of type
4298 // "cv3 T3", where "cv1 T1" is reference-compatible with
4301 // then the reference is bound to the value of the initializer
4302 // expression in the first case and to the result of the conversion
4303 // in the second case (or, in either case, to an appropriate base
4304 // class subobject).
4305 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4306 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4307 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4308 Init, T2, /*AllowRvalues=*/true,
4310 // In the second case, if the reference is an rvalue reference
4311 // and the second standard conversion sequence of the
4312 // user-defined conversion sequence includes an lvalue-to-rvalue
4313 // conversion, the program is ill-formed.
4314 if (ICS.isUserDefined() && isRValRef &&
4315 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4316 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4321 // A temporary of function type cannot be created; don't even try.
4322 if (T1->isFunctionType())
4325 // -- Otherwise, a temporary of type "cv1 T1" is created and
4326 // initialized from the initializer expression using the
4327 // rules for a non-reference copy initialization (8.5). The
4328 // reference is then bound to the temporary. If T1 is
4329 // reference-related to T2, cv1 must be the same
4330 // cv-qualification as, or greater cv-qualification than,
4331 // cv2; otherwise, the program is ill-formed.
4332 if (RefRelationship == Sema::Ref_Related) {
4333 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4334 // we would be reference-compatible or reference-compatible with
4335 // added qualification. But that wasn't the case, so the reference
4336 // initialization fails.
4338 // Note that we only want to check address spaces and cvr-qualifiers here.
4339 // ObjC GC and lifetime qualifiers aren't important.
4340 Qualifiers T1Quals = T1.getQualifiers();
4341 Qualifiers T2Quals = T2.getQualifiers();
4342 T1Quals.removeObjCGCAttr();
4343 T1Quals.removeObjCLifetime();
4344 T2Quals.removeObjCGCAttr();
4345 T2Quals.removeObjCLifetime();
4346 if (!T1Quals.compatiblyIncludes(T2Quals))
4350 // If at least one of the types is a class type, the types are not
4351 // related, and we aren't allowed any user conversions, the
4352 // reference binding fails. This case is important for breaking
4353 // recursion, since TryImplicitConversion below will attempt to
4354 // create a temporary through the use of a copy constructor.
4355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4356 (T1->isRecordType() || T2->isRecordType()))
4359 // If T1 is reference-related to T2 and the reference is an rvalue
4360 // reference, the initializer expression shall not be an lvalue.
4361 if (RefRelationship >= Sema::Ref_Related &&
4362 isRValRef && Init->Classify(S.Context).isLValue())
4365 // C++ [over.ics.ref]p2:
4366 // When a parameter of reference type is not bound directly to
4367 // an argument expression, the conversion sequence is the one
4368 // required to convert the argument expression to the
4369 // underlying type of the reference according to
4370 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4371 // to copy-initializing a temporary of the underlying type with
4372 // the argument expression. Any difference in top-level
4373 // cv-qualification is subsumed by the initialization itself
4374 // and does not constitute a conversion.
4375 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4376 /*AllowExplicit=*/false,
4377 /*InOverloadResolution=*/false,
4379 /*AllowObjCWritebackConversion=*/false,
4380 /*AllowObjCConversionOnExplicit=*/false);
4382 // Of course, that's still a reference binding.
4383 if (ICS.isStandard()) {
4384 ICS.Standard.ReferenceBinding = true;
4385 ICS.Standard.IsLvalueReference = !isRValRef;
4386 ICS.Standard.BindsToFunctionLvalue = false;
4387 ICS.Standard.BindsToRvalue = true;
4388 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4389 ICS.Standard.ObjCLifetimeConversionBinding = false;
4390 } else if (ICS.isUserDefined()) {
4391 const ReferenceType *LValRefType =
4392 ICS.UserDefined.ConversionFunction->getReturnType()
4393 ->getAs<LValueReferenceType>();
4395 // C++ [over.ics.ref]p3:
4396 // Except for an implicit object parameter, for which see 13.3.1, a
4397 // standard conversion sequence cannot be formed if it requires [...]
4398 // binding an rvalue reference to an lvalue other than a function
4400 // Note that the function case is not possible here.
4401 if (DeclType->isRValueReferenceType() && LValRefType) {
4402 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4403 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4404 // reference to an rvalue!
4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4409 ICS.UserDefined.Before.setAsIdentityConversion();
4410 ICS.UserDefined.After.ReferenceBinding = true;
4411 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4412 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4413 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4414 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4415 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4421 static ImplicitConversionSequence
4422 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4423 bool SuppressUserConversions,
4424 bool InOverloadResolution,
4425 bool AllowObjCWritebackConversion,
4426 bool AllowExplicit = false);
4428 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4429 /// initializer list From.
4430 static ImplicitConversionSequence
4431 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4432 bool SuppressUserConversions,
4433 bool InOverloadResolution,
4434 bool AllowObjCWritebackConversion) {
4435 // C++11 [over.ics.list]p1:
4436 // When an argument is an initializer list, it is not an expression and
4437 // special rules apply for converting it to a parameter type.
4439 ImplicitConversionSequence Result;
4440 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4442 // We need a complete type for what follows. Incomplete types can never be
4443 // initialized from init lists.
4444 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4448 // If the parameter type is a class X and the initializer list has a single
4449 // element of type cv U, where U is X or a class derived from X, the
4450 // implicit conversion sequence is the one required to convert the element
4451 // to the parameter type.
4453 // Otherwise, if the parameter type is a character array [... ]
4454 // and the initializer list has a single element that is an
4455 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4456 // implicit conversion sequence is the identity conversion.
4457 if (From->getNumInits() == 1) {
4458 if (ToType->isRecordType()) {
4459 QualType InitType = From->getInit(0)->getType();
4460 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4461 S.IsDerivedFrom(InitType, ToType))
4462 return TryCopyInitialization(S, From->getInit(0), ToType,
4463 SuppressUserConversions,
4464 InOverloadResolution,
4465 AllowObjCWritebackConversion);
4467 // FIXME: Check the other conditions here: array of character type,
4468 // initializer is a string literal.
4469 if (ToType->isArrayType()) {
4470 InitializedEntity Entity =
4471 InitializedEntity::InitializeParameter(S.Context, ToType,
4472 /*Consumed=*/false);
4473 if (S.CanPerformCopyInitialization(Entity, From)) {
4474 Result.setStandard();
4475 Result.Standard.setAsIdentityConversion();
4476 Result.Standard.setFromType(ToType);
4477 Result.Standard.setAllToTypes(ToType);
4483 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4484 // C++11 [over.ics.list]p2:
4485 // If the parameter type is std::initializer_list<X> or "array of X" and
4486 // all the elements can be implicitly converted to X, the implicit
4487 // conversion sequence is the worst conversion necessary to convert an
4488 // element of the list to X.
4490 // C++14 [over.ics.list]p3:
4491 // Otherwise, if the parameter type is "array of N X", if the initializer
4492 // list has exactly N elements or if it has fewer than N elements and X is
4493 // default-constructible, and if all the elements of the initializer list
4494 // can be implicitly converted to X, the implicit conversion sequence is
4495 // the worst conversion necessary to convert an element of the list to X.
4497 // FIXME: We're missing a lot of these checks.
4498 bool toStdInitializerList = false;
4500 if (ToType->isArrayType())
4501 X = S.Context.getAsArrayType(ToType)->getElementType();
4503 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4505 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4506 Expr *Init = From->getInit(i);
4507 ImplicitConversionSequence ICS =
4508 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4509 InOverloadResolution,
4510 AllowObjCWritebackConversion);
4511 // If a single element isn't convertible, fail.
4516 // Otherwise, look for the worst conversion.
4517 if (Result.isBad() ||
4518 CompareImplicitConversionSequences(S, ICS, Result) ==
4519 ImplicitConversionSequence::Worse)
4523 // For an empty list, we won't have computed any conversion sequence.
4524 // Introduce the identity conversion sequence.
4525 if (From->getNumInits() == 0) {
4526 Result.setStandard();
4527 Result.Standard.setAsIdentityConversion();
4528 Result.Standard.setFromType(ToType);
4529 Result.Standard.setAllToTypes(ToType);
4532 Result.setStdInitializerListElement(toStdInitializerList);
4536 // C++14 [over.ics.list]p4:
4537 // C++11 [over.ics.list]p3:
4538 // Otherwise, if the parameter is a non-aggregate class X and overload
4539 // resolution chooses a single best constructor [...] the implicit
4540 // conversion sequence is a user-defined conversion sequence. If multiple
4541 // constructors are viable but none is better than the others, the
4542 // implicit conversion sequence is a user-defined conversion sequence.
4543 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4544 // This function can deal with initializer lists.
4545 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4546 /*AllowExplicit=*/false,
4547 InOverloadResolution, /*CStyle=*/false,
4548 AllowObjCWritebackConversion,
4549 /*AllowObjCConversionOnExplicit=*/false);
4552 // C++14 [over.ics.list]p5:
4553 // C++11 [over.ics.list]p4:
4554 // Otherwise, if the parameter has an aggregate type which can be
4555 // initialized from the initializer list [...] the implicit conversion
4556 // sequence is a user-defined conversion sequence.
4557 if (ToType->isAggregateType()) {
4558 // Type is an aggregate, argument is an init list. At this point it comes
4559 // down to checking whether the initialization works.
4560 // FIXME: Find out whether this parameter is consumed or not.
4561 InitializedEntity Entity =
4562 InitializedEntity::InitializeParameter(S.Context, ToType,
4563 /*Consumed=*/false);
4564 if (S.CanPerformCopyInitialization(Entity, From)) {
4565 Result.setUserDefined();
4566 Result.UserDefined.Before.setAsIdentityConversion();
4567 // Initializer lists don't have a type.
4568 Result.UserDefined.Before.setFromType(QualType());
4569 Result.UserDefined.Before.setAllToTypes(QualType());
4571 Result.UserDefined.After.setAsIdentityConversion();
4572 Result.UserDefined.After.setFromType(ToType);
4573 Result.UserDefined.After.setAllToTypes(ToType);
4574 Result.UserDefined.ConversionFunction = nullptr;
4579 // C++14 [over.ics.list]p6:
4580 // C++11 [over.ics.list]p5:
4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4582 if (ToType->isReferenceType()) {
4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4584 // mention initializer lists in any way. So we go by what list-
4585 // initialization would do and try to extrapolate from that.
4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4589 // If the initializer list has a single element that is reference-related
4590 // to the parameter type, we initialize the reference from that.
4591 if (From->getNumInits() == 1) {
4592 Expr *Init = From->getInit(0);
4594 QualType T2 = Init->getType();
4596 // If the initializer is the address of an overloaded function, try
4597 // to resolve the overloaded function. If all goes well, T2 is the
4598 // type of the resulting function.
4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4600 DeclAccessPair Found;
4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4602 Init, ToType, false, Found))
4606 // Compute some basic properties of the types and the initializer.
4607 bool dummy1 = false;
4608 bool dummy2 = false;
4609 bool dummy3 = false;
4610 Sema::ReferenceCompareResult RefRelationship
4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4614 if (RefRelationship >= Sema::Ref_Related) {
4615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4616 SuppressUserConversions,
4617 /*AllowExplicit=*/false);
4621 // Otherwise, we bind the reference to a temporary created from the
4622 // initializer list.
4623 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4624 InOverloadResolution,
4625 AllowObjCWritebackConversion);
4626 if (Result.isFailure())
4628 assert(!Result.isEllipsis() &&
4629 "Sub-initialization cannot result in ellipsis conversion.");
4631 // Can we even bind to a temporary?
4632 if (ToType->isRValueReferenceType() ||
4633 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4635 Result.UserDefined.After;
4636 SCS.ReferenceBinding = true;
4637 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4638 SCS.BindsToRvalue = true;
4639 SCS.BindsToFunctionLvalue = false;
4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4641 SCS.ObjCLifetimeConversionBinding = false;
4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4648 // C++14 [over.ics.list]p7:
4649 // C++11 [over.ics.list]p6:
4650 // Otherwise, if the parameter type is not a class:
4651 if (!ToType->isRecordType()) {
4652 // - if the initializer list has one element that is not itself an
4653 // initializer list, the implicit conversion sequence is the one
4654 // required to convert the element to the parameter type.
4655 unsigned NumInits = From->getNumInits();
4656 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4657 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4658 SuppressUserConversions,
4659 InOverloadResolution,
4660 AllowObjCWritebackConversion);
4661 // - if the initializer list has no elements, the implicit conversion
4662 // sequence is the identity conversion.
4663 else if (NumInits == 0) {
4664 Result.setStandard();
4665 Result.Standard.setAsIdentityConversion();
4666 Result.Standard.setFromType(ToType);
4667 Result.Standard.setAllToTypes(ToType);
4672 // C++14 [over.ics.list]p8:
4673 // C++11 [over.ics.list]p7:
4674 // In all cases other than those enumerated above, no conversion is possible
4678 /// TryCopyInitialization - Try to copy-initialize a value of type
4679 /// ToType from the expression From. Return the implicit conversion
4680 /// sequence required to pass this argument, which may be a bad
4681 /// conversion sequence (meaning that the argument cannot be passed to
4682 /// a parameter of this type). If @p SuppressUserConversions, then we
4683 /// do not permit any user-defined conversion sequences.
4684 static ImplicitConversionSequence
4685 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4686 bool SuppressUserConversions,
4687 bool InOverloadResolution,
4688 bool AllowObjCWritebackConversion,
4689 bool AllowExplicit) {
4690 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4691 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4692 InOverloadResolution,AllowObjCWritebackConversion);
4694 if (ToType->isReferenceType())
4695 return TryReferenceInit(S, From, ToType,
4696 /*FIXME:*/From->getLocStart(),
4697 SuppressUserConversions,
4700 return TryImplicitConversion(S, From, ToType,
4701 SuppressUserConversions,
4702 /*AllowExplicit=*/false,
4703 InOverloadResolution,
4705 AllowObjCWritebackConversion,
4706 /*AllowObjCConversionOnExplicit=*/false);
4709 static bool TryCopyInitialization(const CanQualType FromQTy,
4710 const CanQualType ToQTy,
4713 ExprValueKind FromVK) {
4714 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4715 ImplicitConversionSequence ICS =
4716 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4718 return !ICS.isBad();
4721 /// TryObjectArgumentInitialization - Try to initialize the object
4722 /// parameter of the given member function (@c Method) from the
4723 /// expression @p From.
4724 static ImplicitConversionSequence
4725 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4726 Expr::Classification FromClassification,
4727 CXXMethodDecl *Method,
4728 CXXRecordDecl *ActingContext) {
4729 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4730 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4731 // const volatile object.
4732 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4733 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4734 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4736 // Set up the conversion sequence as a "bad" conversion, to allow us
4738 ImplicitConversionSequence ICS;
4740 // We need to have an object of class type.
4741 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4742 FromType = PT->getPointeeType();
4744 // When we had a pointer, it's implicitly dereferenced, so we
4745 // better have an lvalue.
4746 assert(FromClassification.isLValue());
4749 assert(FromType->isRecordType());
4751 // C++0x [over.match.funcs]p4:
4752 // For non-static member functions, the type of the implicit object
4755 // - "lvalue reference to cv X" for functions declared without a
4756 // ref-qualifier or with the & ref-qualifier
4757 // - "rvalue reference to cv X" for functions declared with the &&
4760 // where X is the class of which the function is a member and cv is the
4761 // cv-qualification on the member function declaration.
4763 // However, when finding an implicit conversion sequence for the argument, we
4764 // are not allowed to create temporaries or perform user-defined conversions
4765 // (C++ [over.match.funcs]p5). We perform a simplified version of
4766 // reference binding here, that allows class rvalues to bind to
4767 // non-constant references.
4769 // First check the qualifiers.
4770 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4771 if (ImplicitParamType.getCVRQualifiers()
4772 != FromTypeCanon.getLocalCVRQualifiers() &&
4773 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4774 ICS.setBad(BadConversionSequence::bad_qualifiers,
4775 FromType, ImplicitParamType);
4779 // Check that we have either the same type or a derived type. It
4780 // affects the conversion rank.
4781 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4782 ImplicitConversionKind SecondKind;
4783 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4784 SecondKind = ICK_Identity;
4785 } else if (S.IsDerivedFrom(FromType, ClassType))
4786 SecondKind = ICK_Derived_To_Base;
4788 ICS.setBad(BadConversionSequence::unrelated_class,
4789 FromType, ImplicitParamType);
4793 // Check the ref-qualifier.
4794 switch (Method->getRefQualifier()) {
4796 // Do nothing; we don't care about lvalueness or rvalueness.
4800 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4801 // non-const lvalue reference cannot bind to an rvalue
4802 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4809 if (!FromClassification.isRValue()) {
4810 // rvalue reference cannot bind to an lvalue
4811 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4818 // Success. Mark this as a reference binding.
4820 ICS.Standard.setAsIdentityConversion();
4821 ICS.Standard.Second = SecondKind;
4822 ICS.Standard.setFromType(FromType);
4823 ICS.Standard.setAllToTypes(ImplicitParamType);
4824 ICS.Standard.ReferenceBinding = true;
4825 ICS.Standard.DirectBinding = true;
4826 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4827 ICS.Standard.BindsToFunctionLvalue = false;
4828 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4830 = (Method->getRefQualifier() == RQ_None);
4834 /// PerformObjectArgumentInitialization - Perform initialization of
4835 /// the implicit object parameter for the given Method with the given
4838 Sema::PerformObjectArgumentInitialization(Expr *From,
4839 NestedNameSpecifier *Qualifier,
4840 NamedDecl *FoundDecl,
4841 CXXMethodDecl *Method) {
4842 QualType FromRecordType, DestType;
4843 QualType ImplicitParamRecordType =
4844 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4846 Expr::Classification FromClassification;
4847 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4848 FromRecordType = PT->getPointeeType();
4849 DestType = Method->getThisType(Context);
4850 FromClassification = Expr::Classification::makeSimpleLValue();
4852 FromRecordType = From->getType();
4853 DestType = ImplicitParamRecordType;
4854 FromClassification = From->Classify(Context);
4857 // Note that we always use the true parent context when performing
4858 // the actual argument initialization.
4859 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4860 *this, From->getType(), FromClassification, Method, Method->getParent());
4862 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4863 Qualifiers FromQs = FromRecordType.getQualifiers();
4864 Qualifiers ToQs = DestType.getQualifiers();
4865 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4867 Diag(From->getLocStart(),
4868 diag::err_member_function_call_bad_cvr)
4869 << Method->getDeclName() << FromRecordType << (CVR - 1)
4870 << From->getSourceRange();
4871 Diag(Method->getLocation(), diag::note_previous_decl)
4872 << Method->getDeclName();
4877 return Diag(From->getLocStart(),
4878 diag::err_implicit_object_parameter_init)
4879 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4882 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4883 ExprResult FromRes =
4884 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4885 if (FromRes.isInvalid())
4887 From = FromRes.get();
4890 if (!Context.hasSameType(From->getType(), DestType))
4891 From = ImpCastExprToType(From, DestType, CK_NoOp,
4892 From->getValueKind()).get();
4896 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4897 /// expression From to bool (C++0x [conv]p3).
4898 static ImplicitConversionSequence
4899 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4900 return TryImplicitConversion(S, From, S.Context.BoolTy,
4901 /*SuppressUserConversions=*/false,
4902 /*AllowExplicit=*/true,
4903 /*InOverloadResolution=*/false,
4905 /*AllowObjCWritebackConversion=*/false,
4906 /*AllowObjCConversionOnExplicit=*/false);
4909 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4910 /// of the expression From to bool (C++0x [conv]p3).
4911 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4912 if (checkPlaceholderForOverload(*this, From))
4915 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4917 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4919 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4920 return Diag(From->getLocStart(),
4921 diag::err_typecheck_bool_condition)
4922 << From->getType() << From->getSourceRange();
4926 /// Check that the specified conversion is permitted in a converted constant
4927 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4929 static bool CheckConvertedConstantConversions(Sema &S,
4930 StandardConversionSequence &SCS) {
4931 // Since we know that the target type is an integral or unscoped enumeration
4932 // type, most conversion kinds are impossible. All possible First and Third
4933 // conversions are fine.
4934 switch (SCS.Second) {
4936 case ICK_NoReturn_Adjustment:
4937 case ICK_Integral_Promotion:
4938 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
4941 case ICK_Boolean_Conversion:
4942 // Conversion from an integral or unscoped enumeration type to bool is
4943 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4944 // conversion, so we allow it in a converted constant expression.
4946 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4947 // a lot of popular code. We should at least add a warning for this
4948 // (non-conforming) extension.
4949 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4950 SCS.getToType(2)->isBooleanType();
4952 case ICK_Pointer_Conversion:
4953 case ICK_Pointer_Member:
4954 // C++1z: null pointer conversions and null member pointer conversions are
4955 // only permitted if the source type is std::nullptr_t.
4956 return SCS.getFromType()->isNullPtrType();
4958 case ICK_Floating_Promotion:
4959 case ICK_Complex_Promotion:
4960 case ICK_Floating_Conversion:
4961 case ICK_Complex_Conversion:
4962 case ICK_Floating_Integral:
4963 case ICK_Compatible_Conversion:
4964 case ICK_Derived_To_Base:
4965 case ICK_Vector_Conversion:
4966 case ICK_Vector_Splat:
4967 case ICK_Complex_Real:
4968 case ICK_Block_Pointer_Conversion:
4969 case ICK_TransparentUnionConversion:
4970 case ICK_Writeback_Conversion:
4971 case ICK_Zero_Event_Conversion:
4974 case ICK_Lvalue_To_Rvalue:
4975 case ICK_Array_To_Pointer:
4976 case ICK_Function_To_Pointer:
4977 llvm_unreachable("found a first conversion kind in Second");
4979 case ICK_Qualification:
4980 llvm_unreachable("found a third conversion kind in Second");
4982 case ICK_Num_Conversion_Kinds:
4986 llvm_unreachable("unknown conversion kind");
4989 /// CheckConvertedConstantExpression - Check that the expression From is a
4990 /// converted constant expression of type T, perform the conversion and produce
4991 /// the converted expression, per C++11 [expr.const]p3.
4992 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4993 QualType T, APValue &Value,
4996 assert(S.getLangOpts().CPlusPlus11 &&
4997 "converted constant expression outside C++11");
4999 if (checkPlaceholderForOverload(S, From))
5002 // C++1z [expr.const]p3:
5003 // A converted constant expression of type T is an expression,
5004 // implicitly converted to type T, where the converted
5005 // expression is a constant expression and the implicit conversion
5006 // sequence contains only [... list of conversions ...].
5007 ImplicitConversionSequence ICS =
5008 TryCopyInitialization(S, From, T,
5009 /*SuppressUserConversions=*/false,
5010 /*InOverloadResolution=*/false,
5011 /*AllowObjcWritebackConversion=*/false,
5012 /*AllowExplicit=*/false);
5013 StandardConversionSequence *SCS = nullptr;
5014 switch (ICS.getKind()) {
5015 case ImplicitConversionSequence::StandardConversion:
5016 SCS = &ICS.Standard;
5018 case ImplicitConversionSequence::UserDefinedConversion:
5019 // We are converting to a non-class type, so the Before sequence
5021 SCS = &ICS.UserDefined.After;
5023 case ImplicitConversionSequence::AmbiguousConversion:
5024 case ImplicitConversionSequence::BadConversion:
5025 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5026 return S.Diag(From->getLocStart(),
5027 diag::err_typecheck_converted_constant_expression)
5028 << From->getType() << From->getSourceRange() << T;
5031 case ImplicitConversionSequence::EllipsisConversion:
5032 llvm_unreachable("ellipsis conversion in converted constant expression");
5035 // Check that we would only use permitted conversions.
5036 if (!CheckConvertedConstantConversions(S, *SCS)) {
5037 return S.Diag(From->getLocStart(),
5038 diag::err_typecheck_converted_constant_expression_disallowed)
5039 << From->getType() << From->getSourceRange() << T;
5041 // [...] and where the reference binding (if any) binds directly.
5042 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5043 return S.Diag(From->getLocStart(),
5044 diag::err_typecheck_converted_constant_expression_indirect)
5045 << From->getType() << From->getSourceRange() << T;
5049 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5050 if (Result.isInvalid())
5053 // Check for a narrowing implicit conversion.
5054 APValue PreNarrowingValue;
5055 QualType PreNarrowingType;
5056 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5057 PreNarrowingType)) {
5058 case NK_Variable_Narrowing:
5059 // Implicit conversion to a narrower type, and the value is not a constant
5060 // expression. We'll diagnose this in a moment.
5061 case NK_Not_Narrowing:
5064 case NK_Constant_Narrowing:
5065 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5066 << CCE << /*Constant*/1
5067 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5070 case NK_Type_Narrowing:
5071 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5072 << CCE << /*Constant*/0 << From->getType() << T;
5076 // Check the expression is a constant expression.
5077 SmallVector<PartialDiagnosticAt, 8> Notes;
5078 Expr::EvalResult Eval;
5081 if ((T->isReferenceType()
5082 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5083 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5084 (RequireInt && !Eval.Val.isInt())) {
5085 // The expression can't be folded, so we can't keep it at this position in
5087 Result = ExprError();
5091 if (Notes.empty()) {
5092 // It's a constant expression.
5097 // It's not a constant expression. Produce an appropriate diagnostic.
5098 if (Notes.size() == 1 &&
5099 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5100 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5102 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5103 << CCE << From->getSourceRange();
5104 for (unsigned I = 0; I < Notes.size(); ++I)
5105 S.Diag(Notes[I].first, Notes[I].second);
5110 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5111 APValue &Value, CCEKind CCE) {
5112 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5115 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5116 llvm::APSInt &Value,
5118 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5121 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5128 /// dropPointerConversions - If the given standard conversion sequence
5129 /// involves any pointer conversions, remove them. This may change
5130 /// the result type of the conversion sequence.
5131 static void dropPointerConversion(StandardConversionSequence &SCS) {
5132 if (SCS.Second == ICK_Pointer_Conversion) {
5133 SCS.Second = ICK_Identity;
5134 SCS.Third = ICK_Identity;
5135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5139 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5140 /// convert the expression From to an Objective-C pointer type.
5141 static ImplicitConversionSequence
5142 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5143 // Do an implicit conversion to 'id'.
5144 QualType Ty = S.Context.getObjCIdType();
5145 ImplicitConversionSequence ICS
5146 = TryImplicitConversion(S, From, Ty,
5147 // FIXME: Are these flags correct?
5148 /*SuppressUserConversions=*/false,
5149 /*AllowExplicit=*/true,
5150 /*InOverloadResolution=*/false,
5152 /*AllowObjCWritebackConversion=*/false,
5153 /*AllowObjCConversionOnExplicit=*/true);
5155 // Strip off any final conversions to 'id'.
5156 switch (ICS.getKind()) {
5157 case ImplicitConversionSequence::BadConversion:
5158 case ImplicitConversionSequence::AmbiguousConversion:
5159 case ImplicitConversionSequence::EllipsisConversion:
5162 case ImplicitConversionSequence::UserDefinedConversion:
5163 dropPointerConversion(ICS.UserDefined.After);
5166 case ImplicitConversionSequence::StandardConversion:
5167 dropPointerConversion(ICS.Standard);
5174 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5175 /// conversion of the expression From to an Objective-C pointer type.
5176 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5177 if (checkPlaceholderForOverload(*this, From))
5180 QualType Ty = Context.getObjCIdType();
5181 ImplicitConversionSequence ICS =
5182 TryContextuallyConvertToObjCPointer(*this, From);
5184 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5188 /// Determine whether the provided type is an integral type, or an enumeration
5189 /// type of a permitted flavor.
5190 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5191 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5192 : T->isIntegralOrUnscopedEnumerationType();
5196 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5197 Sema::ContextualImplicitConverter &Converter,
5198 QualType T, UnresolvedSetImpl &ViableConversions) {
5200 if (Converter.Suppress)
5203 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5205 CXXConversionDecl *Conv =
5206 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5207 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5208 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5214 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5215 Sema::ContextualImplicitConverter &Converter,
5216 QualType T, bool HadMultipleCandidates,
5217 UnresolvedSetImpl &ExplicitConversions) {
5218 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5219 DeclAccessPair Found = ExplicitConversions[0];
5220 CXXConversionDecl *Conversion =
5221 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5223 // The user probably meant to invoke the given explicit
5224 // conversion; use it.
5225 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5226 std::string TypeStr;
5227 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5229 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5230 << FixItHint::CreateInsertion(From->getLocStart(),
5231 "static_cast<" + TypeStr + ">(")
5232 << FixItHint::CreateInsertion(
5233 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5234 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5236 // If we aren't in a SFINAE context, build a call to the
5237 // explicit conversion function.
5238 if (SemaRef.isSFINAEContext())
5241 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5242 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5243 HadMultipleCandidates);
5244 if (Result.isInvalid())
5246 // Record usage of conversion in an implicit cast.
5247 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5248 CK_UserDefinedConversion, Result.get(),
5249 nullptr, Result.get()->getValueKind());
5254 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5255 Sema::ContextualImplicitConverter &Converter,
5256 QualType T, bool HadMultipleCandidates,
5257 DeclAccessPair &Found) {
5258 CXXConversionDecl *Conversion =
5259 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5260 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5262 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5263 if (!Converter.SuppressConversion) {
5264 if (SemaRef.isSFINAEContext())
5267 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5268 << From->getSourceRange();
5271 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5272 HadMultipleCandidates);
5273 if (Result.isInvalid())
5275 // Record usage of conversion in an implicit cast.
5276 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5277 CK_UserDefinedConversion, Result.get(),
5278 nullptr, Result.get()->getValueKind());
5282 static ExprResult finishContextualImplicitConversion(
5283 Sema &SemaRef, SourceLocation Loc, Expr *From,
5284 Sema::ContextualImplicitConverter &Converter) {
5285 if (!Converter.match(From->getType()) && !Converter.Suppress)
5286 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5287 << From->getSourceRange();
5289 return SemaRef.DefaultLvalueConversion(From);
5293 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5294 UnresolvedSetImpl &ViableConversions,
5295 OverloadCandidateSet &CandidateSet) {
5296 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5297 DeclAccessPair FoundDecl = ViableConversions[I];
5298 NamedDecl *D = FoundDecl.getDecl();
5299 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5300 if (isa<UsingShadowDecl>(D))
5301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5303 CXXConversionDecl *Conv;
5304 FunctionTemplateDecl *ConvTemplate;
5305 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5306 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5308 Conv = cast<CXXConversionDecl>(D);
5311 SemaRef.AddTemplateConversionCandidate(
5312 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5313 /*AllowObjCConversionOnExplicit=*/false);
5315 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5316 ToType, CandidateSet,
5317 /*AllowObjCConversionOnExplicit=*/false);
5321 /// \brief Attempt to convert the given expression to a type which is accepted
5322 /// by the given converter.
5324 /// This routine will attempt to convert an expression of class type to a
5325 /// type accepted by the specified converter. In C++11 and before, the class
5326 /// must have a single non-explicit conversion function converting to a matching
5327 /// type. In C++1y, there can be multiple such conversion functions, but only
5328 /// one target type.
5330 /// \param Loc The source location of the construct that requires the
5333 /// \param From The expression we're converting from.
5335 /// \param Converter Used to control and diagnose the conversion process.
5337 /// \returns The expression, converted to an integral or enumeration type if
5339 ExprResult Sema::PerformContextualImplicitConversion(
5340 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5341 // We can't perform any more checking for type-dependent expressions.
5342 if (From->isTypeDependent())
5345 // Process placeholders immediately.
5346 if (From->hasPlaceholderType()) {
5347 ExprResult result = CheckPlaceholderExpr(From);
5348 if (result.isInvalid())
5350 From = result.get();
5353 // If the expression already has a matching type, we're golden.
5354 QualType T = From->getType();
5355 if (Converter.match(T))
5356 return DefaultLvalueConversion(From);
5358 // FIXME: Check for missing '()' if T is a function type?
5360 // We can only perform contextual implicit conversions on objects of class
5362 const RecordType *RecordTy = T->getAs<RecordType>();
5363 if (!RecordTy || !getLangOpts().CPlusPlus) {
5364 if (!Converter.Suppress)
5365 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5369 // We must have a complete class type.
5370 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5371 ContextualImplicitConverter &Converter;
5374 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5375 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5377 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5378 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5380 } IncompleteDiagnoser(Converter, From);
5382 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5385 // Look for a conversion to an integral or enumeration type.
5387 ViableConversions; // These are *potentially* viable in C++1y.
5388 UnresolvedSet<4> ExplicitConversions;
5389 const auto &Conversions =
5390 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5392 bool HadMultipleCandidates =
5393 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5395 // To check that there is only one target type, in C++1y:
5397 bool HasUniqueTargetType = true;
5399 // Collect explicit or viable (potentially in C++1y) conversions.
5400 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5401 NamedDecl *D = (*I)->getUnderlyingDecl();
5402 CXXConversionDecl *Conversion;
5403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5405 if (getLangOpts().CPlusPlus14)
5406 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5408 continue; // C++11 does not consider conversion operator templates(?).
5410 Conversion = cast<CXXConversionDecl>(D);
5412 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5413 "Conversion operator templates are considered potentially "
5416 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5417 if (Converter.match(CurToType) || ConvTemplate) {
5419 if (Conversion->isExplicit()) {
5420 // FIXME: For C++1y, do we need this restriction?
5421 // cf. diagnoseNoViableConversion()
5423 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5425 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5426 if (ToType.isNull())
5427 ToType = CurToType.getUnqualifiedType();
5428 else if (HasUniqueTargetType &&
5429 (CurToType.getUnqualifiedType() != ToType))
5430 HasUniqueTargetType = false;
5432 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5437 if (getLangOpts().CPlusPlus14) {
5439 // ... An expression e of class type E appearing in such a context
5440 // is said to be contextually implicitly converted to a specified
5441 // type T and is well-formed if and only if e can be implicitly
5442 // converted to a type T that is determined as follows: E is searched
5443 // for conversion functions whose return type is cv T or reference to
5444 // cv T such that T is allowed by the context. There shall be
5445 // exactly one such T.
5447 // If no unique T is found:
5448 if (ToType.isNull()) {
5449 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5450 HadMultipleCandidates,
5451 ExplicitConversions))
5453 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5456 // If more than one unique Ts are found:
5457 if (!HasUniqueTargetType)
5458 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5461 // If one unique T is found:
5462 // First, build a candidate set from the previously recorded
5463 // potentially viable conversions.
5464 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5465 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5468 // Then, perform overload resolution over the candidate set.
5469 OverloadCandidateSet::iterator Best;
5470 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5472 // Apply this conversion.
5473 DeclAccessPair Found =
5474 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5475 if (recordConversion(*this, Loc, From, Converter, T,
5476 HadMultipleCandidates, Found))
5481 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5483 case OR_No_Viable_Function:
5484 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5485 HadMultipleCandidates,
5486 ExplicitConversions))
5488 // fall through 'OR_Deleted' case.
5490 // We'll complain below about a non-integral condition type.
5494 switch (ViableConversions.size()) {
5496 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5497 HadMultipleCandidates,
5498 ExplicitConversions))
5501 // We'll complain below about a non-integral condition type.
5505 // Apply this conversion.
5506 DeclAccessPair Found = ViableConversions[0];
5507 if (recordConversion(*this, Loc, From, Converter, T,
5508 HadMultipleCandidates, Found))
5513 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5518 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5521 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5522 /// an acceptable non-member overloaded operator for a call whose
5523 /// arguments have types T1 (and, if non-empty, T2). This routine
5524 /// implements the check in C++ [over.match.oper]p3b2 concerning
5525 /// enumeration types.
5526 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5528 ArrayRef<Expr *> Args) {
5529 QualType T1 = Args[0]->getType();
5530 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5538 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5539 if (Proto->getNumParams() < 1)
5542 if (T1->isEnumeralType()) {
5543 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5544 if (Context.hasSameUnqualifiedType(T1, ArgType))
5548 if (Proto->getNumParams() < 2)
5551 if (!T2.isNull() && T2->isEnumeralType()) {
5552 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5553 if (Context.hasSameUnqualifiedType(T2, ArgType))
5560 /// AddOverloadCandidate - Adds the given function to the set of
5561 /// candidate functions, using the given function call arguments. If
5562 /// @p SuppressUserConversions, then don't allow user-defined
5563 /// conversions via constructors or conversion operators.
5565 /// \param PartialOverloading true if we are performing "partial" overloading
5566 /// based on an incomplete set of function arguments. This feature is used by
5567 /// code completion.
5569 Sema::AddOverloadCandidate(FunctionDecl *Function,
5570 DeclAccessPair FoundDecl,
5571 ArrayRef<Expr *> Args,
5572 OverloadCandidateSet &CandidateSet,
5573 bool SuppressUserConversions,
5574 bool PartialOverloading,
5575 bool AllowExplicit) {
5576 const FunctionProtoType *Proto
5577 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5578 assert(Proto && "Functions without a prototype cannot be overloaded");
5579 assert(!Function->getDescribedFunctionTemplate() &&
5580 "Use AddTemplateOverloadCandidate for function templates");
5582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5583 if (!isa<CXXConstructorDecl>(Method)) {
5584 // If we get here, it's because we're calling a member function
5585 // that is named without a member access expression (e.g.,
5586 // "this->f") that was either written explicitly or created
5587 // implicitly. This can happen with a qualified call to a member
5588 // function, e.g., X::f(). We use an empty type for the implied
5589 // object argument (C++ [over.call.func]p3), and the acting context
5591 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5592 QualType(), Expr::Classification::makeSimpleLValue(),
5593 Args, CandidateSet, SuppressUserConversions,
5594 PartialOverloading);
5597 // We treat a constructor like a non-member function, since its object
5598 // argument doesn't participate in overload resolution.
5601 if (!CandidateSet.isNewCandidate(Function))
5604 // C++ [over.match.oper]p3:
5605 // if no operand has a class type, only those non-member functions in the
5606 // lookup set that have a first parameter of type T1 or "reference to
5607 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5608 // is a right operand) a second parameter of type T2 or "reference to
5609 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5610 // candidate functions.
5611 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5612 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5615 // C++11 [class.copy]p11: [DR1402]
5616 // A defaulted move constructor that is defined as deleted is ignored by
5617 // overload resolution.
5618 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5619 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5620 Constructor->isMoveConstructor())
5623 // Overload resolution is always an unevaluated context.
5624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5626 // Add this candidate
5627 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5628 Candidate.FoundDecl = FoundDecl;
5629 Candidate.Function = Function;
5630 Candidate.Viable = true;
5631 Candidate.IsSurrogate = false;
5632 Candidate.IgnoreObjectArgument = false;
5633 Candidate.ExplicitCallArguments = Args.size();
5636 // C++ [class.copy]p3:
5637 // A member function template is never instantiated to perform the copy
5638 // of a class object to an object of its class type.
5639 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5640 if (Args.size() == 1 &&
5641 Constructor->isSpecializationCopyingObject() &&
5642 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5643 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_illegal_constructor;
5650 unsigned NumParams = Proto->getNumParams();
5652 // (C++ 13.3.2p2): A candidate function having fewer than m
5653 // parameters is viable only if it has an ellipsis in its parameter
5655 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5656 !Proto->isVariadic()) {
5657 Candidate.Viable = false;
5658 Candidate.FailureKind = ovl_fail_too_many_arguments;
5662 // (C++ 13.3.2p2): A candidate function having more than m parameters
5663 // is viable only if the (m+1)st parameter has a default argument
5664 // (8.3.6). For the purposes of overload resolution, the
5665 // parameter list is truncated on the right, so that there are
5666 // exactly m parameters.
5667 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5668 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5669 // Not enough arguments.
5670 Candidate.Viable = false;
5671 Candidate.FailureKind = ovl_fail_too_few_arguments;
5675 // (CUDA B.1): Check for invalid calls between targets.
5676 if (getLangOpts().CUDA)
5677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5678 // Skip the check for callers that are implicit members, because in this
5679 // case we may not yet know what the member's target is; the target is
5680 // inferred for the member automatically, based on the bases and fields of
5682 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5683 Candidate.Viable = false;
5684 Candidate.FailureKind = ovl_fail_bad_target;
5688 // Determine the implicit conversion sequences for each of the
5690 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5691 if (ArgIdx < NumParams) {
5692 // (C++ 13.3.2p3): for F to be a viable function, there shall
5693 // exist for each argument an implicit conversion sequence
5694 // (13.3.3.1) that converts that argument to the corresponding
5696 QualType ParamType = Proto->getParamType(ArgIdx);
5697 Candidate.Conversions[ArgIdx]
5698 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5699 SuppressUserConversions,
5700 /*InOverloadResolution=*/true,
5701 /*AllowObjCWritebackConversion=*/
5702 getLangOpts().ObjCAutoRefCount,
5704 if (Candidate.Conversions[ArgIdx].isBad()) {
5705 Candidate.Viable = false;
5706 Candidate.FailureKind = ovl_fail_bad_conversion;
5710 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5711 // argument for which there is no corresponding parameter is
5712 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5713 Candidate.Conversions[ArgIdx].setEllipsis();
5717 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5718 Candidate.Viable = false;
5719 Candidate.FailureKind = ovl_fail_enable_if;
5720 Candidate.DeductionFailure.Data = FailedAttr;
5725 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5727 SmallVector<ObjCMethodDecl*, 4> Methods;
5728 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5731 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5733 ObjCMethodDecl *Method = Methods[b];
5734 unsigned NumNamedArgs = Sel.getNumArgs();
5735 // Method might have more arguments than selector indicates. This is due
5736 // to addition of c-style arguments in method.
5737 if (Method->param_size() > NumNamedArgs)
5738 NumNamedArgs = Method->param_size();
5739 if (Args.size() < NumNamedArgs)
5742 for (unsigned i = 0; i < NumNamedArgs; i++) {
5743 // We can't do any type-checking on a type-dependent argument.
5744 if (Args[i]->isTypeDependent()) {
5749 ParmVarDecl *param = Method->parameters()[i];
5750 Expr *argExpr = Args[i];
5751 assert(argExpr && "SelectBestMethod(): missing expression");
5753 // Strip the unbridged-cast placeholder expression off unless it's
5754 // a consumed argument.
5755 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5756 !param->hasAttr<CFConsumedAttr>())
5757 argExpr = stripARCUnbridgedCast(argExpr);
5759 // If the parameter is __unknown_anytype, move on to the next method.
5760 if (param->getType() == Context.UnknownAnyTy) {
5765 ImplicitConversionSequence ConversionState
5766 = TryCopyInitialization(*this, argExpr, param->getType(),
5767 /*SuppressUserConversions*/false,
5768 /*InOverloadResolution=*/true,
5769 /*AllowObjCWritebackConversion=*/
5770 getLangOpts().ObjCAutoRefCount,
5771 /*AllowExplicit*/false);
5772 if (ConversionState.isBad()) {
5777 // Promote additional arguments to variadic methods.
5778 if (Match && Method->isVariadic()) {
5779 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5780 if (Args[i]->isTypeDependent()) {
5784 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5786 if (Arg.isInvalid()) {
5792 // Check for extra arguments to non-variadic methods.
5793 if (Args.size() != NumNamedArgs)
5795 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5796 // Special case when selectors have no argument. In this case, select
5797 // one with the most general result type of 'id'.
5798 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5799 QualType ReturnT = Methods[b]->getReturnType();
5800 if (ReturnT->isObjCIdType())
5812 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5814 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5815 bool MissingImplicitThis) {
5816 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5817 // we need to find the first failing one.
5818 if (!Function->hasAttrs())
5820 AttrVec Attrs = Function->getAttrs();
5821 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5823 if (Attrs.begin() == E)
5825 std::reverse(Attrs.begin(), E);
5827 SFINAETrap Trap(*this);
5829 // Convert the arguments.
5830 SmallVector<Expr *, 16> ConvertedArgs;
5831 bool InitializationFailed = false;
5832 bool ContainsValueDependentExpr = false;
5833 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5834 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5835 !cast<CXXMethodDecl>(Function)->isStatic() &&
5836 !isa<CXXConstructorDecl>(Function)) {
5837 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5839 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5841 if (R.isInvalid()) {
5842 InitializationFailed = true;
5845 ContainsValueDependentExpr |= R.get()->isValueDependent();
5846 ConvertedArgs.push_back(R.get());
5849 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5851 Function->getParamDecl(i)),
5854 if (R.isInvalid()) {
5855 InitializationFailed = true;
5858 ContainsValueDependentExpr |= R.get()->isValueDependent();
5859 ConvertedArgs.push_back(R.get());
5863 if (InitializationFailed || Trap.hasErrorOccurred())
5864 return cast<EnableIfAttr>(Attrs[0]);
5866 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5868 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5869 if (EIA->getCond()->isValueDependent()) {
5870 // Don't even try now, we'll examine it after instantiation.
5874 if (!EIA->getCond()->EvaluateWithSubstitution(
5875 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5876 if (!ContainsValueDependentExpr)
5878 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
5885 /// \brief Add all of the function declarations in the given function set to
5886 /// the overload candidate set.
5887 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5888 ArrayRef<Expr *> Args,
5889 OverloadCandidateSet& CandidateSet,
5890 TemplateArgumentListInfo *ExplicitTemplateArgs,
5891 bool SuppressUserConversions,
5892 bool PartialOverloading) {
5893 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5894 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5895 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5896 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5897 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5898 cast<CXXMethodDecl>(FD)->getParent(),
5899 Args[0]->getType(), Args[0]->Classify(Context),
5900 Args.slice(1), CandidateSet,
5901 SuppressUserConversions, PartialOverloading);
5903 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5904 SuppressUserConversions, PartialOverloading);
5906 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5907 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5908 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5909 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5910 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5911 ExplicitTemplateArgs,
5913 Args[0]->Classify(Context), Args.slice(1),
5914 CandidateSet, SuppressUserConversions,
5915 PartialOverloading);
5917 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5918 ExplicitTemplateArgs, Args,
5919 CandidateSet, SuppressUserConversions,
5920 PartialOverloading);
5925 /// AddMethodCandidate - Adds a named decl (which is some kind of
5926 /// method) as a method candidate to the given overload set.
5927 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5928 QualType ObjectType,
5929 Expr::Classification ObjectClassification,
5930 ArrayRef<Expr *> Args,
5931 OverloadCandidateSet& CandidateSet,
5932 bool SuppressUserConversions) {
5933 NamedDecl *Decl = FoundDecl.getDecl();
5934 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5936 if (isa<UsingShadowDecl>(Decl))
5937 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5939 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5940 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5941 "Expected a member function template");
5942 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5943 /*ExplicitArgs*/ nullptr,
5944 ObjectType, ObjectClassification,
5946 SuppressUserConversions);
5948 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5949 ObjectType, ObjectClassification,
5951 CandidateSet, SuppressUserConversions);
5955 /// AddMethodCandidate - Adds the given C++ member function to the set
5956 /// of candidate functions, using the given function call arguments
5957 /// and the object argument (@c Object). For example, in a call
5958 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5959 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5960 /// allow user-defined conversions via constructors or conversion
5963 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5964 CXXRecordDecl *ActingContext, QualType ObjectType,
5965 Expr::Classification ObjectClassification,
5966 ArrayRef<Expr *> Args,
5967 OverloadCandidateSet &CandidateSet,
5968 bool SuppressUserConversions,
5969 bool PartialOverloading) {
5970 const FunctionProtoType *Proto
5971 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5972 assert(Proto && "Methods without a prototype cannot be overloaded");
5973 assert(!isa<CXXConstructorDecl>(Method) &&
5974 "Use AddOverloadCandidate for constructors");
5976 if (!CandidateSet.isNewCandidate(Method))
5979 // C++11 [class.copy]p23: [DR1402]
5980 // A defaulted move assignment operator that is defined as deleted is
5981 // ignored by overload resolution.
5982 if (Method->isDefaulted() && Method->isDeleted() &&
5983 Method->isMoveAssignmentOperator())
5986 // Overload resolution is always an unevaluated context.
5987 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5989 // Add this candidate
5990 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5991 Candidate.FoundDecl = FoundDecl;
5992 Candidate.Function = Method;
5993 Candidate.IsSurrogate = false;
5994 Candidate.IgnoreObjectArgument = false;
5995 Candidate.ExplicitCallArguments = Args.size();
5997 unsigned NumParams = Proto->getNumParams();
5999 // (C++ 13.3.2p2): A candidate function having fewer than m
6000 // parameters is viable only if it has an ellipsis in its parameter
6002 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6003 !Proto->isVariadic()) {
6004 Candidate.Viable = false;
6005 Candidate.FailureKind = ovl_fail_too_many_arguments;
6009 // (C++ 13.3.2p2): A candidate function having more than m parameters
6010 // is viable only if the (m+1)st parameter has a default argument
6011 // (8.3.6). For the purposes of overload resolution, the
6012 // parameter list is truncated on the right, so that there are
6013 // exactly m parameters.
6014 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6015 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6016 // Not enough arguments.
6017 Candidate.Viable = false;
6018 Candidate.FailureKind = ovl_fail_too_few_arguments;
6022 Candidate.Viable = true;
6024 if (Method->isStatic() || ObjectType.isNull())
6025 // The implicit object argument is ignored.
6026 Candidate.IgnoreObjectArgument = true;
6028 // Determine the implicit conversion sequence for the object
6030 Candidate.Conversions[0]
6031 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6032 Method, ActingContext);
6033 if (Candidate.Conversions[0].isBad()) {
6034 Candidate.Viable = false;
6035 Candidate.FailureKind = ovl_fail_bad_conversion;
6040 // (CUDA B.1): Check for invalid calls between targets.
6041 if (getLangOpts().CUDA)
6042 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6043 if (CheckCUDATarget(Caller, Method)) {
6044 Candidate.Viable = false;
6045 Candidate.FailureKind = ovl_fail_bad_target;
6049 // Determine the implicit conversion sequences for each of the
6051 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6052 if (ArgIdx < NumParams) {
6053 // (C++ 13.3.2p3): for F to be a viable function, there shall
6054 // exist for each argument an implicit conversion sequence
6055 // (13.3.3.1) that converts that argument to the corresponding
6057 QualType ParamType = Proto->getParamType(ArgIdx);
6058 Candidate.Conversions[ArgIdx + 1]
6059 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6060 SuppressUserConversions,
6061 /*InOverloadResolution=*/true,
6062 /*AllowObjCWritebackConversion=*/
6063 getLangOpts().ObjCAutoRefCount);
6064 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6065 Candidate.Viable = false;
6066 Candidate.FailureKind = ovl_fail_bad_conversion;
6070 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6071 // argument for which there is no corresponding parameter is
6072 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6073 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6077 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6078 Candidate.Viable = false;
6079 Candidate.FailureKind = ovl_fail_enable_if;
6080 Candidate.DeductionFailure.Data = FailedAttr;
6085 /// \brief Add a C++ member function template as a candidate to the candidate
6086 /// set, using template argument deduction to produce an appropriate member
6087 /// function template specialization.
6089 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6090 DeclAccessPair FoundDecl,
6091 CXXRecordDecl *ActingContext,
6092 TemplateArgumentListInfo *ExplicitTemplateArgs,
6093 QualType ObjectType,
6094 Expr::Classification ObjectClassification,
6095 ArrayRef<Expr *> Args,
6096 OverloadCandidateSet& CandidateSet,
6097 bool SuppressUserConversions,
6098 bool PartialOverloading) {
6099 if (!CandidateSet.isNewCandidate(MethodTmpl))
6102 // C++ [over.match.funcs]p7:
6103 // In each case where a candidate is a function template, candidate
6104 // function template specializations are generated using template argument
6105 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6106 // candidate functions in the usual way.113) A given name can refer to one
6107 // or more function templates and also to a set of overloaded non-template
6108 // functions. In such a case, the candidate functions generated from each
6109 // function template are combined with the set of non-template candidate
6111 TemplateDeductionInfo Info(CandidateSet.getLocation());
6112 FunctionDecl *Specialization = nullptr;
6113 if (TemplateDeductionResult Result
6114 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6115 Specialization, Info, PartialOverloading)) {
6116 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6117 Candidate.FoundDecl = FoundDecl;
6118 Candidate.Function = MethodTmpl->getTemplatedDecl();
6119 Candidate.Viable = false;
6120 Candidate.FailureKind = ovl_fail_bad_deduction;
6121 Candidate.IsSurrogate = false;
6122 Candidate.IgnoreObjectArgument = false;
6123 Candidate.ExplicitCallArguments = Args.size();
6124 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6129 // Add the function template specialization produced by template argument
6130 // deduction as a candidate.
6131 assert(Specialization && "Missing member function template specialization?");
6132 assert(isa<CXXMethodDecl>(Specialization) &&
6133 "Specialization is not a member function?");
6134 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6135 ActingContext, ObjectType, ObjectClassification, Args,
6136 CandidateSet, SuppressUserConversions, PartialOverloading);
6139 /// \brief Add a C++ function template specialization as a candidate
6140 /// in the candidate set, using template argument deduction to produce
6141 /// an appropriate function template specialization.
6143 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6144 DeclAccessPair FoundDecl,
6145 TemplateArgumentListInfo *ExplicitTemplateArgs,
6146 ArrayRef<Expr *> Args,
6147 OverloadCandidateSet& CandidateSet,
6148 bool SuppressUserConversions,
6149 bool PartialOverloading) {
6150 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6153 // C++ [over.match.funcs]p7:
6154 // In each case where a candidate is a function template, candidate
6155 // function template specializations are generated using template argument
6156 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6157 // candidate functions in the usual way.113) A given name can refer to one
6158 // or more function templates and also to a set of overloaded non-template
6159 // functions. In such a case, the candidate functions generated from each
6160 // function template are combined with the set of non-template candidate
6162 TemplateDeductionInfo Info(CandidateSet.getLocation());
6163 FunctionDecl *Specialization = nullptr;
6164 if (TemplateDeductionResult Result
6165 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6166 Specialization, Info, PartialOverloading)) {
6167 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6168 Candidate.FoundDecl = FoundDecl;
6169 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6170 Candidate.Viable = false;
6171 Candidate.FailureKind = ovl_fail_bad_deduction;
6172 Candidate.IsSurrogate = false;
6173 Candidate.IgnoreObjectArgument = false;
6174 Candidate.ExplicitCallArguments = Args.size();
6175 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6180 // Add the function template specialization produced by template argument
6181 // deduction as a candidate.
6182 assert(Specialization && "Missing function template specialization?");
6183 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6184 SuppressUserConversions, PartialOverloading);
6187 /// Determine whether this is an allowable conversion from the result
6188 /// of an explicit conversion operator to the expected type, per C++
6189 /// [over.match.conv]p1 and [over.match.ref]p1.
6191 /// \param ConvType The return type of the conversion function.
6193 /// \param ToType The type we are converting to.
6195 /// \param AllowObjCPointerConversion Allow a conversion from one
6196 /// Objective-C pointer to another.
6198 /// \returns true if the conversion is allowable, false otherwise.
6199 static bool isAllowableExplicitConversion(Sema &S,
6200 QualType ConvType, QualType ToType,
6201 bool AllowObjCPointerConversion) {
6202 QualType ToNonRefType = ToType.getNonReferenceType();
6204 // Easy case: the types are the same.
6205 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6208 // Allow qualification conversions.
6209 bool ObjCLifetimeConversion;
6210 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6211 ObjCLifetimeConversion))
6214 // If we're not allowed to consider Objective-C pointer conversions,
6216 if (!AllowObjCPointerConversion)
6219 // Is this an Objective-C pointer conversion?
6220 bool IncompatibleObjC = false;
6221 QualType ConvertedType;
6222 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6226 /// AddConversionCandidate - Add a C++ conversion function as a
6227 /// candidate in the candidate set (C++ [over.match.conv],
6228 /// C++ [over.match.copy]). From is the expression we're converting from,
6229 /// and ToType is the type that we're eventually trying to convert to
6230 /// (which may or may not be the same type as the type that the
6231 /// conversion function produces).
6233 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6234 DeclAccessPair FoundDecl,
6235 CXXRecordDecl *ActingContext,
6236 Expr *From, QualType ToType,
6237 OverloadCandidateSet& CandidateSet,
6238 bool AllowObjCConversionOnExplicit) {
6239 assert(!Conversion->getDescribedFunctionTemplate() &&
6240 "Conversion function templates use AddTemplateConversionCandidate");
6241 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6242 if (!CandidateSet.isNewCandidate(Conversion))
6245 // If the conversion function has an undeduced return type, trigger its
6247 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6248 if (DeduceReturnType(Conversion, From->getExprLoc()))
6250 ConvType = Conversion->getConversionType().getNonReferenceType();
6253 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6254 // operator is only a candidate if its return type is the target type or
6255 // can be converted to the target type with a qualification conversion.
6256 if (Conversion->isExplicit() &&
6257 !isAllowableExplicitConversion(*this, ConvType, ToType,
6258 AllowObjCConversionOnExplicit))
6261 // Overload resolution is always an unevaluated context.
6262 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6264 // Add this candidate
6265 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6266 Candidate.FoundDecl = FoundDecl;
6267 Candidate.Function = Conversion;
6268 Candidate.IsSurrogate = false;
6269 Candidate.IgnoreObjectArgument = false;
6270 Candidate.FinalConversion.setAsIdentityConversion();
6271 Candidate.FinalConversion.setFromType(ConvType);
6272 Candidate.FinalConversion.setAllToTypes(ToType);
6273 Candidate.Viable = true;
6274 Candidate.ExplicitCallArguments = 1;
6276 // C++ [over.match.funcs]p4:
6277 // For conversion functions, the function is considered to be a member of
6278 // the class of the implicit implied object argument for the purpose of
6279 // defining the type of the implicit object parameter.
6281 // Determine the implicit conversion sequence for the implicit
6282 // object parameter.
6283 QualType ImplicitParamType = From->getType();
6284 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6285 ImplicitParamType = FromPtrType->getPointeeType();
6286 CXXRecordDecl *ConversionContext
6287 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6289 Candidate.Conversions[0]
6290 = TryObjectArgumentInitialization(*this, From->getType(),
6291 From->Classify(Context),
6292 Conversion, ConversionContext);
6294 if (Candidate.Conversions[0].isBad()) {
6295 Candidate.Viable = false;
6296 Candidate.FailureKind = ovl_fail_bad_conversion;
6300 // We won't go through a user-defined type conversion function to convert a
6301 // derived to base as such conversions are given Conversion Rank. They only
6302 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6304 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6305 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6306 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6307 Candidate.Viable = false;
6308 Candidate.FailureKind = ovl_fail_trivial_conversion;
6312 // To determine what the conversion from the result of calling the
6313 // conversion function to the type we're eventually trying to
6314 // convert to (ToType), we need to synthesize a call to the
6315 // conversion function and attempt copy initialization from it. This
6316 // makes sure that we get the right semantics with respect to
6317 // lvalues/rvalues and the type. Fortunately, we can allocate this
6318 // call on the stack and we don't need its arguments to be
6320 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6321 VK_LValue, From->getLocStart());
6322 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6323 Context.getPointerType(Conversion->getType()),
6324 CK_FunctionToPointerDecay,
6325 &ConversionRef, VK_RValue);
6327 QualType ConversionType = Conversion->getConversionType();
6328 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6329 Candidate.Viable = false;
6330 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6334 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6336 // Note that it is safe to allocate CallExpr on the stack here because
6337 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6339 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6340 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6341 From->getLocStart());
6342 ImplicitConversionSequence ICS =
6343 TryCopyInitialization(*this, &Call, ToType,
6344 /*SuppressUserConversions=*/true,
6345 /*InOverloadResolution=*/false,
6346 /*AllowObjCWritebackConversion=*/false);
6348 switch (ICS.getKind()) {
6349 case ImplicitConversionSequence::StandardConversion:
6350 Candidate.FinalConversion = ICS.Standard;
6352 // C++ [over.ics.user]p3:
6353 // If the user-defined conversion is specified by a specialization of a
6354 // conversion function template, the second standard conversion sequence
6355 // shall have exact match rank.
6356 if (Conversion->getPrimaryTemplate() &&
6357 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6358 Candidate.Viable = false;
6359 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6363 // C++0x [dcl.init.ref]p5:
6364 // In the second case, if the reference is an rvalue reference and
6365 // the second standard conversion sequence of the user-defined
6366 // conversion sequence includes an lvalue-to-rvalue conversion, the
6367 // program is ill-formed.
6368 if (ToType->isRValueReferenceType() &&
6369 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6370 Candidate.Viable = false;
6371 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6376 case ImplicitConversionSequence::BadConversion:
6377 Candidate.Viable = false;
6378 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6383 "Can only end up with a standard conversion sequence or failure");
6386 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6387 Candidate.Viable = false;
6388 Candidate.FailureKind = ovl_fail_enable_if;
6389 Candidate.DeductionFailure.Data = FailedAttr;
6394 /// \brief Adds a conversion function template specialization
6395 /// candidate to the overload set, using template argument deduction
6396 /// to deduce the template arguments of the conversion function
6397 /// template from the type that we are converting to (C++
6398 /// [temp.deduct.conv]).
6400 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6401 DeclAccessPair FoundDecl,
6402 CXXRecordDecl *ActingDC,
6403 Expr *From, QualType ToType,
6404 OverloadCandidateSet &CandidateSet,
6405 bool AllowObjCConversionOnExplicit) {
6406 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6407 "Only conversion function templates permitted here");
6409 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6412 TemplateDeductionInfo Info(CandidateSet.getLocation());
6413 CXXConversionDecl *Specialization = nullptr;
6414 if (TemplateDeductionResult Result
6415 = DeduceTemplateArguments(FunctionTemplate, ToType,
6416 Specialization, Info)) {
6417 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6418 Candidate.FoundDecl = FoundDecl;
6419 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6420 Candidate.Viable = false;
6421 Candidate.FailureKind = ovl_fail_bad_deduction;
6422 Candidate.IsSurrogate = false;
6423 Candidate.IgnoreObjectArgument = false;
6424 Candidate.ExplicitCallArguments = 1;
6425 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6430 // Add the conversion function template specialization produced by
6431 // template argument deduction as a candidate.
6432 assert(Specialization && "Missing function template specialization?");
6433 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6434 CandidateSet, AllowObjCConversionOnExplicit);
6437 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6438 /// converts the given @c Object to a function pointer via the
6439 /// conversion function @c Conversion, and then attempts to call it
6440 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6441 /// the type of function that we'll eventually be calling.
6442 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6443 DeclAccessPair FoundDecl,
6444 CXXRecordDecl *ActingContext,
6445 const FunctionProtoType *Proto,
6447 ArrayRef<Expr *> Args,
6448 OverloadCandidateSet& CandidateSet) {
6449 if (!CandidateSet.isNewCandidate(Conversion))
6452 // Overload resolution is always an unevaluated context.
6453 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6455 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6456 Candidate.FoundDecl = FoundDecl;
6457 Candidate.Function = nullptr;
6458 Candidate.Surrogate = Conversion;
6459 Candidate.Viable = true;
6460 Candidate.IsSurrogate = true;
6461 Candidate.IgnoreObjectArgument = false;
6462 Candidate.ExplicitCallArguments = Args.size();
6464 // Determine the implicit conversion sequence for the implicit
6465 // object parameter.
6466 ImplicitConversionSequence ObjectInit
6467 = TryObjectArgumentInitialization(*this, Object->getType(),
6468 Object->Classify(Context),
6469 Conversion, ActingContext);
6470 if (ObjectInit.isBad()) {
6471 Candidate.Viable = false;
6472 Candidate.FailureKind = ovl_fail_bad_conversion;
6473 Candidate.Conversions[0] = ObjectInit;
6477 // The first conversion is actually a user-defined conversion whose
6478 // first conversion is ObjectInit's standard conversion (which is
6479 // effectively a reference binding). Record it as such.
6480 Candidate.Conversions[0].setUserDefined();
6481 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6482 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6483 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6484 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6485 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6486 Candidate.Conversions[0].UserDefined.After
6487 = Candidate.Conversions[0].UserDefined.Before;
6488 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6491 unsigned NumParams = Proto->getNumParams();
6493 // (C++ 13.3.2p2): A candidate function having fewer than m
6494 // parameters is viable only if it has an ellipsis in its parameter
6496 if (Args.size() > NumParams && !Proto->isVariadic()) {
6497 Candidate.Viable = false;
6498 Candidate.FailureKind = ovl_fail_too_many_arguments;
6502 // Function types don't have any default arguments, so just check if
6503 // we have enough arguments.
6504 if (Args.size() < NumParams) {
6505 // Not enough arguments.
6506 Candidate.Viable = false;
6507 Candidate.FailureKind = ovl_fail_too_few_arguments;
6511 // Determine the implicit conversion sequences for each of the
6513 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6514 if (ArgIdx < NumParams) {
6515 // (C++ 13.3.2p3): for F to be a viable function, there shall
6516 // exist for each argument an implicit conversion sequence
6517 // (13.3.3.1) that converts that argument to the corresponding
6519 QualType ParamType = Proto->getParamType(ArgIdx);
6520 Candidate.Conversions[ArgIdx + 1]
6521 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6522 /*SuppressUserConversions=*/false,
6523 /*InOverloadResolution=*/false,
6524 /*AllowObjCWritebackConversion=*/
6525 getLangOpts().ObjCAutoRefCount);
6526 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6527 Candidate.Viable = false;
6528 Candidate.FailureKind = ovl_fail_bad_conversion;
6532 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6533 // argument for which there is no corresponding parameter is
6534 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6535 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6539 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6540 Candidate.Viable = false;
6541 Candidate.FailureKind = ovl_fail_enable_if;
6542 Candidate.DeductionFailure.Data = FailedAttr;
6547 /// \brief Add overload candidates for overloaded operators that are
6548 /// member functions.
6550 /// Add the overloaded operator candidates that are member functions
6551 /// for the operator Op that was used in an operator expression such
6552 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6553 /// CandidateSet will store the added overload candidates. (C++
6554 /// [over.match.oper]).
6555 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6556 SourceLocation OpLoc,
6557 ArrayRef<Expr *> Args,
6558 OverloadCandidateSet& CandidateSet,
6559 SourceRange OpRange) {
6560 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6562 // C++ [over.match.oper]p3:
6563 // For a unary operator @ with an operand of a type whose
6564 // cv-unqualified version is T1, and for a binary operator @ with
6565 // a left operand of a type whose cv-unqualified version is T1 and
6566 // a right operand of a type whose cv-unqualified version is T2,
6567 // three sets of candidate functions, designated member
6568 // candidates, non-member candidates and built-in candidates, are
6569 // constructed as follows:
6570 QualType T1 = Args[0]->getType();
6572 // -- If T1 is a complete class type or a class currently being
6573 // defined, the set of member candidates is the result of the
6574 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6575 // the set of member candidates is empty.
6576 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6577 // Complete the type if it can be completed.
6578 RequireCompleteType(OpLoc, T1, 0);
6579 // If the type is neither complete nor being defined, bail out now.
6580 if (!T1Rec->getDecl()->getDefinition())
6583 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6584 LookupQualifiedName(Operators, T1Rec->getDecl());
6585 Operators.suppressDiagnostics();
6587 for (LookupResult::iterator Oper = Operators.begin(),
6588 OperEnd = Operators.end();
6591 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6592 Args[0]->Classify(Context),
6595 /* SuppressUserConversions = */ false);
6599 /// AddBuiltinCandidate - Add a candidate for a built-in
6600 /// operator. ResultTy and ParamTys are the result and parameter types
6601 /// of the built-in candidate, respectively. Args and NumArgs are the
6602 /// arguments being passed to the candidate. IsAssignmentOperator
6603 /// should be true when this built-in candidate is an assignment
6604 /// operator. NumContextualBoolArguments is the number of arguments
6605 /// (at the beginning of the argument list) that will be contextually
6606 /// converted to bool.
6607 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6608 ArrayRef<Expr *> Args,
6609 OverloadCandidateSet& CandidateSet,
6610 bool IsAssignmentOperator,
6611 unsigned NumContextualBoolArguments) {
6612 // Overload resolution is always an unevaluated context.
6613 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6615 // Add this candidate
6616 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6617 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6618 Candidate.Function = nullptr;
6619 Candidate.IsSurrogate = false;
6620 Candidate.IgnoreObjectArgument = false;
6621 Candidate.BuiltinTypes.ResultTy = ResultTy;
6622 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6623 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6625 // Determine the implicit conversion sequences for each of the
6627 Candidate.Viable = true;
6628 Candidate.ExplicitCallArguments = Args.size();
6629 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6630 // C++ [over.match.oper]p4:
6631 // For the built-in assignment operators, conversions of the
6632 // left operand are restricted as follows:
6633 // -- no temporaries are introduced to hold the left operand, and
6634 // -- no user-defined conversions are applied to the left
6635 // operand to achieve a type match with the left-most
6636 // parameter of a built-in candidate.
6638 // We block these conversions by turning off user-defined
6639 // conversions, since that is the only way that initialization of
6640 // a reference to a non-class type can occur from something that
6641 // is not of the same type.
6642 if (ArgIdx < NumContextualBoolArguments) {
6643 assert(ParamTys[ArgIdx] == Context.BoolTy &&
6644 "Contextual conversion to bool requires bool type");
6645 Candidate.Conversions[ArgIdx]
6646 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6648 Candidate.Conversions[ArgIdx]
6649 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6650 ArgIdx == 0 && IsAssignmentOperator,
6651 /*InOverloadResolution=*/false,
6652 /*AllowObjCWritebackConversion=*/
6653 getLangOpts().ObjCAutoRefCount);
6655 if (Candidate.Conversions[ArgIdx].isBad()) {
6656 Candidate.Viable = false;
6657 Candidate.FailureKind = ovl_fail_bad_conversion;
6665 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6666 /// candidate operator functions for built-in operators (C++
6667 /// [over.built]). The types are separated into pointer types and
6668 /// enumeration types.
6669 class BuiltinCandidateTypeSet {
6670 /// TypeSet - A set of types.
6671 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6673 /// PointerTypes - The set of pointer types that will be used in the
6674 /// built-in candidates.
6675 TypeSet PointerTypes;
6677 /// MemberPointerTypes - The set of member pointer types that will be
6678 /// used in the built-in candidates.
6679 TypeSet MemberPointerTypes;
6681 /// EnumerationTypes - The set of enumeration types that will be
6682 /// used in the built-in candidates.
6683 TypeSet EnumerationTypes;
6685 /// \brief The set of vector types that will be used in the built-in
6687 TypeSet VectorTypes;
6689 /// \brief A flag indicating non-record types are viable candidates
6690 bool HasNonRecordTypes;
6692 /// \brief A flag indicating whether either arithmetic or enumeration types
6693 /// were present in the candidate set.
6694 bool HasArithmeticOrEnumeralTypes;
6696 /// \brief A flag indicating whether the nullptr type was present in the
6698 bool HasNullPtrType;
6700 /// Sema - The semantic analysis instance where we are building the
6701 /// candidate type set.
6704 /// Context - The AST context in which we will build the type sets.
6705 ASTContext &Context;
6707 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6708 const Qualifiers &VisibleQuals);
6709 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6712 /// iterator - Iterates through the types that are part of the set.
6713 typedef TypeSet::iterator iterator;
6715 BuiltinCandidateTypeSet(Sema &SemaRef)
6716 : HasNonRecordTypes(false),
6717 HasArithmeticOrEnumeralTypes(false),
6718 HasNullPtrType(false),
6720 Context(SemaRef.Context) { }
6722 void AddTypesConvertedFrom(QualType Ty,
6724 bool AllowUserConversions,
6725 bool AllowExplicitConversions,
6726 const Qualifiers &VisibleTypeConversionsQuals);
6728 /// pointer_begin - First pointer type found;
6729 iterator pointer_begin() { return PointerTypes.begin(); }
6731 /// pointer_end - Past the last pointer type found;
6732 iterator pointer_end() { return PointerTypes.end(); }
6734 /// member_pointer_begin - First member pointer type found;
6735 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6737 /// member_pointer_end - Past the last member pointer type found;
6738 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6740 /// enumeration_begin - First enumeration type found;
6741 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6743 /// enumeration_end - Past the last enumeration type found;
6744 iterator enumeration_end() { return EnumerationTypes.end(); }
6746 iterator vector_begin() { return VectorTypes.begin(); }
6747 iterator vector_end() { return VectorTypes.end(); }
6749 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6750 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6751 bool hasNullPtrType() const { return HasNullPtrType; }
6754 } // end anonymous namespace
6756 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6757 /// the set of pointer types along with any more-qualified variants of
6758 /// that type. For example, if @p Ty is "int const *", this routine
6759 /// will add "int const *", "int const volatile *", "int const
6760 /// restrict *", and "int const volatile restrict *" to the set of
6761 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6762 /// false otherwise.
6764 /// FIXME: what to do about extended qualifiers?
6766 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6767 const Qualifiers &VisibleQuals) {
6769 // Insert this type.
6770 if (!PointerTypes.insert(Ty).second)
6774 const PointerType *PointerTy = Ty->getAs<PointerType>();
6775 bool buildObjCPtr = false;
6777 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6778 PointeeTy = PTy->getPointeeType();
6779 buildObjCPtr = true;
6781 PointeeTy = PointerTy->getPointeeType();
6784 // Don't add qualified variants of arrays. For one, they're not allowed
6785 // (the qualifier would sink to the element type), and for another, the
6786 // only overload situation where it matters is subscript or pointer +- int,
6787 // and those shouldn't have qualifier variants anyway.
6788 if (PointeeTy->isArrayType())
6791 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6792 bool hasVolatile = VisibleQuals.hasVolatile();
6793 bool hasRestrict = VisibleQuals.hasRestrict();
6795 // Iterate through all strict supersets of BaseCVR.
6796 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6797 if ((CVR | BaseCVR) != CVR) continue;
6798 // Skip over volatile if no volatile found anywhere in the types.
6799 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6801 // Skip over restrict if no restrict found anywhere in the types, or if
6802 // the type cannot be restrict-qualified.
6803 if ((CVR & Qualifiers::Restrict) &&
6805 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6808 // Build qualified pointee type.
6809 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6811 // Build qualified pointer type.
6812 QualType QPointerTy;
6814 QPointerTy = Context.getPointerType(QPointeeTy);
6816 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6818 // Insert qualified pointer type.
6819 PointerTypes.insert(QPointerTy);
6825 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6826 /// to the set of pointer types along with any more-qualified variants of
6827 /// that type. For example, if @p Ty is "int const *", this routine
6828 /// will add "int const *", "int const volatile *", "int const
6829 /// restrict *", and "int const volatile restrict *" to the set of
6830 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6831 /// false otherwise.
6833 /// FIXME: what to do about extended qualifiers?
6835 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6837 // Insert this type.
6838 if (!MemberPointerTypes.insert(Ty).second)
6841 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6842 assert(PointerTy && "type was not a member pointer type!");
6844 QualType PointeeTy = PointerTy->getPointeeType();
6845 // Don't add qualified variants of arrays. For one, they're not allowed
6846 // (the qualifier would sink to the element type), and for another, the
6847 // only overload situation where it matters is subscript or pointer +- int,
6848 // and those shouldn't have qualifier variants anyway.
6849 if (PointeeTy->isArrayType())
6851 const Type *ClassTy = PointerTy->getClass();
6853 // Iterate through all strict supersets of the pointee type's CVR
6855 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6856 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6857 if ((CVR | BaseCVR) != CVR) continue;
6859 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6860 MemberPointerTypes.insert(
6861 Context.getMemberPointerType(QPointeeTy, ClassTy));
6867 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6868 /// Ty can be implicit converted to the given set of @p Types. We're
6869 /// primarily interested in pointer types and enumeration types. We also
6870 /// take member pointer types, for the conditional operator.
6871 /// AllowUserConversions is true if we should look at the conversion
6872 /// functions of a class type, and AllowExplicitConversions if we
6873 /// should also include the explicit conversion functions of a class
6876 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6878 bool AllowUserConversions,
6879 bool AllowExplicitConversions,
6880 const Qualifiers &VisibleQuals) {
6881 // Only deal with canonical types.
6882 Ty = Context.getCanonicalType(Ty);
6884 // Look through reference types; they aren't part of the type of an
6885 // expression for the purposes of conversions.
6886 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6887 Ty = RefTy->getPointeeType();
6889 // If we're dealing with an array type, decay to the pointer.
6890 if (Ty->isArrayType())
6891 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6893 // Otherwise, we don't care about qualifiers on the type.
6894 Ty = Ty.getLocalUnqualifiedType();
6896 // Flag if we ever add a non-record type.
6897 const RecordType *TyRec = Ty->getAs<RecordType>();
6898 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6900 // Flag if we encounter an arithmetic type.
6901 HasArithmeticOrEnumeralTypes =
6902 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6904 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6905 PointerTypes.insert(Ty);
6906 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6907 // Insert our type, and its more-qualified variants, into the set
6909 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6911 } else if (Ty->isMemberPointerType()) {
6912 // Member pointers are far easier, since the pointee can't be converted.
6913 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6915 } else if (Ty->isEnumeralType()) {
6916 HasArithmeticOrEnumeralTypes = true;
6917 EnumerationTypes.insert(Ty);
6918 } else if (Ty->isVectorType()) {
6919 // We treat vector types as arithmetic types in many contexts as an
6921 HasArithmeticOrEnumeralTypes = true;
6922 VectorTypes.insert(Ty);
6923 } else if (Ty->isNullPtrType()) {
6924 HasNullPtrType = true;
6925 } else if (AllowUserConversions && TyRec) {
6926 // No conversion functions in incomplete types.
6927 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6930 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6931 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6932 if (isa<UsingShadowDecl>(D))
6933 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6935 // Skip conversion function templates; they don't tell us anything
6936 // about which builtin types we can convert to.
6937 if (isa<FunctionTemplateDecl>(D))
6940 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6941 if (AllowExplicitConversions || !Conv->isExplicit()) {
6942 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6949 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6950 /// the volatile- and non-volatile-qualified assignment operators for the
6951 /// given type to the candidate set.
6952 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6954 ArrayRef<Expr *> Args,
6955 OverloadCandidateSet &CandidateSet) {
6956 QualType ParamTypes[2];
6958 // T& operator=(T&, T)
6959 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6962 /*IsAssignmentOperator=*/true);
6964 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6965 // volatile T& operator=(volatile T&, T)
6967 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6970 /*IsAssignmentOperator=*/true);
6974 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6975 /// if any, found in visible type conversion functions found in ArgExpr's type.
6976 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6978 const RecordType *TyRec;
6979 if (const MemberPointerType *RHSMPType =
6980 ArgExpr->getType()->getAs<MemberPointerType>())
6981 TyRec = RHSMPType->getClass()->getAs<RecordType>();
6983 TyRec = ArgExpr->getType()->getAs<RecordType>();
6985 // Just to be safe, assume the worst case.
6986 VRQuals.addVolatile();
6987 VRQuals.addRestrict();
6991 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6992 if (!ClassDecl->hasDefinition())
6995 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
6996 if (isa<UsingShadowDecl>(D))
6997 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6998 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6999 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7000 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7001 CanTy = ResTypeRef->getPointeeType();
7002 // Need to go down the pointer/mempointer chain and add qualifiers
7006 if (CanTy.isRestrictQualified())
7007 VRQuals.addRestrict();
7008 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7009 CanTy = ResTypePtr->getPointeeType();
7010 else if (const MemberPointerType *ResTypeMPtr =
7011 CanTy->getAs<MemberPointerType>())
7012 CanTy = ResTypeMPtr->getPointeeType();
7015 if (CanTy.isVolatileQualified())
7016 VRQuals.addVolatile();
7017 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7027 /// \brief Helper class to manage the addition of builtin operator overload
7028 /// candidates. It provides shared state and utility methods used throughout
7029 /// the process, as well as a helper method to add each group of builtin
7030 /// operator overloads from the standard to a candidate set.
7031 class BuiltinOperatorOverloadBuilder {
7032 // Common instance state available to all overload candidate addition methods.
7034 ArrayRef<Expr *> Args;
7035 Qualifiers VisibleTypeConversionsQuals;
7036 bool HasArithmeticOrEnumeralCandidateType;
7037 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7038 OverloadCandidateSet &CandidateSet;
7040 // Define some constants used to index and iterate over the arithemetic types
7041 // provided via the getArithmeticType() method below.
7042 // The "promoted arithmetic types" are the arithmetic
7043 // types are that preserved by promotion (C++ [over.built]p2).
7044 static const unsigned FirstIntegralType = 3;
7045 static const unsigned LastIntegralType = 20;
7046 static const unsigned FirstPromotedIntegralType = 3,
7047 LastPromotedIntegralType = 11;
7048 static const unsigned FirstPromotedArithmeticType = 0,
7049 LastPromotedArithmeticType = 11;
7050 static const unsigned NumArithmeticTypes = 20;
7052 /// \brief Get the canonical type for a given arithmetic type index.
7053 CanQualType getArithmeticType(unsigned index) {
7054 assert(index < NumArithmeticTypes);
7055 static CanQualType ASTContext::* const
7056 ArithmeticTypes[NumArithmeticTypes] = {
7057 // Start of promoted types.
7058 &ASTContext::FloatTy,
7059 &ASTContext::DoubleTy,
7060 &ASTContext::LongDoubleTy,
7062 // Start of integral types.
7064 &ASTContext::LongTy,
7065 &ASTContext::LongLongTy,
7066 &ASTContext::Int128Ty,
7067 &ASTContext::UnsignedIntTy,
7068 &ASTContext::UnsignedLongTy,
7069 &ASTContext::UnsignedLongLongTy,
7070 &ASTContext::UnsignedInt128Ty,
7071 // End of promoted types.
7073 &ASTContext::BoolTy,
7074 &ASTContext::CharTy,
7075 &ASTContext::WCharTy,
7076 &ASTContext::Char16Ty,
7077 &ASTContext::Char32Ty,
7078 &ASTContext::SignedCharTy,
7079 &ASTContext::ShortTy,
7080 &ASTContext::UnsignedCharTy,
7081 &ASTContext::UnsignedShortTy,
7082 // End of integral types.
7083 // FIXME: What about complex? What about half?
7085 return S.Context.*ArithmeticTypes[index];
7088 /// \brief Gets the canonical type resulting from the usual arithemetic
7089 /// converions for the given arithmetic types.
7090 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7091 // Accelerator table for performing the usual arithmetic conversions.
7092 // The rules are basically:
7093 // - if either is floating-point, use the wider floating-point
7094 // - if same signedness, use the higher rank
7095 // - if same size, use unsigned of the higher rank
7096 // - use the larger type
7097 // These rules, together with the axiom that higher ranks are
7098 // never smaller, are sufficient to precompute all of these results
7099 // *except* when dealing with signed types of higher rank.
7100 // (we could precompute SLL x UI for all known platforms, but it's
7101 // better not to make any assumptions).
7102 // We assume that int128 has a higher rank than long long on all platforms.
7105 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7107 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7108 [LastPromotedArithmeticType] = {
7109 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7110 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7111 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7112 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7113 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7114 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7115 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7116 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7117 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7118 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7119 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7122 assert(L < LastPromotedArithmeticType);
7123 assert(R < LastPromotedArithmeticType);
7124 int Idx = ConversionsTable[L][R];
7126 // Fast path: the table gives us a concrete answer.
7127 if (Idx != Dep) return getArithmeticType(Idx);
7129 // Slow path: we need to compare widths.
7130 // An invariant is that the signed type has higher rank.
7131 CanQualType LT = getArithmeticType(L),
7132 RT = getArithmeticType(R);
7133 unsigned LW = S.Context.getIntWidth(LT),
7134 RW = S.Context.getIntWidth(RT);
7136 // If they're different widths, use the signed type.
7137 if (LW > RW) return LT;
7138 else if (LW < RW) return RT;
7140 // Otherwise, use the unsigned type of the signed type's rank.
7141 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7142 assert(L == SLL || R == SLL);
7143 return S.Context.UnsignedLongLongTy;
7146 /// \brief Helper method to factor out the common pattern of adding overloads
7147 /// for '++' and '--' builtin operators.
7148 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7151 QualType ParamTypes[2] = {
7152 S.Context.getLValueReferenceType(CandidateTy),
7156 // Non-volatile version.
7157 if (Args.size() == 1)
7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7160 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7162 // Use a heuristic to reduce number of builtin candidates in the set:
7163 // add volatile version only if there are conversions to a volatile type.
7166 S.Context.getLValueReferenceType(
7167 S.Context.getVolatileType(CandidateTy));
7168 if (Args.size() == 1)
7169 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7171 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7174 // Add restrict version only if there are conversions to a restrict type
7175 // and our candidate type is a non-restrict-qualified pointer.
7176 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7177 !CandidateTy.isRestrictQualified()) {
7179 = S.Context.getLValueReferenceType(
7180 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7181 if (Args.size() == 1)
7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7184 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7188 = S.Context.getLValueReferenceType(
7189 S.Context.getCVRQualifiedType(CandidateTy,
7190 (Qualifiers::Volatile |
7191 Qualifiers::Restrict)));
7192 if (Args.size() == 1)
7193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7195 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7202 BuiltinOperatorOverloadBuilder(
7203 Sema &S, ArrayRef<Expr *> Args,
7204 Qualifiers VisibleTypeConversionsQuals,
7205 bool HasArithmeticOrEnumeralCandidateType,
7206 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7207 OverloadCandidateSet &CandidateSet)
7209 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7210 HasArithmeticOrEnumeralCandidateType(
7211 HasArithmeticOrEnumeralCandidateType),
7212 CandidateTypes(CandidateTypes),
7213 CandidateSet(CandidateSet) {
7214 // Validate some of our static helper constants in debug builds.
7215 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7216 "Invalid first promoted integral type");
7217 assert(getArithmeticType(LastPromotedIntegralType - 1)
7218 == S.Context.UnsignedInt128Ty &&
7219 "Invalid last promoted integral type");
7220 assert(getArithmeticType(FirstPromotedArithmeticType)
7221 == S.Context.FloatTy &&
7222 "Invalid first promoted arithmetic type");
7223 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7224 == S.Context.UnsignedInt128Ty &&
7225 "Invalid last promoted arithmetic type");
7228 // C++ [over.built]p3:
7230 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7231 // is either volatile or empty, there exist candidate operator
7232 // functions of the form
7234 // VQ T& operator++(VQ T&);
7235 // T operator++(VQ T&, int);
7237 // C++ [over.built]p4:
7239 // For every pair (T, VQ), where T is an arithmetic type other
7240 // than bool, and VQ is either volatile or empty, there exist
7241 // candidate operator functions of the form
7243 // VQ T& operator--(VQ T&);
7244 // T operator--(VQ T&, int);
7245 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7246 if (!HasArithmeticOrEnumeralCandidateType)
7249 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7250 Arith < NumArithmeticTypes; ++Arith) {
7251 addPlusPlusMinusMinusStyleOverloads(
7252 getArithmeticType(Arith),
7253 VisibleTypeConversionsQuals.hasVolatile(),
7254 VisibleTypeConversionsQuals.hasRestrict());
7258 // C++ [over.built]p5:
7260 // For every pair (T, VQ), where T is a cv-qualified or
7261 // cv-unqualified object type, and VQ is either volatile or
7262 // empty, there exist candidate operator functions of the form
7264 // T*VQ& operator++(T*VQ&);
7265 // T*VQ& operator--(T*VQ&);
7266 // T* operator++(T*VQ&, int);
7267 // T* operator--(T*VQ&, int);
7268 void addPlusPlusMinusMinusPointerOverloads() {
7269 for (BuiltinCandidateTypeSet::iterator
7270 Ptr = CandidateTypes[0].pointer_begin(),
7271 PtrEnd = CandidateTypes[0].pointer_end();
7272 Ptr != PtrEnd; ++Ptr) {
7273 // Skip pointer types that aren't pointers to object types.
7274 if (!(*Ptr)->getPointeeType()->isObjectType())
7277 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7278 (!(*Ptr).isVolatileQualified() &&
7279 VisibleTypeConversionsQuals.hasVolatile()),
7280 (!(*Ptr).isRestrictQualified() &&
7281 VisibleTypeConversionsQuals.hasRestrict()));
7285 // C++ [over.built]p6:
7286 // For every cv-qualified or cv-unqualified object type T, there
7287 // exist candidate operator functions of the form
7289 // T& operator*(T*);
7291 // C++ [over.built]p7:
7292 // For every function type T that does not have cv-qualifiers or a
7293 // ref-qualifier, there exist candidate operator functions of the form
7294 // T& operator*(T*);
7295 void addUnaryStarPointerOverloads() {
7296 for (BuiltinCandidateTypeSet::iterator
7297 Ptr = CandidateTypes[0].pointer_begin(),
7298 PtrEnd = CandidateTypes[0].pointer_end();
7299 Ptr != PtrEnd; ++Ptr) {
7300 QualType ParamTy = *Ptr;
7301 QualType PointeeTy = ParamTy->getPointeeType();
7302 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7305 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7306 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7309 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7310 &ParamTy, Args, CandidateSet);
7314 // C++ [over.built]p9:
7315 // For every promoted arithmetic type T, there exist candidate
7316 // operator functions of the form
7320 void addUnaryPlusOrMinusArithmeticOverloads() {
7321 if (!HasArithmeticOrEnumeralCandidateType)
7324 for (unsigned Arith = FirstPromotedArithmeticType;
7325 Arith < LastPromotedArithmeticType; ++Arith) {
7326 QualType ArithTy = getArithmeticType(Arith);
7327 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7330 // Extension: We also add these operators for vector types.
7331 for (BuiltinCandidateTypeSet::iterator
7332 Vec = CandidateTypes[0].vector_begin(),
7333 VecEnd = CandidateTypes[0].vector_end();
7334 Vec != VecEnd; ++Vec) {
7335 QualType VecTy = *Vec;
7336 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7340 // C++ [over.built]p8:
7341 // For every type T, there exist candidate operator functions of
7344 // T* operator+(T*);
7345 void addUnaryPlusPointerOverloads() {
7346 for (BuiltinCandidateTypeSet::iterator
7347 Ptr = CandidateTypes[0].pointer_begin(),
7348 PtrEnd = CandidateTypes[0].pointer_end();
7349 Ptr != PtrEnd; ++Ptr) {
7350 QualType ParamTy = *Ptr;
7351 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7355 // C++ [over.built]p10:
7356 // For every promoted integral type T, there exist candidate
7357 // operator functions of the form
7360 void addUnaryTildePromotedIntegralOverloads() {
7361 if (!HasArithmeticOrEnumeralCandidateType)
7364 for (unsigned Int = FirstPromotedIntegralType;
7365 Int < LastPromotedIntegralType; ++Int) {
7366 QualType IntTy = getArithmeticType(Int);
7367 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7370 // Extension: We also add this operator for vector types.
7371 for (BuiltinCandidateTypeSet::iterator
7372 Vec = CandidateTypes[0].vector_begin(),
7373 VecEnd = CandidateTypes[0].vector_end();
7374 Vec != VecEnd; ++Vec) {
7375 QualType VecTy = *Vec;
7376 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7380 // C++ [over.match.oper]p16:
7381 // For every pointer to member type T, there exist candidate operator
7382 // functions of the form
7384 // bool operator==(T,T);
7385 // bool operator!=(T,T);
7386 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7387 /// Set of (canonical) types that we've already handled.
7388 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7390 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7391 for (BuiltinCandidateTypeSet::iterator
7392 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7393 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7394 MemPtr != MemPtrEnd;
7396 // Don't add the same builtin candidate twice.
7397 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7400 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7401 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7406 // C++ [over.built]p15:
7408 // For every T, where T is an enumeration type, a pointer type, or
7409 // std::nullptr_t, there exist candidate operator functions of the form
7411 // bool operator<(T, T);
7412 // bool operator>(T, T);
7413 // bool operator<=(T, T);
7414 // bool operator>=(T, T);
7415 // bool operator==(T, T);
7416 // bool operator!=(T, T);
7417 void addRelationalPointerOrEnumeralOverloads() {
7418 // C++ [over.match.oper]p3:
7419 // [...]the built-in candidates include all of the candidate operator
7420 // functions defined in 13.6 that, compared to the given operator, [...]
7421 // do not have the same parameter-type-list as any non-template non-member
7424 // Note that in practice, this only affects enumeration types because there
7425 // aren't any built-in candidates of record type, and a user-defined operator
7426 // must have an operand of record or enumeration type. Also, the only other
7427 // overloaded operator with enumeration arguments, operator=,
7428 // cannot be overloaded for enumeration types, so this is the only place
7429 // where we must suppress candidates like this.
7430 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7431 UserDefinedBinaryOperators;
7433 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7434 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7435 CandidateTypes[ArgIdx].enumeration_end()) {
7436 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7437 CEnd = CandidateSet.end();
7439 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7442 if (C->Function->isFunctionTemplateSpecialization())
7445 QualType FirstParamType =
7446 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7447 QualType SecondParamType =
7448 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7450 // Skip if either parameter isn't of enumeral type.
7451 if (!FirstParamType->isEnumeralType() ||
7452 !SecondParamType->isEnumeralType())
7455 // Add this operator to the set of known user-defined operators.
7456 UserDefinedBinaryOperators.insert(
7457 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7458 S.Context.getCanonicalType(SecondParamType)));
7463 /// Set of (canonical) types that we've already handled.
7464 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7466 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7467 for (BuiltinCandidateTypeSet::iterator
7468 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7469 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7470 Ptr != PtrEnd; ++Ptr) {
7471 // Don't add the same builtin candidate twice.
7472 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7475 QualType ParamTypes[2] = { *Ptr, *Ptr };
7476 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7478 for (BuiltinCandidateTypeSet::iterator
7479 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7480 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7481 Enum != EnumEnd; ++Enum) {
7482 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7484 // Don't add the same builtin candidate twice, or if a user defined
7485 // candidate exists.
7486 if (!AddedTypes.insert(CanonType).second ||
7487 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7491 QualType ParamTypes[2] = { *Enum, *Enum };
7492 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7495 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7496 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7497 if (AddedTypes.insert(NullPtrTy).second &&
7498 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7500 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7501 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7508 // C++ [over.built]p13:
7510 // For every cv-qualified or cv-unqualified object type T
7511 // there exist candidate operator functions of the form
7513 // T* operator+(T*, ptrdiff_t);
7514 // T& operator[](T*, ptrdiff_t); [BELOW]
7515 // T* operator-(T*, ptrdiff_t);
7516 // T* operator+(ptrdiff_t, T*);
7517 // T& operator[](ptrdiff_t, T*); [BELOW]
7519 // C++ [over.built]p14:
7521 // For every T, where T is a pointer to object type, there
7522 // exist candidate operator functions of the form
7524 // ptrdiff_t operator-(T, T);
7525 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7526 /// Set of (canonical) types that we've already handled.
7527 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7529 for (int Arg = 0; Arg < 2; ++Arg) {
7530 QualType AsymetricParamTypes[2] = {
7531 S.Context.getPointerDiffType(),
7532 S.Context.getPointerDiffType(),
7534 for (BuiltinCandidateTypeSet::iterator
7535 Ptr = CandidateTypes[Arg].pointer_begin(),
7536 PtrEnd = CandidateTypes[Arg].pointer_end();
7537 Ptr != PtrEnd; ++Ptr) {
7538 QualType PointeeTy = (*Ptr)->getPointeeType();
7539 if (!PointeeTy->isObjectType())
7542 AsymetricParamTypes[Arg] = *Ptr;
7543 if (Arg == 0 || Op == OO_Plus) {
7544 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7545 // T* operator+(ptrdiff_t, T*);
7546 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7548 if (Op == OO_Minus) {
7549 // ptrdiff_t operator-(T, T);
7550 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7553 QualType ParamTypes[2] = { *Ptr, *Ptr };
7554 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7555 Args, CandidateSet);
7561 // C++ [over.built]p12:
7563 // For every pair of promoted arithmetic types L and R, there
7564 // exist candidate operator functions of the form
7566 // LR operator*(L, R);
7567 // LR operator/(L, R);
7568 // LR operator+(L, R);
7569 // LR operator-(L, R);
7570 // bool operator<(L, R);
7571 // bool operator>(L, R);
7572 // bool operator<=(L, R);
7573 // bool operator>=(L, R);
7574 // bool operator==(L, R);
7575 // bool operator!=(L, R);
7577 // where LR is the result of the usual arithmetic conversions
7578 // between types L and R.
7580 // C++ [over.built]p24:
7582 // For every pair of promoted arithmetic types L and R, there exist
7583 // candidate operator functions of the form
7585 // LR operator?(bool, L, R);
7587 // where LR is the result of the usual arithmetic conversions
7588 // between types L and R.
7589 // Our candidates ignore the first parameter.
7590 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7591 if (!HasArithmeticOrEnumeralCandidateType)
7594 for (unsigned Left = FirstPromotedArithmeticType;
7595 Left < LastPromotedArithmeticType; ++Left) {
7596 for (unsigned Right = FirstPromotedArithmeticType;
7597 Right < LastPromotedArithmeticType; ++Right) {
7598 QualType LandR[2] = { getArithmeticType(Left),
7599 getArithmeticType(Right) };
7601 isComparison ? S.Context.BoolTy
7602 : getUsualArithmeticConversions(Left, Right);
7603 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7607 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7608 // conditional operator for vector types.
7609 for (BuiltinCandidateTypeSet::iterator
7610 Vec1 = CandidateTypes[0].vector_begin(),
7611 Vec1End = CandidateTypes[0].vector_end();
7612 Vec1 != Vec1End; ++Vec1) {
7613 for (BuiltinCandidateTypeSet::iterator
7614 Vec2 = CandidateTypes[1].vector_begin(),
7615 Vec2End = CandidateTypes[1].vector_end();
7616 Vec2 != Vec2End; ++Vec2) {
7617 QualType LandR[2] = { *Vec1, *Vec2 };
7618 QualType Result = S.Context.BoolTy;
7619 if (!isComparison) {
7620 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7626 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7631 // C++ [over.built]p17:
7633 // For every pair of promoted integral types L and R, there
7634 // exist candidate operator functions of the form
7636 // LR operator%(L, R);
7637 // LR operator&(L, R);
7638 // LR operator^(L, R);
7639 // LR operator|(L, R);
7640 // L operator<<(L, R);
7641 // L operator>>(L, R);
7643 // where LR is the result of the usual arithmetic conversions
7644 // between types L and R.
7645 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7646 if (!HasArithmeticOrEnumeralCandidateType)
7649 for (unsigned Left = FirstPromotedIntegralType;
7650 Left < LastPromotedIntegralType; ++Left) {
7651 for (unsigned Right = FirstPromotedIntegralType;
7652 Right < LastPromotedIntegralType; ++Right) {
7653 QualType LandR[2] = { getArithmeticType(Left),
7654 getArithmeticType(Right) };
7655 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7657 : getUsualArithmeticConversions(Left, Right);
7658 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7663 // C++ [over.built]p20:
7665 // For every pair (T, VQ), where T is an enumeration or
7666 // pointer to member type and VQ is either volatile or
7667 // empty, there exist candidate operator functions of the form
7669 // VQ T& operator=(VQ T&, T);
7670 void addAssignmentMemberPointerOrEnumeralOverloads() {
7671 /// Set of (canonical) types that we've already handled.
7672 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7674 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7675 for (BuiltinCandidateTypeSet::iterator
7676 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7677 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7678 Enum != EnumEnd; ++Enum) {
7679 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7682 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7685 for (BuiltinCandidateTypeSet::iterator
7686 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7687 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7688 MemPtr != MemPtrEnd; ++MemPtr) {
7689 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7692 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7697 // C++ [over.built]p19:
7699 // For every pair (T, VQ), where T is any type and VQ is either
7700 // volatile or empty, there exist candidate operator functions
7703 // T*VQ& operator=(T*VQ&, T*);
7705 // C++ [over.built]p21:
7707 // For every pair (T, VQ), where T is a cv-qualified or
7708 // cv-unqualified object type and VQ is either volatile or
7709 // empty, there exist candidate operator functions of the form
7711 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7712 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7713 void addAssignmentPointerOverloads(bool isEqualOp) {
7714 /// Set of (canonical) types that we've already handled.
7715 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7717 for (BuiltinCandidateTypeSet::iterator
7718 Ptr = CandidateTypes[0].pointer_begin(),
7719 PtrEnd = CandidateTypes[0].pointer_end();
7720 Ptr != PtrEnd; ++Ptr) {
7721 // If this is operator=, keep track of the builtin candidates we added.
7723 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7724 else if (!(*Ptr)->getPointeeType()->isObjectType())
7727 // non-volatile version
7728 QualType ParamTypes[2] = {
7729 S.Context.getLValueReferenceType(*Ptr),
7730 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7732 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7733 /*IsAssigmentOperator=*/ isEqualOp);
7735 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7736 VisibleTypeConversionsQuals.hasVolatile();
7740 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7741 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7742 /*IsAssigmentOperator=*/isEqualOp);
7745 if (!(*Ptr).isRestrictQualified() &&
7746 VisibleTypeConversionsQuals.hasRestrict()) {
7749 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7750 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7751 /*IsAssigmentOperator=*/isEqualOp);
7754 // volatile restrict version
7756 = S.Context.getLValueReferenceType(
7757 S.Context.getCVRQualifiedType(*Ptr,
7758 (Qualifiers::Volatile |
7759 Qualifiers::Restrict)));
7760 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7761 /*IsAssigmentOperator=*/isEqualOp);
7767 for (BuiltinCandidateTypeSet::iterator
7768 Ptr = CandidateTypes[1].pointer_begin(),
7769 PtrEnd = CandidateTypes[1].pointer_end();
7770 Ptr != PtrEnd; ++Ptr) {
7771 // Make sure we don't add the same candidate twice.
7772 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7775 QualType ParamTypes[2] = {
7776 S.Context.getLValueReferenceType(*Ptr),
7780 // non-volatile version
7781 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7782 /*IsAssigmentOperator=*/true);
7784 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7785 VisibleTypeConversionsQuals.hasVolatile();
7789 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7790 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7791 /*IsAssigmentOperator=*/true);
7794 if (!(*Ptr).isRestrictQualified() &&
7795 VisibleTypeConversionsQuals.hasRestrict()) {
7798 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7799 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7800 /*IsAssigmentOperator=*/true);
7803 // volatile restrict version
7805 = S.Context.getLValueReferenceType(
7806 S.Context.getCVRQualifiedType(*Ptr,
7807 (Qualifiers::Volatile |
7808 Qualifiers::Restrict)));
7809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7810 /*IsAssigmentOperator=*/true);
7817 // C++ [over.built]p18:
7819 // For every triple (L, VQ, R), where L is an arithmetic type,
7820 // VQ is either volatile or empty, and R is a promoted
7821 // arithmetic type, there exist candidate operator functions of
7824 // VQ L& operator=(VQ L&, R);
7825 // VQ L& operator*=(VQ L&, R);
7826 // VQ L& operator/=(VQ L&, R);
7827 // VQ L& operator+=(VQ L&, R);
7828 // VQ L& operator-=(VQ L&, R);
7829 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7830 if (!HasArithmeticOrEnumeralCandidateType)
7833 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7834 for (unsigned Right = FirstPromotedArithmeticType;
7835 Right < LastPromotedArithmeticType; ++Right) {
7836 QualType ParamTypes[2];
7837 ParamTypes[1] = getArithmeticType(Right);
7839 // Add this built-in operator as a candidate (VQ is empty).
7841 S.Context.getLValueReferenceType(getArithmeticType(Left));
7842 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7843 /*IsAssigmentOperator=*/isEqualOp);
7845 // Add this built-in operator as a candidate (VQ is 'volatile').
7846 if (VisibleTypeConversionsQuals.hasVolatile()) {
7848 S.Context.getVolatileType(getArithmeticType(Left));
7849 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7850 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7851 /*IsAssigmentOperator=*/isEqualOp);
7856 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7857 for (BuiltinCandidateTypeSet::iterator
7858 Vec1 = CandidateTypes[0].vector_begin(),
7859 Vec1End = CandidateTypes[0].vector_end();
7860 Vec1 != Vec1End; ++Vec1) {
7861 for (BuiltinCandidateTypeSet::iterator
7862 Vec2 = CandidateTypes[1].vector_begin(),
7863 Vec2End = CandidateTypes[1].vector_end();
7864 Vec2 != Vec2End; ++Vec2) {
7865 QualType ParamTypes[2];
7866 ParamTypes[1] = *Vec2;
7867 // Add this built-in operator as a candidate (VQ is empty).
7868 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7869 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7870 /*IsAssigmentOperator=*/isEqualOp);
7872 // Add this built-in operator as a candidate (VQ is 'volatile').
7873 if (VisibleTypeConversionsQuals.hasVolatile()) {
7874 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7875 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7876 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7877 /*IsAssigmentOperator=*/isEqualOp);
7883 // C++ [over.built]p22:
7885 // For every triple (L, VQ, R), where L is an integral type, VQ
7886 // is either volatile or empty, and R is a promoted integral
7887 // type, there exist candidate operator functions of the form
7889 // VQ L& operator%=(VQ L&, R);
7890 // VQ L& operator<<=(VQ L&, R);
7891 // VQ L& operator>>=(VQ L&, R);
7892 // VQ L& operator&=(VQ L&, R);
7893 // VQ L& operator^=(VQ L&, R);
7894 // VQ L& operator|=(VQ L&, R);
7895 void addAssignmentIntegralOverloads() {
7896 if (!HasArithmeticOrEnumeralCandidateType)
7899 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7900 for (unsigned Right = FirstPromotedIntegralType;
7901 Right < LastPromotedIntegralType; ++Right) {
7902 QualType ParamTypes[2];
7903 ParamTypes[1] = getArithmeticType(Right);
7905 // Add this built-in operator as a candidate (VQ is empty).
7907 S.Context.getLValueReferenceType(getArithmeticType(Left));
7908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7909 if (VisibleTypeConversionsQuals.hasVolatile()) {
7910 // Add this built-in operator as a candidate (VQ is 'volatile').
7911 ParamTypes[0] = getArithmeticType(Left);
7912 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7913 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7914 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7920 // C++ [over.operator]p23:
7922 // There also exist candidate operator functions of the form
7924 // bool operator!(bool);
7925 // bool operator&&(bool, bool);
7926 // bool operator||(bool, bool);
7927 void addExclaimOverload() {
7928 QualType ParamTy = S.Context.BoolTy;
7929 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7930 /*IsAssignmentOperator=*/false,
7931 /*NumContextualBoolArguments=*/1);
7933 void addAmpAmpOrPipePipeOverload() {
7934 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7935 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7936 /*IsAssignmentOperator=*/false,
7937 /*NumContextualBoolArguments=*/2);
7940 // C++ [over.built]p13:
7942 // For every cv-qualified or cv-unqualified object type T there
7943 // exist candidate operator functions of the form
7945 // T* operator+(T*, ptrdiff_t); [ABOVE]
7946 // T& operator[](T*, ptrdiff_t);
7947 // T* operator-(T*, ptrdiff_t); [ABOVE]
7948 // T* operator+(ptrdiff_t, T*); [ABOVE]
7949 // T& operator[](ptrdiff_t, T*);
7950 void addSubscriptOverloads() {
7951 for (BuiltinCandidateTypeSet::iterator
7952 Ptr = CandidateTypes[0].pointer_begin(),
7953 PtrEnd = CandidateTypes[0].pointer_end();
7954 Ptr != PtrEnd; ++Ptr) {
7955 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7956 QualType PointeeType = (*Ptr)->getPointeeType();
7957 if (!PointeeType->isObjectType())
7960 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7962 // T& operator[](T*, ptrdiff_t)
7963 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7966 for (BuiltinCandidateTypeSet::iterator
7967 Ptr = CandidateTypes[1].pointer_begin(),
7968 PtrEnd = CandidateTypes[1].pointer_end();
7969 Ptr != PtrEnd; ++Ptr) {
7970 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7971 QualType PointeeType = (*Ptr)->getPointeeType();
7972 if (!PointeeType->isObjectType())
7975 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7977 // T& operator[](ptrdiff_t, T*)
7978 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7982 // C++ [over.built]p11:
7983 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7984 // C1 is the same type as C2 or is a derived class of C2, T is an object
7985 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7986 // there exist candidate operator functions of the form
7988 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7990 // where CV12 is the union of CV1 and CV2.
7991 void addArrowStarOverloads() {
7992 for (BuiltinCandidateTypeSet::iterator
7993 Ptr = CandidateTypes[0].pointer_begin(),
7994 PtrEnd = CandidateTypes[0].pointer_end();
7995 Ptr != PtrEnd; ++Ptr) {
7996 QualType C1Ty = (*Ptr);
7998 QualifierCollector Q1;
7999 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8000 if (!isa<RecordType>(C1))
8002 // heuristic to reduce number of builtin candidates in the set.
8003 // Add volatile/restrict version only if there are conversions to a
8004 // volatile/restrict type.
8005 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8007 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8009 for (BuiltinCandidateTypeSet::iterator
8010 MemPtr = CandidateTypes[1].member_pointer_begin(),
8011 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8012 MemPtr != MemPtrEnd; ++MemPtr) {
8013 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8014 QualType C2 = QualType(mptr->getClass(), 0);
8015 C2 = C2.getUnqualifiedType();
8016 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8018 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8020 QualType T = mptr->getPointeeType();
8021 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8022 T.isVolatileQualified())
8024 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8025 T.isRestrictQualified())
8027 T = Q1.apply(S.Context, T);
8028 QualType ResultTy = S.Context.getLValueReferenceType(T);
8029 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8034 // Note that we don't consider the first argument, since it has been
8035 // contextually converted to bool long ago. The candidates below are
8036 // therefore added as binary.
8038 // C++ [over.built]p25:
8039 // For every type T, where T is a pointer, pointer-to-member, or scoped
8040 // enumeration type, there exist candidate operator functions of the form
8042 // T operator?(bool, T, T);
8044 void addConditionalOperatorOverloads() {
8045 /// Set of (canonical) types that we've already handled.
8046 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8048 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8049 for (BuiltinCandidateTypeSet::iterator
8050 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8051 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8052 Ptr != PtrEnd; ++Ptr) {
8053 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8056 QualType ParamTypes[2] = { *Ptr, *Ptr };
8057 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8060 for (BuiltinCandidateTypeSet::iterator
8061 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8062 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8063 MemPtr != MemPtrEnd; ++MemPtr) {
8064 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8067 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8068 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8071 if (S.getLangOpts().CPlusPlus11) {
8072 for (BuiltinCandidateTypeSet::iterator
8073 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8074 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8075 Enum != EnumEnd; ++Enum) {
8076 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8079 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8082 QualType ParamTypes[2] = { *Enum, *Enum };
8083 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8090 } // end anonymous namespace
8092 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8093 /// operator overloads to the candidate set (C++ [over.built]), based
8094 /// on the operator @p Op and the arguments given. For example, if the
8095 /// operator is a binary '+', this routine might add "int
8096 /// operator+(int, int)" to cover integer addition.
8097 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8098 SourceLocation OpLoc,
8099 ArrayRef<Expr *> Args,
8100 OverloadCandidateSet &CandidateSet) {
8101 // Find all of the types that the arguments can convert to, but only
8102 // if the operator we're looking at has built-in operator candidates
8103 // that make use of these types. Also record whether we encounter non-record
8104 // candidate types or either arithmetic or enumeral candidate types.
8105 Qualifiers VisibleTypeConversionsQuals;
8106 VisibleTypeConversionsQuals.addConst();
8107 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8108 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8110 bool HasNonRecordCandidateType = false;
8111 bool HasArithmeticOrEnumeralCandidateType = false;
8112 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8113 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8114 CandidateTypes.emplace_back(*this);
8115 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8118 (Op == OO_Exclaim ||
8121 VisibleTypeConversionsQuals);
8122 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8123 CandidateTypes[ArgIdx].hasNonRecordTypes();
8124 HasArithmeticOrEnumeralCandidateType =
8125 HasArithmeticOrEnumeralCandidateType ||
8126 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8129 // Exit early when no non-record types have been added to the candidate set
8130 // for any of the arguments to the operator.
8132 // We can't exit early for !, ||, or &&, since there we have always have
8133 // 'bool' overloads.
8134 if (!HasNonRecordCandidateType &&
8135 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8138 // Setup an object to manage the common state for building overloads.
8139 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8140 VisibleTypeConversionsQuals,
8141 HasArithmeticOrEnumeralCandidateType,
8142 CandidateTypes, CandidateSet);
8144 // Dispatch over the operation to add in only those overloads which apply.
8147 case NUM_OVERLOADED_OPERATORS:
8148 llvm_unreachable("Expected an overloaded operator");
8153 case OO_Array_Delete:
8156 "Special operators don't use AddBuiltinOperatorCandidates");
8160 // C++ [over.match.oper]p3:
8161 // -- For the operator ',', the unary operator '&', or the
8162 // operator '->', the built-in candidates set is empty.
8165 case OO_Plus: // '+' is either unary or binary
8166 if (Args.size() == 1)
8167 OpBuilder.addUnaryPlusPointerOverloads();
8170 case OO_Minus: // '-' is either unary or binary
8171 if (Args.size() == 1) {
8172 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8174 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8175 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8179 case OO_Star: // '*' is either unary or binary
8180 if (Args.size() == 1)
8181 OpBuilder.addUnaryStarPointerOverloads();
8183 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8187 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8192 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8193 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8197 case OO_ExclaimEqual:
8198 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8204 case OO_GreaterEqual:
8205 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8206 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8213 case OO_GreaterGreater:
8214 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8217 case OO_Amp: // '&' is either unary or binary
8218 if (Args.size() == 1)
8219 // C++ [over.match.oper]p3:
8220 // -- For the operator ',', the unary operator '&', or the
8221 // operator '->', the built-in candidates set is empty.
8224 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8228 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8232 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8237 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8242 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8245 case OO_PercentEqual:
8246 case OO_LessLessEqual:
8247 case OO_GreaterGreaterEqual:
8251 OpBuilder.addAssignmentIntegralOverloads();
8255 OpBuilder.addExclaimOverload();
8260 OpBuilder.addAmpAmpOrPipePipeOverload();
8264 OpBuilder.addSubscriptOverloads();
8268 OpBuilder.addArrowStarOverloads();
8271 case OO_Conditional:
8272 OpBuilder.addConditionalOperatorOverloads();
8273 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8278 /// \brief Add function candidates found via argument-dependent lookup
8279 /// to the set of overloading candidates.
8281 /// This routine performs argument-dependent name lookup based on the
8282 /// given function name (which may also be an operator name) and adds
8283 /// all of the overload candidates found by ADL to the overload
8284 /// candidate set (C++ [basic.lookup.argdep]).
8286 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8288 ArrayRef<Expr *> Args,
8289 TemplateArgumentListInfo *ExplicitTemplateArgs,
8290 OverloadCandidateSet& CandidateSet,
8291 bool PartialOverloading) {
8294 // FIXME: This approach for uniquing ADL results (and removing
8295 // redundant candidates from the set) relies on pointer-equality,
8296 // which means we need to key off the canonical decl. However,
8297 // always going back to the canonical decl might not get us the
8298 // right set of default arguments. What default arguments are
8299 // we supposed to consider on ADL candidates, anyway?
8301 // FIXME: Pass in the explicit template arguments?
8302 ArgumentDependentLookup(Name, Loc, Args, Fns);
8304 // Erase all of the candidates we already knew about.
8305 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8306 CandEnd = CandidateSet.end();
8307 Cand != CandEnd; ++Cand)
8308 if (Cand->Function) {
8309 Fns.erase(Cand->Function);
8310 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8314 // For each of the ADL candidates we found, add it to the overload
8316 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8317 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8318 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8319 if (ExplicitTemplateArgs)
8322 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8323 PartialOverloading);
8325 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8326 FoundDecl, ExplicitTemplateArgs,
8327 Args, CandidateSet, PartialOverloading);
8331 /// isBetterOverloadCandidate - Determines whether the first overload
8332 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8333 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8334 const OverloadCandidate &Cand2,
8336 bool UserDefinedConversion) {
8337 // Define viable functions to be better candidates than non-viable
8340 return Cand1.Viable;
8341 else if (!Cand1.Viable)
8344 // C++ [over.match.best]p1:
8346 // -- if F is a static member function, ICS1(F) is defined such
8347 // that ICS1(F) is neither better nor worse than ICS1(G) for
8348 // any function G, and, symmetrically, ICS1(G) is neither
8349 // better nor worse than ICS1(F).
8350 unsigned StartArg = 0;
8351 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8354 // C++ [over.match.best]p1:
8355 // A viable function F1 is defined to be a better function than another
8356 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8357 // conversion sequence than ICSi(F2), and then...
8358 unsigned NumArgs = Cand1.NumConversions;
8359 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8360 bool HasBetterConversion = false;
8361 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8362 switch (CompareImplicitConversionSequences(S,
8363 Cand1.Conversions[ArgIdx],
8364 Cand2.Conversions[ArgIdx])) {
8365 case ImplicitConversionSequence::Better:
8366 // Cand1 has a better conversion sequence.
8367 HasBetterConversion = true;
8370 case ImplicitConversionSequence::Worse:
8371 // Cand1 can't be better than Cand2.
8374 case ImplicitConversionSequence::Indistinguishable:
8380 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8381 // ICSj(F2), or, if not that,
8382 if (HasBetterConversion)
8385 // -- the context is an initialization by user-defined conversion
8386 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8387 // from the return type of F1 to the destination type (i.e.,
8388 // the type of the entity being initialized) is a better
8389 // conversion sequence than the standard conversion sequence
8390 // from the return type of F2 to the destination type.
8391 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8392 isa<CXXConversionDecl>(Cand1.Function) &&
8393 isa<CXXConversionDecl>(Cand2.Function)) {
8394 // First check whether we prefer one of the conversion functions over the
8395 // other. This only distinguishes the results in non-standard, extension
8396 // cases such as the conversion from a lambda closure type to a function
8397 // pointer or block.
8398 ImplicitConversionSequence::CompareKind Result =
8399 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8400 if (Result == ImplicitConversionSequence::Indistinguishable)
8401 Result = CompareStandardConversionSequences(S,
8402 Cand1.FinalConversion,
8403 Cand2.FinalConversion);
8405 if (Result != ImplicitConversionSequence::Indistinguishable)
8406 return Result == ImplicitConversionSequence::Better;
8408 // FIXME: Compare kind of reference binding if conversion functions
8409 // convert to a reference type used in direct reference binding, per
8410 // C++14 [over.match.best]p1 section 2 bullet 3.
8413 // -- F1 is a non-template function and F2 is a function template
8414 // specialization, or, if not that,
8415 bool Cand1IsSpecialization = Cand1.Function &&
8416 Cand1.Function->getPrimaryTemplate();
8417 bool Cand2IsSpecialization = Cand2.Function &&
8418 Cand2.Function->getPrimaryTemplate();
8419 if (Cand1IsSpecialization != Cand2IsSpecialization)
8420 return Cand2IsSpecialization;
8422 // -- F1 and F2 are function template specializations, and the function
8423 // template for F1 is more specialized than the template for F2
8424 // according to the partial ordering rules described in 14.5.5.2, or,
8426 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8427 if (FunctionTemplateDecl *BetterTemplate
8428 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8429 Cand2.Function->getPrimaryTemplate(),
8431 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8433 Cand1.ExplicitCallArguments,
8434 Cand2.ExplicitCallArguments))
8435 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8438 // Check for enable_if value-based overload resolution.
8439 if (Cand1.Function && Cand2.Function &&
8440 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8441 Cand2.Function->hasAttr<EnableIfAttr>())) {
8442 // FIXME: The next several lines are just
8443 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8444 // instead of reverse order which is how they're stored in the AST.
8446 if (Cand1.Function->hasAttrs()) {
8447 Cand1Attrs = Cand1.Function->getAttrs();
8448 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8451 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8455 if (Cand2.Function->hasAttrs()) {
8456 Cand2Attrs = Cand2.Function->getAttrs();
8457 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8460 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8463 // Candidate 1 is better if it has strictly more attributes and
8464 // the common sequence is identical.
8465 if (Cand1Attrs.size() <= Cand2Attrs.size())
8468 auto Cand1I = Cand1Attrs.begin();
8469 for (auto &Cand2A : Cand2Attrs) {
8470 auto &Cand1A = *Cand1I++;
8471 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8472 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8473 S.getASTContext(), true);
8474 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8475 S.getASTContext(), true);
8476 if (Cand1ID != Cand2ID)
8486 /// \brief Computes the best viable function (C++ 13.3.3)
8487 /// within an overload candidate set.
8489 /// \param Loc The location of the function name (or operator symbol) for
8490 /// which overload resolution occurs.
8492 /// \param Best If overload resolution was successful or found a deleted
8493 /// function, \p Best points to the candidate function found.
8495 /// \returns The result of overload resolution.
8497 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8499 bool UserDefinedConversion) {
8500 // Find the best viable function.
8502 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8504 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8505 UserDefinedConversion))
8509 // If we didn't find any viable functions, abort.
8511 return OR_No_Viable_Function;
8513 // Make sure that this function is better than every other viable
8514 // function. If not, we have an ambiguity.
8515 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8518 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8519 UserDefinedConversion)) {
8521 return OR_Ambiguous;
8525 // Best is the best viable function.
8526 if (Best->Function &&
8527 (Best->Function->isDeleted() ||
8528 S.isFunctionConsideredUnavailable(Best->Function)))
8536 enum OverloadCandidateKind {
8540 oc_function_template,
8542 oc_constructor_template,
8543 oc_implicit_default_constructor,
8544 oc_implicit_copy_constructor,
8545 oc_implicit_move_constructor,
8546 oc_implicit_copy_assignment,
8547 oc_implicit_move_assignment,
8548 oc_implicit_inherited_constructor
8551 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8553 std::string &Description) {
8554 bool isTemplate = false;
8556 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8558 Description = S.getTemplateArgumentBindingsText(
8559 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8562 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8563 if (!Ctor->isImplicit())
8564 return isTemplate ? oc_constructor_template : oc_constructor;
8566 if (Ctor->getInheritedConstructor())
8567 return oc_implicit_inherited_constructor;
8569 if (Ctor->isDefaultConstructor())
8570 return oc_implicit_default_constructor;
8572 if (Ctor->isMoveConstructor())
8573 return oc_implicit_move_constructor;
8575 assert(Ctor->isCopyConstructor() &&
8576 "unexpected sort of implicit constructor");
8577 return oc_implicit_copy_constructor;
8580 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8581 // This actually gets spelled 'candidate function' for now, but
8582 // it doesn't hurt to split it out.
8583 if (!Meth->isImplicit())
8584 return isTemplate ? oc_method_template : oc_method;
8586 if (Meth->isMoveAssignmentOperator())
8587 return oc_implicit_move_assignment;
8589 if (Meth->isCopyAssignmentOperator())
8590 return oc_implicit_copy_assignment;
8592 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8596 return isTemplate ? oc_function_template : oc_function;
8599 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8600 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8603 Ctor = Ctor->getInheritedConstructor();
8606 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8609 } // end anonymous namespace
8611 // Notes the location of an overload candidate.
8612 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8614 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8615 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8616 << (unsigned) K << FnDesc;
8617 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8618 Diag(Fn->getLocation(), PD);
8619 MaybeEmitInheritedConstructorNote(*this, Fn);
8622 // Notes the location of all overload candidates designated through
8624 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8625 assert(OverloadedExpr->getType() == Context.OverloadTy);
8627 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8628 OverloadExpr *OvlExpr = Ovl.Expression;
8630 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8631 IEnd = OvlExpr->decls_end();
8633 if (FunctionTemplateDecl *FunTmpl =
8634 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8635 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8636 } else if (FunctionDecl *Fun
8637 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8638 NoteOverloadCandidate(Fun, DestType);
8643 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
8644 /// "lead" diagnostic; it will be given two arguments, the source and
8645 /// target types of the conversion.
8646 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8648 SourceLocation CaretLoc,
8649 const PartialDiagnostic &PDiag) const {
8650 S.Diag(CaretLoc, PDiag)
8651 << Ambiguous.getFromType() << Ambiguous.getToType();
8652 // FIXME: The note limiting machinery is borrowed from
8653 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8654 // refactoring here.
8655 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8656 unsigned CandsShown = 0;
8657 AmbiguousConversionSequence::const_iterator I, E;
8658 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8659 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8662 S.NoteOverloadCandidate(*I);
8665 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8668 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8670 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8671 assert(Conv.isBad());
8672 assert(Cand->Function && "for now, candidate must be a function");
8673 FunctionDecl *Fn = Cand->Function;
8675 // There's a conversion slot for the object argument if this is a
8676 // non-constructor method. Note that 'I' corresponds the
8677 // conversion-slot index.
8678 bool isObjectArgument = false;
8679 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8681 isObjectArgument = true;
8687 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8689 Expr *FromExpr = Conv.Bad.FromExpr;
8690 QualType FromTy = Conv.Bad.getFromType();
8691 QualType ToTy = Conv.Bad.getToType();
8693 if (FromTy == S.Context.OverloadTy) {
8694 assert(FromExpr && "overload set argument came from implicit argument?");
8695 Expr *E = FromExpr->IgnoreParens();
8696 if (isa<UnaryOperator>(E))
8697 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8698 DeclarationName Name = cast<OverloadExpr>(E)->getName();
8700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8701 << (unsigned) FnKind << FnDesc
8702 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8703 << ToTy << Name << I+1;
8704 MaybeEmitInheritedConstructorNote(S, Fn);
8708 // Do some hand-waving analysis to see if the non-viability is due
8709 // to a qualifier mismatch.
8710 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8711 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8712 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8713 CToTy = RT->getPointeeType();
8715 // TODO: detect and diagnose the full richness of const mismatches.
8716 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8717 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8718 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8721 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8722 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8723 Qualifiers FromQs = CFromTy.getQualifiers();
8724 Qualifiers ToQs = CToTy.getQualifiers();
8726 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8728 << (unsigned) FnKind << FnDesc
8729 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8731 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8732 << (unsigned) isObjectArgument << I+1;
8733 MaybeEmitInheritedConstructorNote(S, Fn);
8737 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8739 << (unsigned) FnKind << FnDesc
8740 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8742 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8743 << (unsigned) isObjectArgument << I+1;
8744 MaybeEmitInheritedConstructorNote(S, Fn);
8748 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8750 << (unsigned) FnKind << FnDesc
8751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8753 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8754 << (unsigned) isObjectArgument << I+1;
8755 MaybeEmitInheritedConstructorNote(S, Fn);
8759 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8760 assert(CVR && "unexpected qualifiers mismatch");
8762 if (isObjectArgument) {
8763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8764 << (unsigned) FnKind << FnDesc
8765 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8766 << FromTy << (CVR - 1);
8768 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8769 << (unsigned) FnKind << FnDesc
8770 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8771 << FromTy << (CVR - 1) << I+1;
8773 MaybeEmitInheritedConstructorNote(S, Fn);
8777 // Special diagnostic for failure to convert an initializer list, since
8778 // telling the user that it has type void is not useful.
8779 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8780 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8781 << (unsigned) FnKind << FnDesc
8782 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8783 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8784 MaybeEmitInheritedConstructorNote(S, Fn);
8788 // Diagnose references or pointers to incomplete types differently,
8789 // since it's far from impossible that the incompleteness triggered
8791 QualType TempFromTy = FromTy.getNonReferenceType();
8792 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8793 TempFromTy = PTy->getPointeeType();
8794 if (TempFromTy->isIncompleteType()) {
8795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8796 << (unsigned) FnKind << FnDesc
8797 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8798 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8799 MaybeEmitInheritedConstructorNote(S, Fn);
8803 // Diagnose base -> derived pointer conversions.
8804 unsigned BaseToDerivedConversion = 0;
8805 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8806 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8807 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8808 FromPtrTy->getPointeeType()) &&
8809 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8810 !ToPtrTy->getPointeeType()->isIncompleteType() &&
8811 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8812 FromPtrTy->getPointeeType()))
8813 BaseToDerivedConversion = 1;
8815 } else if (const ObjCObjectPointerType *FromPtrTy
8816 = FromTy->getAs<ObjCObjectPointerType>()) {
8817 if (const ObjCObjectPointerType *ToPtrTy
8818 = ToTy->getAs<ObjCObjectPointerType>())
8819 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8820 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8821 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8822 FromPtrTy->getPointeeType()) &&
8823 FromIface->isSuperClassOf(ToIface))
8824 BaseToDerivedConversion = 2;
8825 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8826 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8827 !FromTy->isIncompleteType() &&
8828 !ToRefTy->getPointeeType()->isIncompleteType() &&
8829 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8830 BaseToDerivedConversion = 3;
8831 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8832 ToTy.getNonReferenceType().getCanonicalType() ==
8833 FromTy.getNonReferenceType().getCanonicalType()) {
8834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8835 << (unsigned) FnKind << FnDesc
8836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8837 << (unsigned) isObjectArgument << I + 1;
8838 MaybeEmitInheritedConstructorNote(S, Fn);
8843 if (BaseToDerivedConversion) {
8844 S.Diag(Fn->getLocation(),
8845 diag::note_ovl_candidate_bad_base_to_derived_conv)
8846 << (unsigned) FnKind << FnDesc
8847 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8848 << (BaseToDerivedConversion - 1)
8849 << FromTy << ToTy << I+1;
8850 MaybeEmitInheritedConstructorNote(S, Fn);
8854 if (isa<ObjCObjectPointerType>(CFromTy) &&
8855 isa<PointerType>(CToTy)) {
8856 Qualifiers FromQs = CFromTy.getQualifiers();
8857 Qualifiers ToQs = CToTy.getQualifiers();
8858 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8860 << (unsigned) FnKind << FnDesc
8861 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8862 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8863 MaybeEmitInheritedConstructorNote(S, Fn);
8868 // Emit the generic diagnostic and, optionally, add the hints to it.
8869 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8870 FDiag << (unsigned) FnKind << FnDesc
8871 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8872 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8873 << (unsigned) (Cand->Fix.Kind);
8875 // If we can fix the conversion, suggest the FixIts.
8876 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8877 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8879 S.Diag(Fn->getLocation(), FDiag);
8881 MaybeEmitInheritedConstructorNote(S, Fn);
8884 /// Additional arity mismatch diagnosis specific to a function overload
8885 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8886 /// over a candidate in any candidate set.
8887 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8889 FunctionDecl *Fn = Cand->Function;
8890 unsigned MinParams = Fn->getMinRequiredArguments();
8892 // With invalid overloaded operators, it's possible that we think we
8893 // have an arity mismatch when in fact it looks like we have the
8894 // right number of arguments, because only overloaded operators have
8895 // the weird behavior of overloading member and non-member functions.
8896 // Just don't report anything.
8897 if (Fn->isInvalidDecl() &&
8898 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8901 if (NumArgs < MinParams) {
8902 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8903 (Cand->FailureKind == ovl_fail_bad_deduction &&
8904 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8906 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8907 (Cand->FailureKind == ovl_fail_bad_deduction &&
8908 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8914 /// General arity mismatch diagnosis over a candidate in a candidate set.
8915 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8916 assert(isa<FunctionDecl>(D) &&
8917 "The templated declaration should at least be a function"
8918 " when diagnosing bad template argument deduction due to too many"
8919 " or too few arguments");
8921 FunctionDecl *Fn = cast<FunctionDecl>(D);
8923 // TODO: treat calls to a missing default constructor as a special case
8924 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8925 unsigned MinParams = Fn->getMinRequiredArguments();
8927 // at least / at most / exactly
8928 unsigned mode, modeCount;
8929 if (NumFormalArgs < MinParams) {
8930 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8931 FnTy->isTemplateVariadic())
8932 mode = 0; // "at least"
8934 mode = 2; // "exactly"
8935 modeCount = MinParams;
8937 if (MinParams != FnTy->getNumParams())
8938 mode = 1; // "at most"
8940 mode = 2; // "exactly"
8941 modeCount = FnTy->getNumParams();
8944 std::string Description;
8945 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8947 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8948 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8949 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8950 << mode << Fn->getParamDecl(0) << NumFormalArgs;
8952 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8953 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8954 << mode << modeCount << NumFormalArgs;
8955 MaybeEmitInheritedConstructorNote(S, Fn);
8958 /// Arity mismatch diagnosis specific to a function overload candidate.
8959 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8960 unsigned NumFormalArgs) {
8961 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8962 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8965 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
8966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8967 return FD->getDescribedFunctionTemplate();
8968 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8969 return RD->getDescribedClassTemplate();
8971 llvm_unreachable("Unsupported: Getting the described template declaration"
8972 " for bad deduction diagnosis");
8975 /// Diagnose a failed template-argument deduction.
8976 static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8977 DeductionFailureInfo &DeductionFailure,
8979 TemplateParameter Param = DeductionFailure.getTemplateParameter();
8981 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8982 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8983 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8984 switch (DeductionFailure.Result) {
8985 case Sema::TDK_Success:
8986 llvm_unreachable("TDK_success while diagnosing bad deduction");
8988 case Sema::TDK_Incomplete: {
8989 assert(ParamD && "no parameter found for incomplete deduction result");
8990 S.Diag(Templated->getLocation(),
8991 diag::note_ovl_candidate_incomplete_deduction)
8992 << ParamD->getDeclName();
8993 MaybeEmitInheritedConstructorNote(S, Templated);
8997 case Sema::TDK_Underqualified: {
8998 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8999 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9001 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9003 // Param will have been canonicalized, but it should just be a
9004 // qualified version of ParamD, so move the qualifiers to that.
9005 QualifierCollector Qs;
9007 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9008 assert(S.Context.hasSameType(Param, NonCanonParam));
9010 // Arg has also been canonicalized, but there's nothing we can do
9011 // about that. It also doesn't matter as much, because it won't
9012 // have any template parameters in it (because deduction isn't
9013 // done on dependent types).
9014 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9016 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9017 << ParamD->getDeclName() << Arg << NonCanonParam;
9018 MaybeEmitInheritedConstructorNote(S, Templated);
9022 case Sema::TDK_Inconsistent: {
9023 assert(ParamD && "no parameter found for inconsistent deduction result");
9025 if (isa<TemplateTypeParmDecl>(ParamD))
9027 else if (isa<NonTypeTemplateParmDecl>(ParamD))
9033 S.Diag(Templated->getLocation(),
9034 diag::note_ovl_candidate_inconsistent_deduction)
9035 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9036 << *DeductionFailure.getSecondArg();
9037 MaybeEmitInheritedConstructorNote(S, Templated);
9041 case Sema::TDK_InvalidExplicitArguments:
9042 assert(ParamD && "no parameter found for invalid explicit arguments");
9043 if (ParamD->getDeclName())
9044 S.Diag(Templated->getLocation(),
9045 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9046 << ParamD->getDeclName();
9049 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9050 index = TTP->getIndex();
9051 else if (NonTypeTemplateParmDecl *NTTP
9052 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9053 index = NTTP->getIndex();
9055 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9056 S.Diag(Templated->getLocation(),
9057 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9060 MaybeEmitInheritedConstructorNote(S, Templated);
9063 case Sema::TDK_TooManyArguments:
9064 case Sema::TDK_TooFewArguments:
9065 DiagnoseArityMismatch(S, Templated, NumArgs);
9068 case Sema::TDK_InstantiationDepth:
9069 S.Diag(Templated->getLocation(),
9070 diag::note_ovl_candidate_instantiation_depth);
9071 MaybeEmitInheritedConstructorNote(S, Templated);
9074 case Sema::TDK_SubstitutionFailure: {
9075 // Format the template argument list into the argument string.
9076 SmallString<128> TemplateArgString;
9077 if (TemplateArgumentList *Args =
9078 DeductionFailure.getTemplateArgumentList()) {
9079 TemplateArgString = " ";
9080 TemplateArgString += S.getTemplateArgumentBindingsText(
9081 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9084 // If this candidate was disabled by enable_if, say so.
9085 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9086 if (PDiag && PDiag->second.getDiagID() ==
9087 diag::err_typename_nested_not_found_enable_if) {
9088 // FIXME: Use the source range of the condition, and the fully-qualified
9089 // name of the enable_if template. These are both present in PDiag.
9090 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9091 << "'enable_if'" << TemplateArgString;
9095 // Format the SFINAE diagnostic into the argument string.
9096 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9097 // formatted message in another diagnostic.
9098 SmallString<128> SFINAEArgString;
9101 SFINAEArgString = ": ";
9102 R = SourceRange(PDiag->first, PDiag->first);
9103 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9106 S.Diag(Templated->getLocation(),
9107 diag::note_ovl_candidate_substitution_failure)
9108 << TemplateArgString << SFINAEArgString << R;
9109 MaybeEmitInheritedConstructorNote(S, Templated);
9113 case Sema::TDK_FailedOverloadResolution: {
9114 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9115 S.Diag(Templated->getLocation(),
9116 diag::note_ovl_candidate_failed_overload_resolution)
9117 << R.Expression->getName();
9121 case Sema::TDK_NonDeducedMismatch: {
9122 // FIXME: Provide a source location to indicate what we couldn't match.
9123 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9124 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9125 if (FirstTA.getKind() == TemplateArgument::Template &&
9126 SecondTA.getKind() == TemplateArgument::Template) {
9127 TemplateName FirstTN = FirstTA.getAsTemplate();
9128 TemplateName SecondTN = SecondTA.getAsTemplate();
9129 if (FirstTN.getKind() == TemplateName::Template &&
9130 SecondTN.getKind() == TemplateName::Template) {
9131 if (FirstTN.getAsTemplateDecl()->getName() ==
9132 SecondTN.getAsTemplateDecl()->getName()) {
9133 // FIXME: This fixes a bad diagnostic where both templates are named
9134 // the same. This particular case is a bit difficult since:
9135 // 1) It is passed as a string to the diagnostic printer.
9136 // 2) The diagnostic printer only attempts to find a better
9137 // name for types, not decls.
9138 // Ideally, this should folded into the diagnostic printer.
9139 S.Diag(Templated->getLocation(),
9140 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9141 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9146 // FIXME: For generic lambda parameters, check if the function is a lambda
9147 // call operator, and if so, emit a prettier and more informative
9148 // diagnostic that mentions 'auto' and lambda in addition to
9149 // (or instead of?) the canonical template type parameters.
9150 S.Diag(Templated->getLocation(),
9151 diag::note_ovl_candidate_non_deduced_mismatch)
9152 << FirstTA << SecondTA;
9155 // TODO: diagnose these individually, then kill off
9156 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9157 case Sema::TDK_MiscellaneousDeductionFailure:
9158 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9159 MaybeEmitInheritedConstructorNote(S, Templated);
9164 /// Diagnose a failed template-argument deduction, for function calls.
9165 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9167 unsigned TDK = Cand->DeductionFailure.Result;
9168 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9169 if (CheckArityMismatch(S, Cand, NumArgs))
9172 DiagnoseBadDeduction(S, Cand->Function, // pattern
9173 Cand->DeductionFailure, NumArgs);
9176 /// CUDA: diagnose an invalid call across targets.
9177 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9178 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9179 FunctionDecl *Callee = Cand->Function;
9181 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9182 CalleeTarget = S.IdentifyCUDATarget(Callee);
9185 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9187 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9188 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9190 // This could be an implicit constructor for which we could not infer the
9191 // target due to a collsion. Diagnose that case.
9192 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9193 if (Meth != nullptr && Meth->isImplicit()) {
9194 CXXRecordDecl *ParentClass = Meth->getParent();
9195 Sema::CXXSpecialMember CSM;
9200 case oc_implicit_default_constructor:
9201 CSM = Sema::CXXDefaultConstructor;
9203 case oc_implicit_copy_constructor:
9204 CSM = Sema::CXXCopyConstructor;
9206 case oc_implicit_move_constructor:
9207 CSM = Sema::CXXMoveConstructor;
9209 case oc_implicit_copy_assignment:
9210 CSM = Sema::CXXCopyAssignment;
9212 case oc_implicit_move_assignment:
9213 CSM = Sema::CXXMoveAssignment;
9217 bool ConstRHS = false;
9218 if (Meth->getNumParams()) {
9219 if (const ReferenceType *RT =
9220 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9221 ConstRHS = RT->getPointeeType().isConstQualified();
9225 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9226 /* ConstRHS */ ConstRHS,
9227 /* Diagnose */ true);
9231 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9232 FunctionDecl *Callee = Cand->Function;
9233 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9235 S.Diag(Callee->getLocation(),
9236 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9237 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9240 /// Generates a 'note' diagnostic for an overload candidate. We've
9241 /// already generated a primary error at the call site.
9243 /// It really does need to be a single diagnostic with its caret
9244 /// pointed at the candidate declaration. Yes, this creates some
9245 /// major challenges of technical writing. Yes, this makes pointing
9246 /// out problems with specific arguments quite awkward. It's still
9247 /// better than generating twenty screens of text for every failed
9250 /// It would be great to be able to express per-candidate problems
9251 /// more richly for those diagnostic clients that cared, but we'd
9252 /// still have to be just as careful with the default diagnostics.
9253 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9255 FunctionDecl *Fn = Cand->Function;
9257 // Note deleted candidates, but only if they're viable.
9258 if (Cand->Viable && (Fn->isDeleted() ||
9259 S.isFunctionConsideredUnavailable(Fn))) {
9261 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9265 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9266 MaybeEmitInheritedConstructorNote(S, Fn);
9270 // We don't really have anything else to say about viable candidates.
9272 S.NoteOverloadCandidate(Fn);
9276 switch (Cand->FailureKind) {
9277 case ovl_fail_too_many_arguments:
9278 case ovl_fail_too_few_arguments:
9279 return DiagnoseArityMismatch(S, Cand, NumArgs);
9281 case ovl_fail_bad_deduction:
9282 return DiagnoseBadDeduction(S, Cand, NumArgs);
9284 case ovl_fail_illegal_constructor: {
9285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9286 << (Fn->getPrimaryTemplate() ? 1 : 0);
9287 MaybeEmitInheritedConstructorNote(S, Fn);
9291 case ovl_fail_trivial_conversion:
9292 case ovl_fail_bad_final_conversion:
9293 case ovl_fail_final_conversion_not_exact:
9294 return S.NoteOverloadCandidate(Fn);
9296 case ovl_fail_bad_conversion: {
9297 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9298 for (unsigned N = Cand->NumConversions; I != N; ++I)
9299 if (Cand->Conversions[I].isBad())
9300 return DiagnoseBadConversion(S, Cand, I);
9302 // FIXME: this currently happens when we're called from SemaInit
9303 // when user-conversion overload fails. Figure out how to handle
9304 // those conditions and diagnose them well.
9305 return S.NoteOverloadCandidate(Fn);
9308 case ovl_fail_bad_target:
9309 return DiagnoseBadTarget(S, Cand);
9311 case ovl_fail_enable_if:
9312 return DiagnoseFailedEnableIfAttr(S, Cand);
9316 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9317 // Desugar the type of the surrogate down to a function type,
9318 // retaining as many typedefs as possible while still showing
9319 // the function type (and, therefore, its parameter types).
9320 QualType FnType = Cand->Surrogate->getConversionType();
9321 bool isLValueReference = false;
9322 bool isRValueReference = false;
9323 bool isPointer = false;
9324 if (const LValueReferenceType *FnTypeRef =
9325 FnType->getAs<LValueReferenceType>()) {
9326 FnType = FnTypeRef->getPointeeType();
9327 isLValueReference = true;
9328 } else if (const RValueReferenceType *FnTypeRef =
9329 FnType->getAs<RValueReferenceType>()) {
9330 FnType = FnTypeRef->getPointeeType();
9331 isRValueReference = true;
9333 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9334 FnType = FnTypePtr->getPointeeType();
9337 // Desugar down to a function type.
9338 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9339 // Reconstruct the pointer/reference as appropriate.
9340 if (isPointer) FnType = S.Context.getPointerType(FnType);
9341 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9342 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9344 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9346 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9349 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9350 SourceLocation OpLoc,
9351 OverloadCandidate *Cand) {
9352 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9353 std::string TypeStr("operator");
9356 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9357 if (Cand->NumConversions == 1) {
9359 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9362 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9364 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9368 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9369 OverloadCandidate *Cand) {
9370 unsigned NoOperands = Cand->NumConversions;
9371 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9372 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9373 if (ICS.isBad()) break; // all meaningless after first invalid
9374 if (!ICS.isAmbiguous()) continue;
9376 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9377 S.PDiag(diag::note_ambiguous_type_conversion));
9381 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9383 return Cand->Function->getLocation();
9384 if (Cand->IsSurrogate)
9385 return Cand->Surrogate->getLocation();
9386 return SourceLocation();
9389 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9390 switch ((Sema::TemplateDeductionResult)DFI.Result) {
9391 case Sema::TDK_Success:
9392 llvm_unreachable("TDK_success while diagnosing bad deduction");
9394 case Sema::TDK_Invalid:
9395 case Sema::TDK_Incomplete:
9398 case Sema::TDK_Underqualified:
9399 case Sema::TDK_Inconsistent:
9402 case Sema::TDK_SubstitutionFailure:
9403 case Sema::TDK_NonDeducedMismatch:
9404 case Sema::TDK_MiscellaneousDeductionFailure:
9407 case Sema::TDK_InstantiationDepth:
9408 case Sema::TDK_FailedOverloadResolution:
9411 case Sema::TDK_InvalidExplicitArguments:
9414 case Sema::TDK_TooManyArguments:
9415 case Sema::TDK_TooFewArguments:
9418 llvm_unreachable("Unhandled deduction result");
9422 struct CompareOverloadCandidatesForDisplay {
9426 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9427 : S(S), NumArgs(nArgs) {}
9429 bool operator()(const OverloadCandidate *L,
9430 const OverloadCandidate *R) {
9431 // Fast-path this check.
9432 if (L == R) return false;
9434 // Order first by viability.
9436 if (!R->Viable) return true;
9438 // TODO: introduce a tri-valued comparison for overload
9439 // candidates. Would be more worthwhile if we had a sort
9440 // that could exploit it.
9441 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9442 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9443 } else if (R->Viable)
9446 assert(L->Viable == R->Viable);
9448 // Criteria by which we can sort non-viable candidates:
9450 // 1. Arity mismatches come after other candidates.
9451 if (L->FailureKind == ovl_fail_too_many_arguments ||
9452 L->FailureKind == ovl_fail_too_few_arguments) {
9453 if (R->FailureKind == ovl_fail_too_many_arguments ||
9454 R->FailureKind == ovl_fail_too_few_arguments) {
9455 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9456 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9457 if (LDist == RDist) {
9458 if (L->FailureKind == R->FailureKind)
9459 // Sort non-surrogates before surrogates.
9460 return !L->IsSurrogate && R->IsSurrogate;
9461 // Sort candidates requiring fewer parameters than there were
9462 // arguments given after candidates requiring more parameters
9463 // than there were arguments given.
9464 return L->FailureKind == ovl_fail_too_many_arguments;
9466 return LDist < RDist;
9470 if (R->FailureKind == ovl_fail_too_many_arguments ||
9471 R->FailureKind == ovl_fail_too_few_arguments)
9474 // 2. Bad conversions come first and are ordered by the number
9475 // of bad conversions and quality of good conversions.
9476 if (L->FailureKind == ovl_fail_bad_conversion) {
9477 if (R->FailureKind != ovl_fail_bad_conversion)
9480 // The conversion that can be fixed with a smaller number of changes,
9482 unsigned numLFixes = L->Fix.NumConversionsFixed;
9483 unsigned numRFixes = R->Fix.NumConversionsFixed;
9484 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9485 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9486 if (numLFixes != numRFixes) {
9487 return numLFixes < numRFixes;
9490 // If there's any ordering between the defined conversions...
9491 // FIXME: this might not be transitive.
9492 assert(L->NumConversions == R->NumConversions);
9495 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9496 for (unsigned E = L->NumConversions; I != E; ++I) {
9497 switch (CompareImplicitConversionSequences(S,
9499 R->Conversions[I])) {
9500 case ImplicitConversionSequence::Better:
9504 case ImplicitConversionSequence::Worse:
9508 case ImplicitConversionSequence::Indistinguishable:
9512 if (leftBetter > 0) return true;
9513 if (leftBetter < 0) return false;
9515 } else if (R->FailureKind == ovl_fail_bad_conversion)
9518 if (L->FailureKind == ovl_fail_bad_deduction) {
9519 if (R->FailureKind != ovl_fail_bad_deduction)
9522 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9523 return RankDeductionFailure(L->DeductionFailure)
9524 < RankDeductionFailure(R->DeductionFailure);
9525 } else if (R->FailureKind == ovl_fail_bad_deduction)
9531 // Sort everything else by location.
9532 SourceLocation LLoc = GetLocationForCandidate(L);
9533 SourceLocation RLoc = GetLocationForCandidate(R);
9535 // Put candidates without locations (e.g. builtins) at the end.
9536 if (LLoc.isInvalid()) return false;
9537 if (RLoc.isInvalid()) return true;
9539 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9544 /// CompleteNonViableCandidate - Normally, overload resolution only
9545 /// computes up to the first. Produces the FixIt set if possible.
9546 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9547 ArrayRef<Expr *> Args) {
9548 assert(!Cand->Viable);
9550 // Don't do anything on failures other than bad conversion.
9551 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9553 // We only want the FixIts if all the arguments can be corrected.
9554 bool Unfixable = false;
9555 // Use a implicit copy initialization to check conversion fixes.
9556 Cand->Fix.setConversionChecker(TryCopyInitialization);
9558 // Skip forward to the first bad conversion.
9559 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9560 unsigned ConvCount = Cand->NumConversions;
9562 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9564 if (Cand->Conversions[ConvIdx - 1].isBad()) {
9565 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9570 if (ConvIdx == ConvCount)
9573 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9574 "remaining conversion is initialized?");
9576 // FIXME: this should probably be preserved from the overload
9577 // operation somehow.
9578 bool SuppressUserConversions = false;
9580 const FunctionProtoType* Proto;
9581 unsigned ArgIdx = ConvIdx;
9583 if (Cand->IsSurrogate) {
9585 = Cand->Surrogate->getConversionType().getNonReferenceType();
9586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9587 ConvType = ConvPtrType->getPointeeType();
9588 Proto = ConvType->getAs<FunctionProtoType>();
9590 } else if (Cand->Function) {
9591 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9592 if (isa<CXXMethodDecl>(Cand->Function) &&
9593 !isa<CXXConstructorDecl>(Cand->Function))
9596 // Builtin binary operator with a bad first conversion.
9597 assert(ConvCount <= 3);
9598 for (; ConvIdx != ConvCount; ++ConvIdx)
9599 Cand->Conversions[ConvIdx]
9600 = TryCopyInitialization(S, Args[ConvIdx],
9601 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9602 SuppressUserConversions,
9603 /*InOverloadResolution*/ true,
9604 /*AllowObjCWritebackConversion=*/
9605 S.getLangOpts().ObjCAutoRefCount);
9609 // Fill in the rest of the conversions.
9610 unsigned NumParams = Proto->getNumParams();
9611 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9612 if (ArgIdx < NumParams) {
9613 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9614 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9615 /*InOverloadResolution=*/true,
9616 /*AllowObjCWritebackConversion=*/
9617 S.getLangOpts().ObjCAutoRefCount);
9618 // Store the FixIt in the candidate if it exists.
9619 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9620 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9623 Cand->Conversions[ConvIdx].setEllipsis();
9627 /// PrintOverloadCandidates - When overload resolution fails, prints
9628 /// diagnostic messages containing the candidates in the candidate
9630 void OverloadCandidateSet::NoteCandidates(Sema &S,
9631 OverloadCandidateDisplayKind OCD,
9632 ArrayRef<Expr *> Args,
9634 SourceLocation OpLoc) {
9635 // Sort the candidates by viability and position. Sorting directly would
9636 // be prohibitive, so we make a set of pointers and sort those.
9637 SmallVector<OverloadCandidate*, 32> Cands;
9638 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9639 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9641 Cands.push_back(Cand);
9642 else if (OCD == OCD_AllCandidates) {
9643 CompleteNonViableCandidate(S, Cand, Args);
9644 if (Cand->Function || Cand->IsSurrogate)
9645 Cands.push_back(Cand);
9646 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9647 // want to list every possible builtin candidate.
9651 std::sort(Cands.begin(), Cands.end(),
9652 CompareOverloadCandidatesForDisplay(S, Args.size()));
9654 bool ReportedAmbiguousConversions = false;
9656 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9657 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9658 unsigned CandsShown = 0;
9659 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9660 OverloadCandidate *Cand = *I;
9662 // Set an arbitrary limit on the number of candidate functions we'll spam
9663 // the user with. FIXME: This limit should depend on details of the
9665 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9671 NoteFunctionCandidate(S, Cand, Args.size());
9672 else if (Cand->IsSurrogate)
9673 NoteSurrogateCandidate(S, Cand);
9675 assert(Cand->Viable &&
9676 "Non-viable built-in candidates are not added to Cands.");
9677 // Generally we only see ambiguities including viable builtin
9678 // operators if overload resolution got screwed up by an
9679 // ambiguous user-defined conversion.
9681 // FIXME: It's quite possible for different conversions to see
9682 // different ambiguities, though.
9683 if (!ReportedAmbiguousConversions) {
9684 NoteAmbiguousUserConversions(S, OpLoc, Cand);
9685 ReportedAmbiguousConversions = true;
9688 // If this is a viable builtin, print it.
9689 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9694 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9697 static SourceLocation
9698 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9699 return Cand->Specialization ? Cand->Specialization->getLocation()
9704 struct CompareTemplateSpecCandidatesForDisplay {
9706 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9708 bool operator()(const TemplateSpecCandidate *L,
9709 const TemplateSpecCandidate *R) {
9710 // Fast-path this check.
9714 // Assuming that both candidates are not matches...
9716 // Sort by the ranking of deduction failures.
9717 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9718 return RankDeductionFailure(L->DeductionFailure) <
9719 RankDeductionFailure(R->DeductionFailure);
9721 // Sort everything else by location.
9722 SourceLocation LLoc = GetLocationForCandidate(L);
9723 SourceLocation RLoc = GetLocationForCandidate(R);
9725 // Put candidates without locations (e.g. builtins) at the end.
9726 if (LLoc.isInvalid())
9728 if (RLoc.isInvalid())
9731 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9736 /// Diagnose a template argument deduction failure.
9737 /// We are treating these failures as overload failures due to bad
9739 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9740 DiagnoseBadDeduction(S, Specialization, // pattern
9741 DeductionFailure, /*NumArgs=*/0);
9744 void TemplateSpecCandidateSet::destroyCandidates() {
9745 for (iterator i = begin(), e = end(); i != e; ++i) {
9746 i->DeductionFailure.Destroy();
9750 void TemplateSpecCandidateSet::clear() {
9751 destroyCandidates();
9755 /// NoteCandidates - When no template specialization match is found, prints
9756 /// diagnostic messages containing the non-matching specializations that form
9757 /// the candidate set.
9758 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9759 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9760 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9761 // Sort the candidates by position (assuming no candidate is a match).
9762 // Sorting directly would be prohibitive, so we make a set of pointers
9764 SmallVector<TemplateSpecCandidate *, 32> Cands;
9765 Cands.reserve(size());
9766 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9767 if (Cand->Specialization)
9768 Cands.push_back(Cand);
9769 // Otherwise, this is a non-matching builtin candidate. We do not,
9770 // in general, want to list every possible builtin candidate.
9773 std::sort(Cands.begin(), Cands.end(),
9774 CompareTemplateSpecCandidatesForDisplay(S));
9776 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9777 // for generalization purposes (?).
9778 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9780 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9781 unsigned CandsShown = 0;
9782 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9783 TemplateSpecCandidate *Cand = *I;
9785 // Set an arbitrary limit on the number of candidates we'll spam
9786 // the user with. FIXME: This limit should depend on details of the
9788 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9792 assert(Cand->Specialization &&
9793 "Non-matching built-in candidates are not added to Cands.");
9794 Cand->NoteDeductionFailure(S);
9798 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9801 // [PossiblyAFunctionType] --> [Return]
9802 // NonFunctionType --> NonFunctionType
9804 // R (*)(A) --> R (A)
9805 // R (&)(A) --> R (A)
9806 // R (S::*)(A) --> R (A)
9807 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9808 QualType Ret = PossiblyAFunctionType;
9809 if (const PointerType *ToTypePtr =
9810 PossiblyAFunctionType->getAs<PointerType>())
9811 Ret = ToTypePtr->getPointeeType();
9812 else if (const ReferenceType *ToTypeRef =
9813 PossiblyAFunctionType->getAs<ReferenceType>())
9814 Ret = ToTypeRef->getPointeeType();
9815 else if (const MemberPointerType *MemTypePtr =
9816 PossiblyAFunctionType->getAs<MemberPointerType>())
9817 Ret = MemTypePtr->getPointeeType();
9819 Context.getCanonicalType(Ret).getUnqualifiedType();
9824 // A helper class to help with address of function resolution
9825 // - allows us to avoid passing around all those ugly parameters
9826 class AddressOfFunctionResolver {
9829 const QualType& TargetType;
9830 QualType TargetFunctionType; // Extracted function type from target type
9833 //DeclAccessPair& ResultFunctionAccessPair;
9834 ASTContext& Context;
9836 bool TargetTypeIsNonStaticMemberFunction;
9837 bool FoundNonTemplateFunction;
9838 bool StaticMemberFunctionFromBoundPointer;
9840 OverloadExpr::FindResult OvlExprInfo;
9841 OverloadExpr *OvlExpr;
9842 TemplateArgumentListInfo OvlExplicitTemplateArgs;
9843 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9844 TemplateSpecCandidateSet FailedCandidates;
9847 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9848 const QualType &TargetType, bool Complain)
9849 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9850 Complain(Complain), Context(S.getASTContext()),
9851 TargetTypeIsNonStaticMemberFunction(
9852 !!TargetType->getAs<MemberPointerType>()),
9853 FoundNonTemplateFunction(false),
9854 StaticMemberFunctionFromBoundPointer(false),
9855 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9856 OvlExpr(OvlExprInfo.Expression),
9857 FailedCandidates(OvlExpr->getNameLoc()) {
9858 ExtractUnqualifiedFunctionTypeFromTargetType();
9860 if (TargetFunctionType->isFunctionType()) {
9861 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9862 if (!UME->isImplicitAccess() &&
9863 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9864 StaticMemberFunctionFromBoundPointer = true;
9865 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9867 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9868 OvlExpr, false, &dap)) {
9869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9870 if (!Method->isStatic()) {
9871 // If the target type is a non-function type and the function found
9872 // is a non-static member function, pretend as if that was the
9873 // target, it's the only possible type to end up with.
9874 TargetTypeIsNonStaticMemberFunction = true;
9876 // And skip adding the function if its not in the proper form.
9877 // We'll diagnose this due to an empty set of functions.
9878 if (!OvlExprInfo.HasFormOfMemberPointer)
9882 Matches.push_back(std::make_pair(dap, Fn));
9887 if (OvlExpr->hasExplicitTemplateArgs())
9888 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9890 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9891 // C++ [over.over]p4:
9892 // If more than one function is selected, [...]
9893 if (Matches.size() > 1) {
9894 if (FoundNonTemplateFunction)
9895 EliminateAllTemplateMatches();
9897 EliminateAllExceptMostSpecializedTemplate();
9903 bool isTargetTypeAFunction() const {
9904 return TargetFunctionType->isFunctionType();
9907 // [ToType] [Return]
9909 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9910 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9911 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9912 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9913 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9916 // return true if any matching specializations were found
9917 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9918 const DeclAccessPair& CurAccessFunPair) {
9919 if (CXXMethodDecl *Method
9920 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9921 // Skip non-static function templates when converting to pointer, and
9922 // static when converting to member pointer.
9923 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9926 else if (TargetTypeIsNonStaticMemberFunction)
9929 // C++ [over.over]p2:
9930 // If the name is a function template, template argument deduction is
9931 // done (14.8.2.2), and if the argument deduction succeeds, the
9932 // resulting template argument list is used to generate a single
9933 // function template specialization, which is added to the set of
9934 // overloaded functions considered.
9935 FunctionDecl *Specialization = nullptr;
9936 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9937 if (Sema::TemplateDeductionResult Result
9938 = S.DeduceTemplateArguments(FunctionTemplate,
9939 &OvlExplicitTemplateArgs,
9940 TargetFunctionType, Specialization,
9941 Info, /*InOverloadResolution=*/true)) {
9942 // Make a note of the failed deduction for diagnostics.
9943 FailedCandidates.addCandidate()
9944 .set(FunctionTemplate->getTemplatedDecl(),
9945 MakeDeductionFailureInfo(Context, Result, Info));
9949 // Template argument deduction ensures that we have an exact match or
9950 // compatible pointer-to-function arguments that would be adjusted by ICS.
9951 // This function template specicalization works.
9952 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9953 assert(S.isSameOrCompatibleFunctionType(
9954 Context.getCanonicalType(Specialization->getType()),
9955 Context.getCanonicalType(TargetFunctionType)));
9956 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9960 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9961 const DeclAccessPair& CurAccessFunPair) {
9962 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9963 // Skip non-static functions when converting to pointer, and static
9964 // when converting to member pointer.
9965 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9968 else if (TargetTypeIsNonStaticMemberFunction)
9971 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9972 if (S.getLangOpts().CUDA)
9973 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9974 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
9977 // If any candidate has a placeholder return type, trigger its deduction
9979 if (S.getLangOpts().CPlusPlus14 &&
9980 FunDecl->getReturnType()->isUndeducedType() &&
9981 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9985 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9986 FunDecl->getType()) ||
9987 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9989 Matches.push_back(std::make_pair(CurAccessFunPair,
9990 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9991 FoundNonTemplateFunction = true;
9999 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10002 // If the overload expression doesn't have the form of a pointer to
10003 // member, don't try to convert it to a pointer-to-member type.
10004 if (IsInvalidFormOfPointerToMemberFunction())
10007 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10008 E = OvlExpr->decls_end();
10010 // Look through any using declarations to find the underlying function.
10011 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10013 // C++ [over.over]p3:
10014 // Non-member functions and static member functions match
10015 // targets of type "pointer-to-function" or "reference-to-function."
10016 // Nonstatic member functions match targets of
10017 // type "pointer-to-member-function."
10018 // Note that according to DR 247, the containing class does not matter.
10019 if (FunctionTemplateDecl *FunctionTemplate
10020 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10021 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10024 // If we have explicit template arguments supplied, skip non-templates.
10025 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10026 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10029 assert(Ret || Matches.empty());
10033 void EliminateAllExceptMostSpecializedTemplate() {
10034 // [...] and any given function template specialization F1 is
10035 // eliminated if the set contains a second function template
10036 // specialization whose function template is more specialized
10037 // than the function template of F1 according to the partial
10038 // ordering rules of 14.5.5.2.
10040 // The algorithm specified above is quadratic. We instead use a
10041 // two-pass algorithm (similar to the one used to identify the
10042 // best viable function in an overload set) that identifies the
10043 // best function template (if it exists).
10045 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10046 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10047 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10049 // TODO: It looks like FailedCandidates does not serve much purpose
10050 // here, since the no_viable diagnostic has index 0.
10051 UnresolvedSetIterator Result = S.getMostSpecialized(
10052 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10053 SourceExpr->getLocStart(), S.PDiag(),
10054 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10055 .second->getDeclName(),
10056 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10057 Complain, TargetFunctionType);
10059 if (Result != MatchesCopy.end()) {
10060 // Make it the first and only element
10061 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10062 Matches[0].second = cast<FunctionDecl>(*Result);
10067 void EliminateAllTemplateMatches() {
10068 // [...] any function template specializations in the set are
10069 // eliminated if the set also contains a non-template function, [...]
10070 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10071 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10074 Matches[I] = Matches[--N];
10075 Matches.set_size(N);
10081 void ComplainNoMatchesFound() const {
10082 assert(Matches.empty());
10083 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10084 << OvlExpr->getName() << TargetFunctionType
10085 << OvlExpr->getSourceRange();
10086 if (FailedCandidates.empty())
10087 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10089 // We have some deduction failure messages. Use them to diagnose
10090 // the function templates, and diagnose the non-template candidates
10092 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10093 IEnd = OvlExpr->decls_end();
10095 if (FunctionDecl *Fun =
10096 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10097 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10098 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10102 bool IsInvalidFormOfPointerToMemberFunction() const {
10103 return TargetTypeIsNonStaticMemberFunction &&
10104 !OvlExprInfo.HasFormOfMemberPointer;
10107 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10108 // TODO: Should we condition this on whether any functions might
10109 // have matched, or is it more appropriate to do that in callers?
10110 // TODO: a fixit wouldn't hurt.
10111 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10112 << TargetType << OvlExpr->getSourceRange();
10115 bool IsStaticMemberFunctionFromBoundPointer() const {
10116 return StaticMemberFunctionFromBoundPointer;
10119 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10120 S.Diag(OvlExpr->getLocStart(),
10121 diag::err_invalid_form_pointer_member_function)
10122 << OvlExpr->getSourceRange();
10125 void ComplainOfInvalidConversion() const {
10126 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10127 << OvlExpr->getName() << TargetType;
10130 void ComplainMultipleMatchesFound() const {
10131 assert(Matches.size() > 1);
10132 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10133 << OvlExpr->getName()
10134 << OvlExpr->getSourceRange();
10135 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10138 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10140 int getNumMatches() const { return Matches.size(); }
10142 FunctionDecl* getMatchingFunctionDecl() const {
10143 if (Matches.size() != 1) return nullptr;
10144 return Matches[0].second;
10147 const DeclAccessPair* getMatchingFunctionAccessPair() const {
10148 if (Matches.size() != 1) return nullptr;
10149 return &Matches[0].first;
10154 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10155 /// an overloaded function (C++ [over.over]), where @p From is an
10156 /// expression with overloaded function type and @p ToType is the type
10157 /// we're trying to resolve to. For example:
10163 /// int (*pfd)(double) = f; // selects f(double)
10166 /// This routine returns the resulting FunctionDecl if it could be
10167 /// resolved, and NULL otherwise. When @p Complain is true, this
10168 /// routine will emit diagnostics if there is an error.
10170 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10171 QualType TargetType,
10173 DeclAccessPair &FoundResult,
10174 bool *pHadMultipleCandidates) {
10175 assert(AddressOfExpr->getType() == Context.OverloadTy);
10177 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10179 int NumMatches = Resolver.getNumMatches();
10180 FunctionDecl *Fn = nullptr;
10181 if (NumMatches == 0 && Complain) {
10182 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10183 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10185 Resolver.ComplainNoMatchesFound();
10187 else if (NumMatches > 1 && Complain)
10188 Resolver.ComplainMultipleMatchesFound();
10189 else if (NumMatches == 1) {
10190 Fn = Resolver.getMatchingFunctionDecl();
10192 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10194 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10195 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10197 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10201 if (pHadMultipleCandidates)
10202 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10206 /// \brief Given an expression that refers to an overloaded function, try to
10207 /// resolve that overloaded function expression down to a single function.
10209 /// This routine can only resolve template-ids that refer to a single function
10210 /// template, where that template-id refers to a single template whose template
10211 /// arguments are either provided by the template-id or have defaults,
10212 /// as described in C++0x [temp.arg.explicit]p3.
10214 /// If no template-ids are found, no diagnostics are emitted and NULL is
10217 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10219 DeclAccessPair *FoundResult) {
10220 // C++ [over.over]p1:
10221 // [...] [Note: any redundant set of parentheses surrounding the
10222 // overloaded function name is ignored (5.1). ]
10223 // C++ [over.over]p1:
10224 // [...] The overloaded function name can be preceded by the &
10227 // If we didn't actually find any template-ids, we're done.
10228 if (!ovl->hasExplicitTemplateArgs())
10231 TemplateArgumentListInfo ExplicitTemplateArgs;
10232 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10233 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10235 // Look through all of the overloaded functions, searching for one
10236 // whose type matches exactly.
10237 FunctionDecl *Matched = nullptr;
10238 for (UnresolvedSetIterator I = ovl->decls_begin(),
10239 E = ovl->decls_end(); I != E; ++I) {
10240 // C++0x [temp.arg.explicit]p3:
10241 // [...] In contexts where deduction is done and fails, or in contexts
10242 // where deduction is not done, if a template argument list is
10243 // specified and it, along with any default template arguments,
10244 // identifies a single function template specialization, then the
10245 // template-id is an lvalue for the function template specialization.
10246 FunctionTemplateDecl *FunctionTemplate
10247 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10249 // C++ [over.over]p2:
10250 // If the name is a function template, template argument deduction is
10251 // done (14.8.2.2), and if the argument deduction succeeds, the
10252 // resulting template argument list is used to generate a single
10253 // function template specialization, which is added to the set of
10254 // overloaded functions considered.
10255 FunctionDecl *Specialization = nullptr;
10256 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10257 if (TemplateDeductionResult Result
10258 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10259 Specialization, Info,
10260 /*InOverloadResolution=*/true)) {
10261 // Make a note of the failed deduction for diagnostics.
10262 // TODO: Actually use the failed-deduction info?
10263 FailedCandidates.addCandidate()
10264 .set(FunctionTemplate->getTemplatedDecl(),
10265 MakeDeductionFailureInfo(Context, Result, Info));
10269 assert(Specialization && "no specialization and no error?");
10271 // Multiple matches; we can't resolve to a single declaration.
10274 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10276 NoteAllOverloadCandidates(ovl);
10281 Matched = Specialization;
10282 if (FoundResult) *FoundResult = I.getPair();
10285 if (Matched && getLangOpts().CPlusPlus14 &&
10286 Matched->getReturnType()->isUndeducedType() &&
10287 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10296 // Resolve and fix an overloaded expression that can be resolved
10297 // because it identifies a single function template specialization.
10299 // Last three arguments should only be supplied if Complain = true
10301 // Return true if it was logically possible to so resolve the
10302 // expression, regardless of whether or not it succeeded. Always
10303 // returns true if 'complain' is set.
10304 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10305 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10306 bool complain, const SourceRange& OpRangeForComplaining,
10307 QualType DestTypeForComplaining,
10308 unsigned DiagIDForComplaining) {
10309 assert(SrcExpr.get()->getType() == Context.OverloadTy);
10311 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10313 DeclAccessPair found;
10314 ExprResult SingleFunctionExpression;
10315 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10316 ovl.Expression, /*complain*/ false, &found)) {
10317 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10318 SrcExpr = ExprError();
10322 // It is only correct to resolve to an instance method if we're
10323 // resolving a form that's permitted to be a pointer to member.
10324 // Otherwise we'll end up making a bound member expression, which
10325 // is illegal in all the contexts we resolve like this.
10326 if (!ovl.HasFormOfMemberPointer &&
10327 isa<CXXMethodDecl>(fn) &&
10328 cast<CXXMethodDecl>(fn)->isInstance()) {
10329 if (!complain) return false;
10331 Diag(ovl.Expression->getExprLoc(),
10332 diag::err_bound_member_function)
10333 << 0 << ovl.Expression->getSourceRange();
10335 // TODO: I believe we only end up here if there's a mix of
10336 // static and non-static candidates (otherwise the expression
10337 // would have 'bound member' type, not 'overload' type).
10338 // Ideally we would note which candidate was chosen and why
10339 // the static candidates were rejected.
10340 SrcExpr = ExprError();
10344 // Fix the expression to refer to 'fn'.
10345 SingleFunctionExpression =
10346 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10348 // If desired, do function-to-pointer decay.
10349 if (doFunctionPointerConverion) {
10350 SingleFunctionExpression =
10351 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10352 if (SingleFunctionExpression.isInvalid()) {
10353 SrcExpr = ExprError();
10359 if (!SingleFunctionExpression.isUsable()) {
10361 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10362 << ovl.Expression->getName()
10363 << DestTypeForComplaining
10364 << OpRangeForComplaining
10365 << ovl.Expression->getQualifierLoc().getSourceRange();
10366 NoteAllOverloadCandidates(SrcExpr.get());
10368 SrcExpr = ExprError();
10375 SrcExpr = SingleFunctionExpression;
10379 /// \brief Add a single candidate to the overload set.
10380 static void AddOverloadedCallCandidate(Sema &S,
10381 DeclAccessPair FoundDecl,
10382 TemplateArgumentListInfo *ExplicitTemplateArgs,
10383 ArrayRef<Expr *> Args,
10384 OverloadCandidateSet &CandidateSet,
10385 bool PartialOverloading,
10387 NamedDecl *Callee = FoundDecl.getDecl();
10388 if (isa<UsingShadowDecl>(Callee))
10389 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10391 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10392 if (ExplicitTemplateArgs) {
10393 assert(!KnownValid && "Explicit template arguments?");
10396 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10397 /*SuppressUsedConversions=*/false,
10398 PartialOverloading);
10402 if (FunctionTemplateDecl *FuncTemplate
10403 = dyn_cast<FunctionTemplateDecl>(Callee)) {
10404 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10405 ExplicitTemplateArgs, Args, CandidateSet,
10406 /*SuppressUsedConversions=*/false,
10407 PartialOverloading);
10411 assert(!KnownValid && "unhandled case in overloaded call candidate");
10414 /// \brief Add the overload candidates named by callee and/or found by argument
10415 /// dependent lookup to the given overload set.
10416 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10417 ArrayRef<Expr *> Args,
10418 OverloadCandidateSet &CandidateSet,
10419 bool PartialOverloading) {
10422 // Verify that ArgumentDependentLookup is consistent with the rules
10423 // in C++0x [basic.lookup.argdep]p3:
10425 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10426 // and let Y be the lookup set produced by argument dependent
10427 // lookup (defined as follows). If X contains
10429 // -- a declaration of a class member, or
10431 // -- a block-scope function declaration that is not a
10432 // using-declaration, or
10434 // -- a declaration that is neither a function or a function
10437 // then Y is empty.
10439 if (ULE->requiresADL()) {
10440 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10441 E = ULE->decls_end(); I != E; ++I) {
10442 assert(!(*I)->getDeclContext()->isRecord());
10443 assert(isa<UsingShadowDecl>(*I) ||
10444 !(*I)->getDeclContext()->isFunctionOrMethod());
10445 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10450 // It would be nice to avoid this copy.
10451 TemplateArgumentListInfo TABuffer;
10452 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10453 if (ULE->hasExplicitTemplateArgs()) {
10454 ULE->copyTemplateArgumentsInto(TABuffer);
10455 ExplicitTemplateArgs = &TABuffer;
10458 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10459 E = ULE->decls_end(); I != E; ++I)
10460 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10461 CandidateSet, PartialOverloading,
10462 /*KnownValid*/ true);
10464 if (ULE->requiresADL())
10465 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10466 Args, ExplicitTemplateArgs,
10467 CandidateSet, PartialOverloading);
10470 /// Determine whether a declaration with the specified name could be moved into
10471 /// a different namespace.
10472 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10473 switch (Name.getCXXOverloadedOperator()) {
10474 case OO_New: case OO_Array_New:
10475 case OO_Delete: case OO_Array_Delete:
10483 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10484 /// template, where the non-dependent name was declared after the template
10485 /// was defined. This is common in code written for a compilers which do not
10486 /// correctly implement two-stage name lookup.
10488 /// Returns true if a viable candidate was found and a diagnostic was issued.
10490 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10491 const CXXScopeSpec &SS, LookupResult &R,
10492 OverloadCandidateSet::CandidateSetKind CSK,
10493 TemplateArgumentListInfo *ExplicitTemplateArgs,
10494 ArrayRef<Expr *> Args,
10495 bool *DoDiagnoseEmptyLookup = nullptr) {
10496 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10499 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10500 if (DC->isTransparentContext())
10503 SemaRef.LookupQualifiedName(R, DC);
10506 R.suppressDiagnostics();
10508 if (isa<CXXRecordDecl>(DC)) {
10509 // Don't diagnose names we find in classes; we get much better
10510 // diagnostics for these from DiagnoseEmptyLookup.
10512 if (DoDiagnoseEmptyLookup)
10513 *DoDiagnoseEmptyLookup = true;
10517 OverloadCandidateSet Candidates(FnLoc, CSK);
10518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10519 AddOverloadedCallCandidate(SemaRef, I.getPair(),
10520 ExplicitTemplateArgs, Args,
10521 Candidates, false, /*KnownValid*/ false);
10523 OverloadCandidateSet::iterator Best;
10524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10525 // No viable functions. Don't bother the user with notes for functions
10526 // which don't work and shouldn't be found anyway.
10531 // Find the namespaces where ADL would have looked, and suggest
10532 // declaring the function there instead.
10533 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10534 Sema::AssociatedClassSet AssociatedClasses;
10535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10536 AssociatedNamespaces,
10537 AssociatedClasses);
10538 Sema::AssociatedNamespaceSet SuggestedNamespaces;
10539 if (canBeDeclaredInNamespace(R.getLookupName())) {
10540 DeclContext *Std = SemaRef.getStdNamespace();
10541 for (Sema::AssociatedNamespaceSet::iterator
10542 it = AssociatedNamespaces.begin(),
10543 end = AssociatedNamespaces.end(); it != end; ++it) {
10544 // Never suggest declaring a function within namespace 'std'.
10545 if (Std && Std->Encloses(*it))
10548 // Never suggest declaring a function within a namespace with a
10549 // reserved name, like __gnu_cxx.
10550 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10552 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10555 SuggestedNamespaces.insert(*it);
10559 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10560 << R.getLookupName();
10561 if (SuggestedNamespaces.empty()) {
10562 SemaRef.Diag(Best->Function->getLocation(),
10563 diag::note_not_found_by_two_phase_lookup)
10564 << R.getLookupName() << 0;
10565 } else if (SuggestedNamespaces.size() == 1) {
10566 SemaRef.Diag(Best->Function->getLocation(),
10567 diag::note_not_found_by_two_phase_lookup)
10568 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10570 // FIXME: It would be useful to list the associated namespaces here,
10571 // but the diagnostics infrastructure doesn't provide a way to produce
10572 // a localized representation of a list of items.
10573 SemaRef.Diag(Best->Function->getLocation(),
10574 diag::note_not_found_by_two_phase_lookup)
10575 << R.getLookupName() << 2;
10578 // Try to recover by calling this function.
10588 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10589 /// template, where the non-dependent operator was declared after the template
10592 /// Returns true if a viable candidate was found and a diagnostic was issued.
10594 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10595 SourceLocation OpLoc,
10596 ArrayRef<Expr *> Args) {
10597 DeclarationName OpName =
10598 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10599 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10600 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10601 OverloadCandidateSet::CSK_Operator,
10602 /*ExplicitTemplateArgs=*/nullptr, Args);
10606 class BuildRecoveryCallExprRAII {
10609 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10610 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10611 SemaRef.IsBuildingRecoveryCallExpr = true;
10614 ~BuildRecoveryCallExprRAII() {
10615 SemaRef.IsBuildingRecoveryCallExpr = false;
10621 static std::unique_ptr<CorrectionCandidateCallback>
10622 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10623 bool HasTemplateArgs, bool AllowTypoCorrection) {
10624 if (!AllowTypoCorrection)
10625 return llvm::make_unique<NoTypoCorrectionCCC>();
10626 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10627 HasTemplateArgs, ME);
10630 /// Attempts to recover from a call where no functions were found.
10632 /// Returns true if new candidates were found.
10634 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10635 UnresolvedLookupExpr *ULE,
10636 SourceLocation LParenLoc,
10637 MutableArrayRef<Expr *> Args,
10638 SourceLocation RParenLoc,
10639 bool EmptyLookup, bool AllowTypoCorrection) {
10640 // Do not try to recover if it is already building a recovery call.
10641 // This stops infinite loops for template instantiations like
10643 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10644 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10646 if (SemaRef.IsBuildingRecoveryCallExpr)
10647 return ExprError();
10648 BuildRecoveryCallExprRAII RCE(SemaRef);
10651 SS.Adopt(ULE->getQualifierLoc());
10652 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10654 TemplateArgumentListInfo TABuffer;
10655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10656 if (ULE->hasExplicitTemplateArgs()) {
10657 ULE->copyTemplateArgumentsInto(TABuffer);
10658 ExplicitTemplateArgs = &TABuffer;
10661 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10662 Sema::LookupOrdinaryName);
10663 bool DoDiagnoseEmptyLookup = EmptyLookup;
10664 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10665 OverloadCandidateSet::CSK_Normal,
10666 ExplicitTemplateArgs, Args,
10667 &DoDiagnoseEmptyLookup) &&
10668 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10670 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10671 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10672 ExplicitTemplateArgs, Args)))
10673 return ExprError();
10675 assert(!R.empty() && "lookup results empty despite recovery");
10677 // Build an implicit member call if appropriate. Just drop the
10678 // casts and such from the call, we don't really care.
10679 ExprResult NewFn = ExprError();
10680 if ((*R.begin())->isCXXClassMember())
10681 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10682 R, ExplicitTemplateArgs);
10683 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10684 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10685 ExplicitTemplateArgs);
10687 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10689 if (NewFn.isInvalid())
10690 return ExprError();
10692 // This shouldn't cause an infinite loop because we're giving it
10693 // an expression with viable lookup results, which should never
10695 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10696 MultiExprArg(Args.data(), Args.size()),
10700 /// \brief Constructs and populates an OverloadedCandidateSet from
10701 /// the given function.
10702 /// \returns true when an the ExprResult output parameter has been set.
10703 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10704 UnresolvedLookupExpr *ULE,
10706 SourceLocation RParenLoc,
10707 OverloadCandidateSet *CandidateSet,
10708 ExprResult *Result) {
10710 if (ULE->requiresADL()) {
10711 // To do ADL, we must have found an unqualified name.
10712 assert(!ULE->getQualifier() && "qualified name with ADL");
10714 // We don't perform ADL for implicit declarations of builtins.
10715 // Verify that this was correctly set up.
10717 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10718 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10719 F->getBuiltinID() && F->isImplicit())
10720 llvm_unreachable("performing ADL for builtin");
10722 // We don't perform ADL in C.
10723 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10727 UnbridgedCastsSet UnbridgedCasts;
10728 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10729 *Result = ExprError();
10733 // Add the functions denoted by the callee to the set of candidate
10734 // functions, including those from argument-dependent lookup.
10735 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10737 if (getLangOpts().MSVCCompat &&
10738 CurContext->isDependentContext() && !isSFINAEContext() &&
10739 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10741 OverloadCandidateSet::iterator Best;
10742 if (CandidateSet->empty() ||
10743 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10744 OR_No_Viable_Function) {
10745 // In Microsoft mode, if we are inside a template class member function then
10746 // create a type dependent CallExpr. The goal is to postpone name lookup
10747 // to instantiation time to be able to search into type dependent base
10749 CallExpr *CE = new (Context) CallExpr(
10750 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
10751 CE->setTypeDependent(true);
10757 if (CandidateSet->empty())
10760 UnbridgedCasts.restore();
10764 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10765 /// the completed call expression. If overload resolution fails, emits
10766 /// diagnostics and returns ExprError()
10767 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10768 UnresolvedLookupExpr *ULE,
10769 SourceLocation LParenLoc,
10771 SourceLocation RParenLoc,
10773 OverloadCandidateSet *CandidateSet,
10774 OverloadCandidateSet::iterator *Best,
10775 OverloadingResult OverloadResult,
10776 bool AllowTypoCorrection) {
10777 if (CandidateSet->empty())
10778 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10779 RParenLoc, /*EmptyLookup=*/true,
10780 AllowTypoCorrection);
10782 switch (OverloadResult) {
10784 FunctionDecl *FDecl = (*Best)->Function;
10785 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10786 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10787 return ExprError();
10788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10793 case OR_No_Viable_Function: {
10794 // Try to recover by looking for viable functions which the user might
10795 // have meant to call.
10796 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10798 /*EmptyLookup=*/false,
10799 AllowTypoCorrection);
10800 if (!Recovery.isInvalid())
10803 SemaRef.Diag(Fn->getLocStart(),
10804 diag::err_ovl_no_viable_function_in_call)
10805 << ULE->getName() << Fn->getSourceRange();
10806 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10811 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10812 << ULE->getName() << Fn->getSourceRange();
10813 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10817 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10818 << (*Best)->Function->isDeleted()
10820 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10821 << Fn->getSourceRange();
10822 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10824 // We emitted an error for the unvailable/deleted function call but keep
10825 // the call in the AST.
10826 FunctionDecl *FDecl = (*Best)->Function;
10827 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10828 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10833 // Overload resolution failed.
10834 return ExprError();
10837 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10838 /// (which eventually refers to the declaration Func) and the call
10839 /// arguments Args/NumArgs, attempt to resolve the function call down
10840 /// to a specific function. If overload resolution succeeds, returns
10841 /// the call expression produced by overload resolution.
10842 /// Otherwise, emits diagnostics and returns ExprError.
10843 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10844 UnresolvedLookupExpr *ULE,
10845 SourceLocation LParenLoc,
10847 SourceLocation RParenLoc,
10849 bool AllowTypoCorrection) {
10850 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10851 OverloadCandidateSet::CSK_Normal);
10854 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10858 OverloadCandidateSet::iterator Best;
10859 OverloadingResult OverloadResult =
10860 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10862 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10863 RParenLoc, ExecConfig, &CandidateSet,
10864 &Best, OverloadResult,
10865 AllowTypoCorrection);
10868 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10869 return Functions.size() > 1 ||
10870 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10873 /// \brief Create a unary operation that may resolve to an overloaded
10876 /// \param OpLoc The location of the operator itself (e.g., '*').
10878 /// \param OpcIn The UnaryOperator::Opcode that describes this
10881 /// \param Fns The set of non-member functions that will be
10882 /// considered by overload resolution. The caller needs to build this
10883 /// set based on the context using, e.g.,
10884 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10885 /// set should not contain any member functions; those will be added
10886 /// by CreateOverloadedUnaryOp().
10888 /// \param Input The input argument.
10890 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10891 const UnresolvedSetImpl &Fns,
10893 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10895 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10896 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10897 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10898 // TODO: provide better source location info.
10899 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10901 if (checkPlaceholderForOverload(*this, Input))
10902 return ExprError();
10904 Expr *Args[2] = { Input, nullptr };
10905 unsigned NumArgs = 1;
10907 // For post-increment and post-decrement, add the implicit '0' as
10908 // the second argument, so that we know this is a post-increment or
10910 if (Opc == UO_PostInc || Opc == UO_PostDec) {
10911 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10912 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10917 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10919 if (Input->isTypeDependent()) {
10921 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10922 VK_RValue, OK_Ordinary, OpLoc);
10924 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10925 UnresolvedLookupExpr *Fn
10926 = UnresolvedLookupExpr::Create(Context, NamingClass,
10927 NestedNameSpecifierLoc(), OpNameInfo,
10928 /*ADL*/ true, IsOverloaded(Fns),
10929 Fns.begin(), Fns.end());
10930 return new (Context)
10931 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10932 VK_RValue, OpLoc, false);
10935 // Build an empty overload set.
10936 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10938 // Add the candidates from the given function set.
10939 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
10941 // Add operator candidates that are member functions.
10942 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10944 // Add candidates from ADL.
10945 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10946 /*ExplicitTemplateArgs*/nullptr,
10949 // Add builtin operator candidates.
10950 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10952 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10954 // Perform overload resolution.
10955 OverloadCandidateSet::iterator Best;
10956 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10958 // We found a built-in operator or an overloaded operator.
10959 FunctionDecl *FnDecl = Best->Function;
10962 // We matched an overloaded operator. Build a call to that
10965 // Convert the arguments.
10966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10967 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10969 ExprResult InputRes =
10970 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10971 Best->FoundDecl, Method);
10972 if (InputRes.isInvalid())
10973 return ExprError();
10974 Input = InputRes.get();
10976 // Convert the arguments.
10977 ExprResult InputInit
10978 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10980 FnDecl->getParamDecl(0)),
10983 if (InputInit.isInvalid())
10984 return ExprError();
10985 Input = InputInit.get();
10988 // Build the actual expression node.
10989 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10990 HadMultipleCandidates, OpLoc);
10991 if (FnExpr.isInvalid())
10992 return ExprError();
10994 // Determine the result type.
10995 QualType ResultTy = FnDecl->getReturnType();
10996 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10997 ResultTy = ResultTy.getNonLValueExprType(Context);
11000 CallExpr *TheCall =
11001 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11002 ResultTy, VK, OpLoc, false);
11004 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11005 return ExprError();
11007 return MaybeBindToTemporary(TheCall);
11009 // We matched a built-in operator. Convert the arguments, then
11010 // break out so that we will build the appropriate built-in
11012 ExprResult InputRes =
11013 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11014 Best->Conversions[0], AA_Passing);
11015 if (InputRes.isInvalid())
11016 return ExprError();
11017 Input = InputRes.get();
11022 case OR_No_Viable_Function:
11023 // This is an erroneous use of an operator which can be overloaded by
11024 // a non-member function. Check for non-member operators which were
11025 // defined too late to be candidates.
11026 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11027 // FIXME: Recover by calling the found function.
11028 return ExprError();
11030 // No viable function; fall through to handling this as a
11031 // built-in operator, which will produce an error message for us.
11035 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11036 << UnaryOperator::getOpcodeStr(Opc)
11037 << Input->getType()
11038 << Input->getSourceRange();
11039 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11040 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11041 return ExprError();
11044 Diag(OpLoc, diag::err_ovl_deleted_oper)
11045 << Best->Function->isDeleted()
11046 << UnaryOperator::getOpcodeStr(Opc)
11047 << getDeletedOrUnavailableSuffix(Best->Function)
11048 << Input->getSourceRange();
11049 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11050 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11051 return ExprError();
11054 // Either we found no viable overloaded operator or we matched a
11055 // built-in operator. In either case, fall through to trying to
11056 // build a built-in operation.
11057 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11060 /// \brief Create a binary operation that may resolve to an overloaded
11063 /// \param OpLoc The location of the operator itself (e.g., '+').
11065 /// \param OpcIn The BinaryOperator::Opcode that describes this
11068 /// \param Fns The set of non-member functions that will be
11069 /// considered by overload resolution. The caller needs to build this
11070 /// set based on the context using, e.g.,
11071 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11072 /// set should not contain any member functions; those will be added
11073 /// by CreateOverloadedBinOp().
11075 /// \param LHS Left-hand argument.
11076 /// \param RHS Right-hand argument.
11078 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11080 const UnresolvedSetImpl &Fns,
11081 Expr *LHS, Expr *RHS) {
11082 Expr *Args[2] = { LHS, RHS };
11083 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11085 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11086 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11087 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11089 // If either side is type-dependent, create an appropriate dependent
11091 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11093 // If there are no functions to store, just build a dependent
11094 // BinaryOperator or CompoundAssignment.
11095 if (Opc <= BO_Assign || Opc > BO_OrAssign)
11096 return new (Context) BinaryOperator(
11097 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11098 OpLoc, FPFeatures.fp_contract);
11100 return new (Context) CompoundAssignOperator(
11101 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11102 Context.DependentTy, Context.DependentTy, OpLoc,
11103 FPFeatures.fp_contract);
11106 // FIXME: save results of ADL from here?
11107 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11108 // TODO: provide better source location info in DNLoc component.
11109 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11110 UnresolvedLookupExpr *Fn
11111 = UnresolvedLookupExpr::Create(Context, NamingClass,
11112 NestedNameSpecifierLoc(), OpNameInfo,
11113 /*ADL*/ true, IsOverloaded(Fns),
11114 Fns.begin(), Fns.end());
11115 return new (Context)
11116 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11117 VK_RValue, OpLoc, FPFeatures.fp_contract);
11120 // Always do placeholder-like conversions on the RHS.
11121 if (checkPlaceholderForOverload(*this, Args[1]))
11122 return ExprError();
11124 // Do placeholder-like conversion on the LHS; note that we should
11125 // not get here with a PseudoObject LHS.
11126 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11127 if (checkPlaceholderForOverload(*this, Args[0]))
11128 return ExprError();
11130 // If this is the assignment operator, we only perform overload resolution
11131 // if the left-hand side is a class or enumeration type. This is actually
11132 // a hack. The standard requires that we do overload resolution between the
11133 // various built-in candidates, but as DR507 points out, this can lead to
11134 // problems. So we do it this way, which pretty much follows what GCC does.
11135 // Note that we go the traditional code path for compound assignment forms.
11136 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11137 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11139 // If this is the .* operator, which is not overloadable, just
11140 // create a built-in binary operator.
11141 if (Opc == BO_PtrMemD)
11142 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11144 // Build an empty overload set.
11145 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11147 // Add the candidates from the given function set.
11148 AddFunctionCandidates(Fns, Args, CandidateSet);
11150 // Add operator candidates that are member functions.
11151 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11153 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11154 // performed for an assignment operator (nor for operator[] nor operator->,
11155 // which don't get here).
11156 if (Opc != BO_Assign)
11157 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11158 /*ExplicitTemplateArgs*/ nullptr,
11161 // Add builtin operator candidates.
11162 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11164 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11166 // Perform overload resolution.
11167 OverloadCandidateSet::iterator Best;
11168 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11170 // We found a built-in operator or an overloaded operator.
11171 FunctionDecl *FnDecl = Best->Function;
11174 // We matched an overloaded operator. Build a call to that
11177 // Convert the arguments.
11178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11179 // Best->Access is only meaningful for class members.
11180 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11183 PerformCopyInitialization(
11184 InitializedEntity::InitializeParameter(Context,
11185 FnDecl->getParamDecl(0)),
11186 SourceLocation(), Args[1]);
11187 if (Arg1.isInvalid())
11188 return ExprError();
11191 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11192 Best->FoundDecl, Method);
11193 if (Arg0.isInvalid())
11194 return ExprError();
11195 Args[0] = Arg0.getAs<Expr>();
11196 Args[1] = RHS = Arg1.getAs<Expr>();
11198 // Convert the arguments.
11199 ExprResult Arg0 = PerformCopyInitialization(
11200 InitializedEntity::InitializeParameter(Context,
11201 FnDecl->getParamDecl(0)),
11202 SourceLocation(), Args[0]);
11203 if (Arg0.isInvalid())
11204 return ExprError();
11207 PerformCopyInitialization(
11208 InitializedEntity::InitializeParameter(Context,
11209 FnDecl->getParamDecl(1)),
11210 SourceLocation(), Args[1]);
11211 if (Arg1.isInvalid())
11212 return ExprError();
11213 Args[0] = LHS = Arg0.getAs<Expr>();
11214 Args[1] = RHS = Arg1.getAs<Expr>();
11217 // Build the actual expression node.
11218 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11220 HadMultipleCandidates, OpLoc);
11221 if (FnExpr.isInvalid())
11222 return ExprError();
11224 // Determine the result type.
11225 QualType ResultTy = FnDecl->getReturnType();
11226 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11227 ResultTy = ResultTy.getNonLValueExprType(Context);
11229 CXXOperatorCallExpr *TheCall =
11230 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11231 Args, ResultTy, VK, OpLoc,
11232 FPFeatures.fp_contract);
11234 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11236 return ExprError();
11238 ArrayRef<const Expr *> ArgsArray(Args, 2);
11239 // Cut off the implicit 'this'.
11240 if (isa<CXXMethodDecl>(FnDecl))
11241 ArgsArray = ArgsArray.slice(1);
11243 // Check for a self move.
11244 if (Op == OO_Equal)
11245 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11247 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11248 TheCall->getSourceRange(), VariadicDoesNotApply);
11250 return MaybeBindToTemporary(TheCall);
11252 // We matched a built-in operator. Convert the arguments, then
11253 // break out so that we will build the appropriate built-in
11255 ExprResult ArgsRes0 =
11256 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11257 Best->Conversions[0], AA_Passing);
11258 if (ArgsRes0.isInvalid())
11259 return ExprError();
11260 Args[0] = ArgsRes0.get();
11262 ExprResult ArgsRes1 =
11263 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11264 Best->Conversions[1], AA_Passing);
11265 if (ArgsRes1.isInvalid())
11266 return ExprError();
11267 Args[1] = ArgsRes1.get();
11272 case OR_No_Viable_Function: {
11273 // C++ [over.match.oper]p9:
11274 // If the operator is the operator , [...] and there are no
11275 // viable functions, then the operator is assumed to be the
11276 // built-in operator and interpreted according to clause 5.
11277 if (Opc == BO_Comma)
11280 // For class as left operand for assignment or compound assigment
11281 // operator do not fall through to handling in built-in, but report that
11282 // no overloaded assignment operator found
11283 ExprResult Result = ExprError();
11284 if (Args[0]->getType()->isRecordType() &&
11285 Opc >= BO_Assign && Opc <= BO_OrAssign) {
11286 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11287 << BinaryOperator::getOpcodeStr(Opc)
11288 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11289 if (Args[0]->getType()->isIncompleteType()) {
11290 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11291 << Args[0]->getType()
11292 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11295 // This is an erroneous use of an operator which can be overloaded by
11296 // a non-member function. Check for non-member operators which were
11297 // defined too late to be candidates.
11298 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11299 // FIXME: Recover by calling the found function.
11300 return ExprError();
11302 // No viable function; try to create a built-in operation, which will
11303 // produce an error. Then, show the non-viable candidates.
11304 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11306 assert(Result.isInvalid() &&
11307 "C++ binary operator overloading is missing candidates!");
11308 if (Result.isInvalid())
11309 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11310 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11315 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
11316 << BinaryOperator::getOpcodeStr(Opc)
11317 << Args[0]->getType() << Args[1]->getType()
11318 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11319 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11320 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11321 return ExprError();
11324 if (isImplicitlyDeleted(Best->Function)) {
11325 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11326 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11327 << Context.getRecordType(Method->getParent())
11328 << getSpecialMember(Method);
11330 // The user probably meant to call this special member. Just
11331 // explain why it's deleted.
11332 NoteDeletedFunction(Method);
11333 return ExprError();
11335 Diag(OpLoc, diag::err_ovl_deleted_oper)
11336 << Best->Function->isDeleted()
11337 << BinaryOperator::getOpcodeStr(Opc)
11338 << getDeletedOrUnavailableSuffix(Best->Function)
11339 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11342 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11343 return ExprError();
11346 // We matched a built-in operator; build it.
11347 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11351 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11352 SourceLocation RLoc,
11353 Expr *Base, Expr *Idx) {
11354 Expr *Args[2] = { Base, Idx };
11355 DeclarationName OpName =
11356 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11358 // If either side is type-dependent, create an appropriate dependent
11360 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11362 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11363 // CHECKME: no 'operator' keyword?
11364 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11365 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11366 UnresolvedLookupExpr *Fn
11367 = UnresolvedLookupExpr::Create(Context, NamingClass,
11368 NestedNameSpecifierLoc(), OpNameInfo,
11369 /*ADL*/ true, /*Overloaded*/ false,
11370 UnresolvedSetIterator(),
11371 UnresolvedSetIterator());
11372 // Can't add any actual overloads yet
11374 return new (Context)
11375 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11376 Context.DependentTy, VK_RValue, RLoc, false);
11379 // Handle placeholders on both operands.
11380 if (checkPlaceholderForOverload(*this, Args[0]))
11381 return ExprError();
11382 if (checkPlaceholderForOverload(*this, Args[1]))
11383 return ExprError();
11385 // Build an empty overload set.
11386 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11388 // Subscript can only be overloaded as a member function.
11390 // Add operator candidates that are member functions.
11391 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11393 // Add builtin operator candidates.
11394 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11396 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11398 // Perform overload resolution.
11399 OverloadCandidateSet::iterator Best;
11400 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11402 // We found a built-in operator or an overloaded operator.
11403 FunctionDecl *FnDecl = Best->Function;
11406 // We matched an overloaded operator. Build a call to that
11409 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11411 // Convert the arguments.
11412 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11414 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11415 Best->FoundDecl, Method);
11416 if (Arg0.isInvalid())
11417 return ExprError();
11418 Args[0] = Arg0.get();
11420 // Convert the arguments.
11421 ExprResult InputInit
11422 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11424 FnDecl->getParamDecl(0)),
11427 if (InputInit.isInvalid())
11428 return ExprError();
11430 Args[1] = InputInit.getAs<Expr>();
11432 // Build the actual expression node.
11433 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11434 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11435 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11437 HadMultipleCandidates,
11438 OpLocInfo.getLoc(),
11439 OpLocInfo.getInfo());
11440 if (FnExpr.isInvalid())
11441 return ExprError();
11443 // Determine the result type
11444 QualType ResultTy = FnDecl->getReturnType();
11445 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11446 ResultTy = ResultTy.getNonLValueExprType(Context);
11448 CXXOperatorCallExpr *TheCall =
11449 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11450 FnExpr.get(), Args,
11451 ResultTy, VK, RLoc,
11454 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11455 return ExprError();
11457 return MaybeBindToTemporary(TheCall);
11459 // We matched a built-in operator. Convert the arguments, then
11460 // break out so that we will build the appropriate built-in
11462 ExprResult ArgsRes0 =
11463 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11464 Best->Conversions[0], AA_Passing);
11465 if (ArgsRes0.isInvalid())
11466 return ExprError();
11467 Args[0] = ArgsRes0.get();
11469 ExprResult ArgsRes1 =
11470 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11471 Best->Conversions[1], AA_Passing);
11472 if (ArgsRes1.isInvalid())
11473 return ExprError();
11474 Args[1] = ArgsRes1.get();
11480 case OR_No_Viable_Function: {
11481 if (CandidateSet.empty())
11482 Diag(LLoc, diag::err_ovl_no_oper)
11483 << Args[0]->getType() << /*subscript*/ 0
11484 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11486 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11487 << Args[0]->getType()
11488 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11489 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11491 return ExprError();
11495 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
11497 << Args[0]->getType() << Args[1]->getType()
11498 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11499 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11501 return ExprError();
11504 Diag(LLoc, diag::err_ovl_deleted_oper)
11505 << Best->Function->isDeleted() << "[]"
11506 << getDeletedOrUnavailableSuffix(Best->Function)
11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11508 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11510 return ExprError();
11513 // We matched a built-in operator; build it.
11514 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11517 /// BuildCallToMemberFunction - Build a call to a member
11518 /// function. MemExpr is the expression that refers to the member
11519 /// function (and includes the object parameter), Args/NumArgs are the
11520 /// arguments to the function call (not including the object
11521 /// parameter). The caller needs to validate that the member
11522 /// expression refers to a non-static member function or an overloaded
11523 /// member function.
11525 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11526 SourceLocation LParenLoc,
11528 SourceLocation RParenLoc) {
11529 assert(MemExprE->getType() == Context.BoundMemberTy ||
11530 MemExprE->getType() == Context.OverloadTy);
11532 // Dig out the member expression. This holds both the object
11533 // argument and the member function we're referring to.
11534 Expr *NakedMemExpr = MemExprE->IgnoreParens();
11536 // Determine whether this is a call to a pointer-to-member function.
11537 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11538 assert(op->getType() == Context.BoundMemberTy);
11539 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11542 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11544 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11545 QualType resultType = proto->getCallResultType(Context);
11546 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11548 // Check that the object type isn't more qualified than the
11549 // member function we're calling.
11550 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11552 QualType objectType = op->getLHS()->getType();
11553 if (op->getOpcode() == BO_PtrMemI)
11554 objectType = objectType->castAs<PointerType>()->getPointeeType();
11555 Qualifiers objectQuals = objectType.getQualifiers();
11557 Qualifiers difference = objectQuals - funcQuals;
11558 difference.removeObjCGCAttr();
11559 difference.removeAddressSpace();
11561 std::string qualsString = difference.getAsString();
11562 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11563 << fnType.getUnqualifiedType()
11565 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11568 if (resultType->isMemberPointerType())
11569 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11570 RequireCompleteType(LParenLoc, resultType, 0);
11572 CXXMemberCallExpr *call
11573 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11574 resultType, valueKind, RParenLoc);
11576 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11578 return ExprError();
11580 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11581 return ExprError();
11583 if (CheckOtherCall(call, proto))
11584 return ExprError();
11586 return MaybeBindToTemporary(call);
11589 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11590 return new (Context)
11591 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11593 UnbridgedCastsSet UnbridgedCasts;
11594 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11595 return ExprError();
11597 MemberExpr *MemExpr;
11598 CXXMethodDecl *Method = nullptr;
11599 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11600 NestedNameSpecifier *Qualifier = nullptr;
11601 if (isa<MemberExpr>(NakedMemExpr)) {
11602 MemExpr = cast<MemberExpr>(NakedMemExpr);
11603 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11604 FoundDecl = MemExpr->getFoundDecl();
11605 Qualifier = MemExpr->getQualifier();
11606 UnbridgedCasts.restore();
11608 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11609 Qualifier = UnresExpr->getQualifier();
11611 QualType ObjectType = UnresExpr->getBaseType();
11612 Expr::Classification ObjectClassification
11613 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11614 : UnresExpr->getBase()->Classify(Context);
11616 // Add overload candidates
11617 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11618 OverloadCandidateSet::CSK_Normal);
11620 // FIXME: avoid copy.
11621 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11622 if (UnresExpr->hasExplicitTemplateArgs()) {
11623 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11624 TemplateArgs = &TemplateArgsBuffer;
11627 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11628 E = UnresExpr->decls_end(); I != E; ++I) {
11630 NamedDecl *Func = *I;
11631 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11632 if (isa<UsingShadowDecl>(Func))
11633 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11636 // Microsoft supports direct constructor calls.
11637 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11638 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11639 Args, CandidateSet);
11640 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11641 // If explicit template arguments were provided, we can't call a
11642 // non-template member function.
11646 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11647 ObjectClassification, Args, CandidateSet,
11648 /*SuppressUserConversions=*/false);
11650 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11651 I.getPair(), ActingDC, TemplateArgs,
11652 ObjectType, ObjectClassification,
11653 Args, CandidateSet,
11654 /*SuppressUsedConversions=*/false);
11658 DeclarationName DeclName = UnresExpr->getMemberName();
11660 UnbridgedCasts.restore();
11662 OverloadCandidateSet::iterator Best;
11663 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11666 Method = cast<CXXMethodDecl>(Best->Function);
11667 FoundDecl = Best->FoundDecl;
11668 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11669 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11670 return ExprError();
11671 // If FoundDecl is different from Method (such as if one is a template
11672 // and the other a specialization), make sure DiagnoseUseOfDecl is
11674 // FIXME: This would be more comprehensively addressed by modifying
11675 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11677 if (Method != FoundDecl.getDecl() &&
11678 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11679 return ExprError();
11682 case OR_No_Viable_Function:
11683 Diag(UnresExpr->getMemberLoc(),
11684 diag::err_ovl_no_viable_member_function_in_call)
11685 << DeclName << MemExprE->getSourceRange();
11686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11687 // FIXME: Leaking incoming expressions!
11688 return ExprError();
11691 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11692 << DeclName << MemExprE->getSourceRange();
11693 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11694 // FIXME: Leaking incoming expressions!
11695 return ExprError();
11698 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11699 << Best->Function->isDeleted()
11701 << getDeletedOrUnavailableSuffix(Best->Function)
11702 << MemExprE->getSourceRange();
11703 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11704 // FIXME: Leaking incoming expressions!
11705 return ExprError();
11708 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11710 // If overload resolution picked a static member, build a
11711 // non-member call based on that function.
11712 if (Method->isStatic()) {
11713 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11717 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11720 QualType ResultType = Method->getReturnType();
11721 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11722 ResultType = ResultType.getNonLValueExprType(Context);
11724 assert(Method && "Member call to something that isn't a method?");
11725 CXXMemberCallExpr *TheCall =
11726 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11727 ResultType, VK, RParenLoc);
11729 // (CUDA B.1): Check for invalid calls between targets.
11730 if (getLangOpts().CUDA) {
11731 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11732 if (CheckCUDATarget(Caller, Method)) {
11733 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11734 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11735 << IdentifyCUDATarget(Caller);
11736 return ExprError();
11741 // Check for a valid return type.
11742 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11744 return ExprError();
11746 // Convert the object argument (for a non-static member function call).
11747 // We only need to do this if there was actually an overload; otherwise
11748 // it was done at lookup.
11749 if (!Method->isStatic()) {
11750 ExprResult ObjectArg =
11751 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11752 FoundDecl, Method);
11753 if (ObjectArg.isInvalid())
11754 return ExprError();
11755 MemExpr->setBase(ObjectArg.get());
11758 // Convert the rest of the arguments
11759 const FunctionProtoType *Proto =
11760 Method->getType()->getAs<FunctionProtoType>();
11761 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11763 return ExprError();
11765 DiagnoseSentinelCalls(Method, LParenLoc, Args);
11767 if (CheckFunctionCall(Method, TheCall, Proto))
11768 return ExprError();
11770 if ((isa<CXXConstructorDecl>(CurContext) ||
11771 isa<CXXDestructorDecl>(CurContext)) &&
11772 TheCall->getMethodDecl()->isPure()) {
11773 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11775 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11776 Diag(MemExpr->getLocStart(),
11777 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11778 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11779 << MD->getParent()->getDeclName();
11781 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11784 return MaybeBindToTemporary(TheCall);
11787 /// BuildCallToObjectOfClassType - Build a call to an object of class
11788 /// type (C++ [over.call.object]), which can end up invoking an
11789 /// overloaded function call operator (@c operator()) or performing a
11790 /// user-defined conversion on the object argument.
11792 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11793 SourceLocation LParenLoc,
11795 SourceLocation RParenLoc) {
11796 if (checkPlaceholderForOverload(*this, Obj))
11797 return ExprError();
11798 ExprResult Object = Obj;
11800 UnbridgedCastsSet UnbridgedCasts;
11801 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11802 return ExprError();
11804 assert(Object.get()->getType()->isRecordType() &&
11805 "Requires object type argument");
11806 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11808 // C++ [over.call.object]p1:
11809 // If the primary-expression E in the function call syntax
11810 // evaluates to a class object of type "cv T", then the set of
11811 // candidate functions includes at least the function call
11812 // operators of T. The function call operators of T are obtained by
11813 // ordinary lookup of the name operator() in the context of
11815 OverloadCandidateSet CandidateSet(LParenLoc,
11816 OverloadCandidateSet::CSK_Operator);
11817 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11819 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11820 diag::err_incomplete_object_call, Object.get()))
11823 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11824 LookupQualifiedName(R, Record->getDecl());
11825 R.suppressDiagnostics();
11827 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11828 Oper != OperEnd; ++Oper) {
11829 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11830 Object.get()->Classify(Context),
11831 Args, CandidateSet,
11832 /*SuppressUserConversions=*/ false);
11835 // C++ [over.call.object]p2:
11836 // In addition, for each (non-explicit in C++0x) conversion function
11837 // declared in T of the form
11839 // operator conversion-type-id () cv-qualifier;
11841 // where cv-qualifier is the same cv-qualification as, or a
11842 // greater cv-qualification than, cv, and where conversion-type-id
11843 // denotes the type "pointer to function of (P1,...,Pn) returning
11844 // R", or the type "reference to pointer to function of
11845 // (P1,...,Pn) returning R", or the type "reference to function
11846 // of (P1,...,Pn) returning R", a surrogate call function [...]
11847 // is also considered as a candidate function. Similarly,
11848 // surrogate call functions are added to the set of candidate
11849 // functions for each conversion function declared in an
11850 // accessible base class provided the function is not hidden
11851 // within T by another intervening declaration.
11852 const auto &Conversions =
11853 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11854 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
11856 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11857 if (isa<UsingShadowDecl>(D))
11858 D = cast<UsingShadowDecl>(D)->getTargetDecl();
11860 // Skip over templated conversion functions; they aren't
11862 if (isa<FunctionTemplateDecl>(D))
11865 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11866 if (!Conv->isExplicit()) {
11867 // Strip the reference type (if any) and then the pointer type (if
11868 // any) to get down to what might be a function type.
11869 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11870 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11871 ConvType = ConvPtrType->getPointeeType();
11873 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11875 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11876 Object.get(), Args, CandidateSet);
11881 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11883 // Perform overload resolution.
11884 OverloadCandidateSet::iterator Best;
11885 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11888 // Overload resolution succeeded; we'll build the appropriate call
11892 case OR_No_Viable_Function:
11893 if (CandidateSet.empty())
11894 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11895 << Object.get()->getType() << /*call*/ 1
11896 << Object.get()->getSourceRange();
11898 Diag(Object.get()->getLocStart(),
11899 diag::err_ovl_no_viable_object_call)
11900 << Object.get()->getType() << Object.get()->getSourceRange();
11901 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11905 Diag(Object.get()->getLocStart(),
11906 diag::err_ovl_ambiguous_object_call)
11907 << Object.get()->getType() << Object.get()->getSourceRange();
11908 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11912 Diag(Object.get()->getLocStart(),
11913 diag::err_ovl_deleted_object_call)
11914 << Best->Function->isDeleted()
11915 << Object.get()->getType()
11916 << getDeletedOrUnavailableSuffix(Best->Function)
11917 << Object.get()->getSourceRange();
11918 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11922 if (Best == CandidateSet.end())
11925 UnbridgedCasts.restore();
11927 if (Best->Function == nullptr) {
11928 // Since there is no function declaration, this is one of the
11929 // surrogate candidates. Dig out the conversion function.
11930 CXXConversionDecl *Conv
11931 = cast<CXXConversionDecl>(
11932 Best->Conversions[0].UserDefined.ConversionFunction);
11934 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11936 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11937 return ExprError();
11938 assert(Conv == Best->FoundDecl.getDecl() &&
11939 "Found Decl & conversion-to-functionptr should be same, right?!");
11940 // We selected one of the surrogate functions that converts the
11941 // object parameter to a function pointer. Perform the conversion
11942 // on the object argument, then let ActOnCallExpr finish the job.
11944 // Create an implicit member expr to refer to the conversion operator.
11945 // and then call it.
11946 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11947 Conv, HadMultipleCandidates);
11948 if (Call.isInvalid())
11949 return ExprError();
11950 // Record usage of conversion in an implicit cast.
11951 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11952 CK_UserDefinedConversion, Call.get(),
11953 nullptr, VK_RValue);
11955 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11958 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11960 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11961 // that calls this method, using Object for the implicit object
11962 // parameter and passing along the remaining arguments.
11963 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11965 // An error diagnostic has already been printed when parsing the declaration.
11966 if (Method->isInvalidDecl())
11967 return ExprError();
11969 const FunctionProtoType *Proto =
11970 Method->getType()->getAs<FunctionProtoType>();
11972 unsigned NumParams = Proto->getNumParams();
11974 DeclarationNameInfo OpLocInfo(
11975 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11976 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11977 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11978 HadMultipleCandidates,
11979 OpLocInfo.getLoc(),
11980 OpLocInfo.getInfo());
11981 if (NewFn.isInvalid())
11984 // Build the full argument list for the method call (the implicit object
11985 // parameter is placed at the beginning of the list).
11986 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11987 MethodArgs[0] = Object.get();
11988 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11990 // Once we've built TheCall, all of the expressions are properly
11992 QualType ResultTy = Method->getReturnType();
11993 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11994 ResultTy = ResultTy.getNonLValueExprType(Context);
11996 CXXOperatorCallExpr *TheCall = new (Context)
11997 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11998 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11999 ResultTy, VK, RParenLoc, false);
12000 MethodArgs.reset();
12002 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12005 // We may have default arguments. If so, we need to allocate more
12006 // slots in the call for them.
12007 if (Args.size() < NumParams)
12008 TheCall->setNumArgs(Context, NumParams + 1);
12010 bool IsError = false;
12012 // Initialize the implicit object parameter.
12013 ExprResult ObjRes =
12014 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12015 Best->FoundDecl, Method);
12016 if (ObjRes.isInvalid())
12020 TheCall->setArg(0, Object.get());
12022 // Check the argument types.
12023 for (unsigned i = 0; i != NumParams; i++) {
12025 if (i < Args.size()) {
12028 // Pass the argument.
12030 ExprResult InputInit
12031 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12033 Method->getParamDecl(i)),
12034 SourceLocation(), Arg);
12036 IsError |= InputInit.isInvalid();
12037 Arg = InputInit.getAs<Expr>();
12040 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12041 if (DefArg.isInvalid()) {
12046 Arg = DefArg.getAs<Expr>();
12049 TheCall->setArg(i + 1, Arg);
12052 // If this is a variadic call, handle args passed through "...".
12053 if (Proto->isVariadic()) {
12054 // Promote the arguments (C99 6.5.2.2p7).
12055 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12056 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12058 IsError |= Arg.isInvalid();
12059 TheCall->setArg(i + 1, Arg.get());
12063 if (IsError) return true;
12065 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12067 if (CheckFunctionCall(Method, TheCall, Proto))
12070 return MaybeBindToTemporary(TheCall);
12073 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12074 /// (if one exists), where @c Base is an expression of class type and
12075 /// @c Member is the name of the member we're trying to find.
12077 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12078 bool *NoArrowOperatorFound) {
12079 assert(Base->getType()->isRecordType() &&
12080 "left-hand side must have class type");
12082 if (checkPlaceholderForOverload(*this, Base))
12083 return ExprError();
12085 SourceLocation Loc = Base->getExprLoc();
12087 // C++ [over.ref]p1:
12089 // [...] An expression x->m is interpreted as (x.operator->())->m
12090 // for a class object x of type T if T::operator->() exists and if
12091 // the operator is selected as the best match function by the
12092 // overload resolution mechanism (13.3).
12093 DeclarationName OpName =
12094 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12095 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12096 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12098 if (RequireCompleteType(Loc, Base->getType(),
12099 diag::err_typecheck_incomplete_tag, Base))
12100 return ExprError();
12102 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12103 LookupQualifiedName(R, BaseRecord->getDecl());
12104 R.suppressDiagnostics();
12106 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12107 Oper != OperEnd; ++Oper) {
12108 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12109 None, CandidateSet, /*SuppressUserConversions=*/false);
12112 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12114 // Perform overload resolution.
12115 OverloadCandidateSet::iterator Best;
12116 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12118 // Overload resolution succeeded; we'll build the call below.
12121 case OR_No_Viable_Function:
12122 if (CandidateSet.empty()) {
12123 QualType BaseType = Base->getType();
12124 if (NoArrowOperatorFound) {
12125 // Report this specific error to the caller instead of emitting a
12126 // diagnostic, as requested.
12127 *NoArrowOperatorFound = true;
12128 return ExprError();
12130 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12131 << BaseType << Base->getSourceRange();
12132 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12133 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12134 << FixItHint::CreateReplacement(OpLoc, ".");
12137 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12138 << "operator->" << Base->getSourceRange();
12139 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12140 return ExprError();
12143 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12144 << "->" << Base->getType() << Base->getSourceRange();
12145 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12146 return ExprError();
12149 Diag(OpLoc, diag::err_ovl_deleted_oper)
12150 << Best->Function->isDeleted()
12152 << getDeletedOrUnavailableSuffix(Best->Function)
12153 << Base->getSourceRange();
12154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12155 return ExprError();
12158 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12160 // Convert the object parameter.
12161 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12162 ExprResult BaseResult =
12163 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12164 Best->FoundDecl, Method);
12165 if (BaseResult.isInvalid())
12166 return ExprError();
12167 Base = BaseResult.get();
12169 // Build the operator call.
12170 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12171 HadMultipleCandidates, OpLoc);
12172 if (FnExpr.isInvalid())
12173 return ExprError();
12175 QualType ResultTy = Method->getReturnType();
12176 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12177 ResultTy = ResultTy.getNonLValueExprType(Context);
12178 CXXOperatorCallExpr *TheCall =
12179 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12180 Base, ResultTy, VK, OpLoc, false);
12182 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12183 return ExprError();
12185 return MaybeBindToTemporary(TheCall);
12188 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12189 /// a literal operator described by the provided lookup results.
12190 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12191 DeclarationNameInfo &SuffixInfo,
12192 ArrayRef<Expr*> Args,
12193 SourceLocation LitEndLoc,
12194 TemplateArgumentListInfo *TemplateArgs) {
12195 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12197 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12198 OverloadCandidateSet::CSK_Normal);
12199 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12200 /*SuppressUserConversions=*/true);
12202 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12204 // Perform overload resolution. This will usually be trivial, but might need
12205 // to perform substitutions for a literal operator template.
12206 OverloadCandidateSet::iterator Best;
12207 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12212 case OR_No_Viable_Function:
12213 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12214 << R.getLookupName();
12215 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12216 return ExprError();
12219 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12220 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12221 return ExprError();
12224 FunctionDecl *FD = Best->Function;
12225 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12226 HadMultipleCandidates,
12227 SuffixInfo.getLoc(),
12228 SuffixInfo.getInfo());
12229 if (Fn.isInvalid())
12232 // Check the argument types. This should almost always be a no-op, except
12233 // that array-to-pointer decay is applied to string literals.
12235 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12236 ExprResult InputInit = PerformCopyInitialization(
12237 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12238 SourceLocation(), Args[ArgIdx]);
12239 if (InputInit.isInvalid())
12241 ConvArgs[ArgIdx] = InputInit.get();
12244 QualType ResultTy = FD->getReturnType();
12245 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12246 ResultTy = ResultTy.getNonLValueExprType(Context);
12248 UserDefinedLiteral *UDL =
12249 new (Context) UserDefinedLiteral(Context, Fn.get(),
12250 llvm::makeArrayRef(ConvArgs, Args.size()),
12251 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12253 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12254 return ExprError();
12256 if (CheckFunctionCall(FD, UDL, nullptr))
12257 return ExprError();
12259 return MaybeBindToTemporary(UDL);
12262 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12263 /// given LookupResult is non-empty, it is assumed to describe a member which
12264 /// will be invoked. Otherwise, the function will be found via argument
12265 /// dependent lookup.
12266 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12267 /// otherwise CallExpr is set to ExprError() and some non-success value
12269 Sema::ForRangeStatus
12270 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12271 SourceLocation RangeLoc, VarDecl *Decl,
12272 BeginEndFunction BEF,
12273 const DeclarationNameInfo &NameInfo,
12274 LookupResult &MemberLookup,
12275 OverloadCandidateSet *CandidateSet,
12276 Expr *Range, ExprResult *CallExpr) {
12277 CandidateSet->clear();
12278 if (!MemberLookup.empty()) {
12279 ExprResult MemberRef =
12280 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12281 /*IsPtr=*/false, CXXScopeSpec(),
12282 /*TemplateKWLoc=*/SourceLocation(),
12283 /*FirstQualifierInScope=*/nullptr,
12285 /*TemplateArgs=*/nullptr);
12286 if (MemberRef.isInvalid()) {
12287 *CallExpr = ExprError();
12288 Diag(Range->getLocStart(), diag::note_in_for_range)
12289 << RangeLoc << BEF << Range->getType();
12290 return FRS_DiagnosticIssued;
12292 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12293 if (CallExpr->isInvalid()) {
12294 *CallExpr = ExprError();
12295 Diag(Range->getLocStart(), diag::note_in_for_range)
12296 << RangeLoc << BEF << Range->getType();
12297 return FRS_DiagnosticIssued;
12300 UnresolvedSet<0> FoundNames;
12301 UnresolvedLookupExpr *Fn =
12302 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12303 NestedNameSpecifierLoc(), NameInfo,
12304 /*NeedsADL=*/true, /*Overloaded=*/false,
12305 FoundNames.begin(), FoundNames.end());
12307 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12308 CandidateSet, CallExpr);
12309 if (CandidateSet->empty() || CandidateSetError) {
12310 *CallExpr = ExprError();
12311 return FRS_NoViableFunction;
12313 OverloadCandidateSet::iterator Best;
12314 OverloadingResult OverloadResult =
12315 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12317 if (OverloadResult == OR_No_Viable_Function) {
12318 *CallExpr = ExprError();
12319 return FRS_NoViableFunction;
12321 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12322 Loc, nullptr, CandidateSet, &Best,
12324 /*AllowTypoCorrection=*/false);
12325 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12326 *CallExpr = ExprError();
12327 Diag(Range->getLocStart(), diag::note_in_for_range)
12328 << RangeLoc << BEF << Range->getType();
12329 return FRS_DiagnosticIssued;
12332 return FRS_Success;
12336 /// FixOverloadedFunctionReference - E is an expression that refers to
12337 /// a C++ overloaded function (possibly with some parentheses and
12338 /// perhaps a '&' around it). We have resolved the overloaded function
12339 /// to the function declaration Fn, so patch up the expression E to
12340 /// refer (possibly indirectly) to Fn. Returns the new expr.
12341 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12342 FunctionDecl *Fn) {
12343 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12344 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12346 if (SubExpr == PE->getSubExpr())
12349 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12352 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12353 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12355 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12356 SubExpr->getType()) &&
12357 "Implicit cast type cannot be determined from overload");
12358 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12359 if (SubExpr == ICE->getSubExpr())
12362 return ImplicitCastExpr::Create(Context, ICE->getType(),
12363 ICE->getCastKind(),
12365 ICE->getValueKind());
12368 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12369 assert(UnOp->getOpcode() == UO_AddrOf &&
12370 "Can only take the address of an overloaded function");
12371 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12372 if (Method->isStatic()) {
12373 // Do nothing: static member functions aren't any different
12374 // from non-member functions.
12376 // Fix the subexpression, which really has to be an
12377 // UnresolvedLookupExpr holding an overloaded member function
12379 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12381 if (SubExpr == UnOp->getSubExpr())
12384 assert(isa<DeclRefExpr>(SubExpr)
12385 && "fixed to something other than a decl ref");
12386 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12387 && "fixed to a member ref with no nested name qualifier");
12389 // We have taken the address of a pointer to member
12390 // function. Perform the computation here so that we get the
12391 // appropriate pointer to member type.
12393 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12394 QualType MemPtrType
12395 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12397 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12398 VK_RValue, OK_Ordinary,
12399 UnOp->getOperatorLoc());
12402 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12404 if (SubExpr == UnOp->getSubExpr())
12407 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12408 Context.getPointerType(SubExpr->getType()),
12409 VK_RValue, OK_Ordinary,
12410 UnOp->getOperatorLoc());
12413 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12414 // FIXME: avoid copy.
12415 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12416 if (ULE->hasExplicitTemplateArgs()) {
12417 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12418 TemplateArgs = &TemplateArgsBuffer;
12421 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12422 ULE->getQualifierLoc(),
12423 ULE->getTemplateKeywordLoc(),
12425 /*enclosing*/ false, // FIXME?
12431 MarkDeclRefReferenced(DRE);
12432 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12436 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12437 // FIXME: avoid copy.
12438 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12439 if (MemExpr->hasExplicitTemplateArgs()) {
12440 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12441 TemplateArgs = &TemplateArgsBuffer;
12446 // If we're filling in a static method where we used to have an
12447 // implicit member access, rewrite to a simple decl ref.
12448 if (MemExpr->isImplicitAccess()) {
12449 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12450 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12451 MemExpr->getQualifierLoc(),
12452 MemExpr->getTemplateKeywordLoc(),
12454 /*enclosing*/ false,
12455 MemExpr->getMemberLoc(),
12460 MarkDeclRefReferenced(DRE);
12461 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12464 SourceLocation Loc = MemExpr->getMemberLoc();
12465 if (MemExpr->getQualifier())
12466 Loc = MemExpr->getQualifierLoc().getBeginLoc();
12467 CheckCXXThisCapture(Loc);
12468 Base = new (Context) CXXThisExpr(Loc,
12469 MemExpr->getBaseType(),
12470 /*isImplicit=*/true);
12473 Base = MemExpr->getBase();
12475 ExprValueKind valueKind;
12477 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12478 valueKind = VK_LValue;
12479 type = Fn->getType();
12481 valueKind = VK_RValue;
12482 type = Context.BoundMemberTy;
12485 MemberExpr *ME = MemberExpr::Create(
12486 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12487 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12488 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12490 ME->setHadMultipleCandidates(true);
12491 MarkMemberReferenced(ME);
12495 llvm_unreachable("Invalid reference to overloaded function");
12498 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12499 DeclAccessPair Found,
12500 FunctionDecl *Fn) {
12501 return FixOverloadedFunctionReference(E.get(), Found, Fn);