1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 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/Optional.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallString.h" 36 #include <algorithm> 37 #include <cstdlib> 38 39 using namespace clang; 40 using namespace sema; 41 42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 44 return P->hasAttr<PassObjectSizeAttr>(); 45 }); 46 } 47 48 /// A convenience routine for creating a decayed reference to a function. 49 static ExprResult 50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 51 const Expr *Base, bool HadMultipleCandidates, 52 SourceLocation Loc = SourceLocation(), 53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 55 return ExprError(); 56 // If FoundDecl is different from Fn (such as if one is a template 57 // and the other a specialization), make sure DiagnoseUseOfDecl is 58 // called on both. 59 // FIXME: This would be more comprehensively addressed by modifying 60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 61 // being used. 62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 63 return ExprError(); 64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 65 S.ResolveExceptionSpec(Loc, FPT); 66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 67 VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 73 CK_FunctionToPointerDecay); 74 } 75 76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle, 80 bool AllowObjCWritebackConversion); 81 82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 83 QualType &ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle); 87 static OverloadingResult 88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 89 UserDefinedConversionSequence& User, 90 OverloadCandidateSet& Conversions, 91 bool AllowExplicit, 92 bool AllowObjCConversionOnExplicit); 93 94 95 static ImplicitConversionSequence::CompareKind 96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareQualificationConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 /// GetConversionRank - Retrieve the implicit conversion rank 111 /// corresponding to the given implicit conversion kind. 112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 113 static const ImplicitConversionRank 114 Rank[(int)ICK_Num_Conversion_Kinds] = { 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Promotion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_OCL_Scalar_Widening, 135 ICR_Complex_Real_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Writeback_Conversion, 139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 140 // it was omitted by the patch that added 141 // ICK_Zero_Event_Conversion 142 ICR_C_Conversion, 143 ICR_C_Conversion_Extension 144 }; 145 return Rank[(int)Kind]; 146 } 147 148 /// GetImplicitConversionName - Return the name of this kind of 149 /// implicit conversion. 150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 152 "No conversion", 153 "Lvalue-to-rvalue", 154 "Array-to-pointer", 155 "Function-to-pointer", 156 "Function pointer conversion", 157 "Qualification", 158 "Integral promotion", 159 "Floating point promotion", 160 "Complex promotion", 161 "Integral conversion", 162 "Floating conversion", 163 "Complex conversion", 164 "Floating-integral conversion", 165 "Pointer conversion", 166 "Pointer-to-member conversion", 167 "Boolean conversion", 168 "Compatible-types conversion", 169 "Derived-to-base conversion", 170 "Vector conversion", 171 "Vector splat", 172 "Complex-real conversion", 173 "Block Pointer conversion", 174 "Transparent Union Conversion", 175 "Writeback conversion", 176 "OpenCL Zero Event Conversion", 177 "C specific type conversion", 178 "Incompatible pointer conversion" 179 }; 180 return Name[Kind]; 181 } 182 183 /// StandardConversionSequence - Set the standard conversion 184 /// sequence to the identity conversion. 185 void StandardConversionSequence::setAsIdentityConversion() { 186 First = ICK_Identity; 187 Second = ICK_Identity; 188 Third = ICK_Identity; 189 DeprecatedStringLiteralToCharPtr = false; 190 QualificationIncludesObjCLifetime = false; 191 ReferenceBinding = false; 192 DirectBinding = false; 193 IsLvalueReference = true; 194 BindsToFunctionLvalue = false; 195 BindsToRvalue = false; 196 BindsImplicitObjectArgumentWithoutRefQualifier = false; 197 ObjCLifetimeConversionBinding = false; 198 CopyConstructor = nullptr; 199 } 200 201 /// getRank - Retrieve the rank of this standard conversion sequence 202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203 /// implicit conversions. 204 ImplicitConversionRank StandardConversionSequence::getRank() const { 205 ImplicitConversionRank Rank = ICR_Exact_Match; 206 if (GetConversionRank(First) > Rank) 207 Rank = GetConversionRank(First); 208 if (GetConversionRank(Second) > Rank) 209 Rank = GetConversionRank(Second); 210 if (GetConversionRank(Third) > Rank) 211 Rank = GetConversionRank(Third); 212 return Rank; 213 } 214 215 /// isPointerConversionToBool - Determines whether this conversion is 216 /// a conversion of a pointer or pointer-to-member to bool. This is 217 /// used as part of the ranking of standard conversion sequences 218 /// (C++ 13.3.3.2p4). 219 bool StandardConversionSequence::isPointerConversionToBool() const { 220 // Note that FromType has not necessarily been transformed by the 221 // array-to-pointer or function-to-pointer implicit conversions, so 222 // check for their presence as well as checking whether FromType is 223 // a pointer. 224 if (getToType(1)->isBooleanType() && 225 (getFromType()->isPointerType() || 226 getFromType()->isMemberPointerType() || 227 getFromType()->isObjCObjectPointerType() || 228 getFromType()->isBlockPointerType() || 229 getFromType()->isNullPtrType() || 230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 231 return true; 232 233 return false; 234 } 235 236 /// isPointerConversionToVoidPointer - Determines whether this 237 /// conversion is a conversion of a pointer to a void pointer. This is 238 /// used as part of the ranking of standard conversion sequences (C++ 239 /// 13.3.3.2p4). 240 bool 241 StandardConversionSequence:: 242 isPointerConversionToVoidPointer(ASTContext& Context) const { 243 QualType FromType = getFromType(); 244 QualType ToType = getToType(1); 245 246 // Note that FromType has not necessarily been transformed by the 247 // array-to-pointer implicit conversion, so check for its presence 248 // and redo the conversion to get a pointer. 249 if (First == ICK_Array_To_Pointer) 250 FromType = Context.getArrayDecayedType(FromType); 251 252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 254 return ToPtrType->getPointeeType()->isVoidType(); 255 256 return false; 257 } 258 259 /// Skip any implicit casts which could be either part of a narrowing conversion 260 /// or after one in an implicit conversion. 261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 263 switch (ICE->getCastKind()) { 264 case CK_NoOp: 265 case CK_IntegralCast: 266 case CK_IntegralToBoolean: 267 case CK_IntegralToFloating: 268 case CK_BooleanToSignedIntegral: 269 case CK_FloatingToIntegral: 270 case CK_FloatingToBoolean: 271 case CK_FloatingCast: 272 Converted = ICE->getSubExpr(); 273 continue; 274 275 default: 276 return Converted; 277 } 278 } 279 280 return Converted; 281 } 282 283 /// Check if this standard conversion sequence represents a narrowing 284 /// conversion, according to C++11 [dcl.init.list]p7. 285 /// 286 /// \param Ctx The AST context. 287 /// \param Converted The result of applying this standard conversion sequence. 288 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 289 /// value of the expression prior to the narrowing conversion. 290 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 291 /// type of the expression prior to the narrowing conversion. 292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 293 /// from floating point types to integral types should be ignored. 294 NarrowingKind StandardConversionSequence::getNarrowingKind( 295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 298 299 // C++11 [dcl.init.list]p7: 300 // A narrowing conversion is an implicit conversion ... 301 QualType FromType = getToType(0); 302 QualType ToType = getToType(1); 303 304 // A conversion to an enumeration type is narrowing if the conversion to 305 // the underlying type is narrowing. This only arises for expressions of 306 // the form 'Enum{init}'. 307 if (auto *ET = ToType->getAs<EnumType>()) 308 ToType = ET->getDecl()->getIntegerType(); 309 310 switch (Second) { 311 // 'bool' is an integral type; dispatch to the right place to handle it. 312 case ICK_Boolean_Conversion: 313 if (FromType->isRealFloatingType()) 314 goto FloatingIntegralConversion; 315 if (FromType->isIntegralOrUnscopedEnumerationType()) 316 goto IntegralConversion; 317 // Boolean conversions can be from pointers and pointers to members 318 // [conv.bool], and those aren't considered narrowing conversions. 319 return NK_Not_Narrowing; 320 321 // -- from a floating-point type to an integer type, or 322 // 323 // -- from an integer type or unscoped enumeration type to a floating-point 324 // type, except where the source is a constant expression and the actual 325 // value after conversion will fit into the target type and will produce 326 // the original value when converted back to the original type, or 327 case ICK_Floating_Integral: 328 FloatingIntegralConversion: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 332 ToType->isRealFloatingType()) { 333 if (IgnoreFloatToIntegralConversion) 334 return NK_Not_Narrowing; 335 llvm::APSInt IntConstantValue; 336 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 337 assert(Initializer && "Unknown conversion expression"); 338 339 // If it's value-dependent, we can't tell whether it's narrowing. 340 if (Initializer->isValueDependent()) 341 return NK_Dependent_Narrowing; 342 343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 344 // Convert the integer to the floating type. 345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 347 llvm::APFloat::rmNearestTiesToEven); 348 // And back. 349 llvm::APSInt ConvertedValue = IntConstantValue; 350 bool ignored; 351 Result.convertToInteger(ConvertedValue, 352 llvm::APFloat::rmTowardZero, &ignored); 353 // If the resulting value is different, this was a narrowing conversion. 354 if (IntConstantValue != ConvertedValue) { 355 ConstantValue = APValue(IntConstantValue); 356 ConstantType = Initializer->getType(); 357 return NK_Constant_Narrowing; 358 } 359 } else { 360 // Variables are always narrowings. 361 return NK_Variable_Narrowing; 362 } 363 } 364 return NK_Not_Narrowing; 365 366 // -- from long double to double or float, or from double to float, except 367 // where the source is a constant expression and the actual value after 368 // conversion is within the range of values that can be represented (even 369 // if it cannot be represented exactly), or 370 case ICK_Floating_Conversion: 371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 373 // FromType is larger than ToType. 374 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 375 376 // If it's value-dependent, we can't tell whether it's narrowing. 377 if (Initializer->isValueDependent()) 378 return NK_Dependent_Narrowing; 379 380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 381 // Constant! 382 assert(ConstantValue.isFloat()); 383 llvm::APFloat FloatVal = ConstantValue.getFloat(); 384 // Convert the source value into the target type. 385 bool ignored; 386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 387 Ctx.getFloatTypeSemantics(ToType), 388 llvm::APFloat::rmNearestTiesToEven, &ignored); 389 // If there was no overflow, the source value is within the range of 390 // values that can be represented. 391 if (ConvertStatus & llvm::APFloat::opOverflow) { 392 ConstantType = Initializer->getType(); 393 return NK_Constant_Narrowing; 394 } 395 } else { 396 return NK_Variable_Narrowing; 397 } 398 } 399 return NK_Not_Narrowing; 400 401 // -- from an integer type or unscoped enumeration type to an integer type 402 // that cannot represent all the values of the original type, except where 403 // the source is a constant expression and the actual value after 404 // conversion will fit into the target type and will produce the original 405 // value when converted back to the original type. 406 case ICK_Integral_Conversion: 407 IntegralConversion: { 408 assert(FromType->isIntegralOrUnscopedEnumerationType()); 409 assert(ToType->isIntegralOrUnscopedEnumerationType()); 410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 411 const unsigned FromWidth = Ctx.getIntWidth(FromType); 412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 413 const unsigned ToWidth = Ctx.getIntWidth(ToType); 414 415 if (FromWidth > ToWidth || 416 (FromWidth == ToWidth && FromSigned != ToSigned) || 417 (FromSigned && !ToSigned)) { 418 // Not all values of FromType can be represented in ToType. 419 llvm::APSInt InitializerValue; 420 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 421 422 // If it's value-dependent, we can't tell whether it's narrowing. 423 if (Initializer->isValueDependent()) 424 return NK_Dependent_Narrowing; 425 426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 427 // Such conversions on variables are always narrowing. 428 return NK_Variable_Narrowing; 429 } 430 bool Narrowing = false; 431 if (FromWidth < ToWidth) { 432 // Negative -> unsigned is narrowing. Otherwise, more bits is never 433 // narrowing. 434 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 435 Narrowing = true; 436 } else { 437 // Add a bit to the InitializerValue so we don't have to worry about 438 // signed vs. unsigned comparisons. 439 InitializerValue = InitializerValue.extend( 440 InitializerValue.getBitWidth() + 1); 441 // Convert the initializer to and from the target width and signed-ness. 442 llvm::APSInt ConvertedValue = InitializerValue; 443 ConvertedValue = ConvertedValue.trunc(ToWidth); 444 ConvertedValue.setIsSigned(ToSigned); 445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 446 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 447 // If the result is different, this was a narrowing conversion. 448 if (ConvertedValue != InitializerValue) 449 Narrowing = true; 450 } 451 if (Narrowing) { 452 ConstantType = Initializer->getType(); 453 ConstantValue = APValue(InitializerValue); 454 return NK_Constant_Narrowing; 455 } 456 } 457 return NK_Not_Narrowing; 458 } 459 460 default: 461 // Other kinds of conversions are not narrowings. 462 return NK_Not_Narrowing; 463 } 464 } 465 466 /// dump - Print this standard conversion sequence to standard 467 /// error. Useful for debugging overloading issues. 468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 469 raw_ostream &OS = llvm::errs(); 470 bool PrintedSomething = false; 471 if (First != ICK_Identity) { 472 OS << GetImplicitConversionName(First); 473 PrintedSomething = true; 474 } 475 476 if (Second != ICK_Identity) { 477 if (PrintedSomething) { 478 OS << " -> "; 479 } 480 OS << GetImplicitConversionName(Second); 481 482 if (CopyConstructor) { 483 OS << " (by copy constructor)"; 484 } else if (DirectBinding) { 485 OS << " (direct reference binding)"; 486 } else if (ReferenceBinding) { 487 OS << " (reference binding)"; 488 } 489 PrintedSomething = true; 490 } 491 492 if (Third != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Third); 497 PrintedSomething = true; 498 } 499 500 if (!PrintedSomething) { 501 OS << "No conversions required"; 502 } 503 } 504 505 /// dump - Print this user-defined conversion sequence to standard 506 /// error. Useful for debugging overloading issues. 507 void UserDefinedConversionSequence::dump() const { 508 raw_ostream &OS = llvm::errs(); 509 if (Before.First || Before.Second || Before.Third) { 510 Before.dump(); 511 OS << " -> "; 512 } 513 if (ConversionFunction) 514 OS << '\'' << *ConversionFunction << '\''; 515 else 516 OS << "aggregate initialization"; 517 if (After.First || After.Second || After.Third) { 518 OS << " -> "; 519 After.dump(); 520 } 521 } 522 523 /// dump - Print this implicit conversion sequence to standard 524 /// error. Useful for debugging overloading issues. 525 void ImplicitConversionSequence::dump() const { 526 raw_ostream &OS = llvm::errs(); 527 if (isStdInitializerListElement()) 528 OS << "Worst std::initializer_list element conversion: "; 529 switch (ConversionKind) { 530 case StandardConversion: 531 OS << "Standard conversion: "; 532 Standard.dump(); 533 break; 534 case UserDefinedConversion: 535 OS << "User-defined conversion: "; 536 UserDefined.dump(); 537 break; 538 case EllipsisConversion: 539 OS << "Ellipsis conversion"; 540 break; 541 case AmbiguousConversion: 542 OS << "Ambiguous conversion"; 543 break; 544 case BadConversion: 545 OS << "Bad conversion"; 546 break; 547 } 548 549 OS << "\n"; 550 } 551 552 void AmbiguousConversionSequence::construct() { 553 new (&conversions()) ConversionSet(); 554 } 555 556 void AmbiguousConversionSequence::destruct() { 557 conversions().~ConversionSet(); 558 } 559 560 void 561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 562 FromTypePtr = O.FromTypePtr; 563 ToTypePtr = O.ToTypePtr; 564 new (&conversions()) ConversionSet(O.conversions()); 565 } 566 567 namespace { 568 // Structure used by DeductionFailureInfo to store 569 // template argument information. 570 struct DFIArguments { 571 TemplateArgument FirstArg; 572 TemplateArgument SecondArg; 573 }; 574 // Structure used by DeductionFailureInfo to store 575 // template parameter and template argument information. 576 struct DFIParamWithArguments : DFIArguments { 577 TemplateParameter Param; 578 }; 579 // Structure used by DeductionFailureInfo to store template argument 580 // information and the index of the problematic call argument. 581 struct DFIDeducedMismatchArgs : DFIArguments { 582 TemplateArgumentList *TemplateArgs; 583 unsigned CallArgIndex; 584 }; 585 } 586 587 /// Convert from Sema's representation of template deduction information 588 /// to the form used in overload-candidate information. 589 DeductionFailureInfo 590 clang::MakeDeductionFailureInfo(ASTContext &Context, 591 Sema::TemplateDeductionResult TDK, 592 TemplateDeductionInfo &Info) { 593 DeductionFailureInfo Result; 594 Result.Result = static_cast<unsigned>(TDK); 595 Result.HasDiagnostic = false; 596 switch (TDK) { 597 case Sema::TDK_Invalid: 598 case Sema::TDK_InstantiationDepth: 599 case Sema::TDK_TooManyArguments: 600 case Sema::TDK_TooFewArguments: 601 case Sema::TDK_MiscellaneousDeductionFailure: 602 case Sema::TDK_CUDATargetMismatch: 603 Result.Data = nullptr; 604 break; 605 606 case Sema::TDK_Incomplete: 607 case Sema::TDK_InvalidExplicitArguments: 608 Result.Data = Info.Param.getOpaqueValue(); 609 break; 610 611 case Sema::TDK_DeducedMismatch: 612 case Sema::TDK_DeducedMismatchNested: { 613 // FIXME: Should allocate from normal heap so that we can free this later. 614 auto *Saved = new (Context) DFIDeducedMismatchArgs; 615 Saved->FirstArg = Info.FirstArg; 616 Saved->SecondArg = Info.SecondArg; 617 Saved->TemplateArgs = Info.take(); 618 Saved->CallArgIndex = Info.CallArgIndex; 619 Result.Data = Saved; 620 break; 621 } 622 623 case Sema::TDK_NonDeducedMismatch: { 624 // FIXME: Should allocate from normal heap so that we can free this later. 625 DFIArguments *Saved = new (Context) DFIArguments; 626 Saved->FirstArg = Info.FirstArg; 627 Saved->SecondArg = Info.SecondArg; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_Inconsistent: 633 case Sema::TDK_Underqualified: { 634 // FIXME: Should allocate from normal heap so that we can free this later. 635 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 636 Saved->Param = Info.Param; 637 Saved->FirstArg = Info.FirstArg; 638 Saved->SecondArg = Info.SecondArg; 639 Result.Data = Saved; 640 break; 641 } 642 643 case Sema::TDK_SubstitutionFailure: 644 Result.Data = Info.take(); 645 if (Info.hasSFINAEDiagnostic()) { 646 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 647 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 648 Info.takeSFINAEDiagnostic(*Diag); 649 Result.HasDiagnostic = true; 650 } 651 break; 652 653 case Sema::TDK_Success: 654 case Sema::TDK_NonDependentConversionFailure: 655 llvm_unreachable("not a deduction failure"); 656 } 657 658 return Result; 659 } 660 661 void DeductionFailureInfo::Destroy() { 662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 663 case Sema::TDK_Success: 664 case Sema::TDK_Invalid: 665 case Sema::TDK_InstantiationDepth: 666 case Sema::TDK_Incomplete: 667 case Sema::TDK_TooManyArguments: 668 case Sema::TDK_TooFewArguments: 669 case Sema::TDK_InvalidExplicitArguments: 670 case Sema::TDK_CUDATargetMismatch: 671 case Sema::TDK_NonDependentConversionFailure: 672 break; 673 674 case Sema::TDK_Inconsistent: 675 case Sema::TDK_Underqualified: 676 case Sema::TDK_DeducedMismatch: 677 case Sema::TDK_DeducedMismatchNested: 678 case Sema::TDK_NonDeducedMismatch: 679 // FIXME: Destroy the data? 680 Data = nullptr; 681 break; 682 683 case Sema::TDK_SubstitutionFailure: 684 // FIXME: Destroy the template argument list? 685 Data = nullptr; 686 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 687 Diag->~PartialDiagnosticAt(); 688 HasDiagnostic = false; 689 } 690 break; 691 692 // Unhandled 693 case Sema::TDK_MiscellaneousDeductionFailure: 694 break; 695 } 696 } 697 698 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 699 if (HasDiagnostic) 700 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 701 return nullptr; 702 } 703 704 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 705 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 706 case Sema::TDK_Success: 707 case Sema::TDK_Invalid: 708 case Sema::TDK_InstantiationDepth: 709 case Sema::TDK_TooManyArguments: 710 case Sema::TDK_TooFewArguments: 711 case Sema::TDK_SubstitutionFailure: 712 case Sema::TDK_DeducedMismatch: 713 case Sema::TDK_DeducedMismatchNested: 714 case Sema::TDK_NonDeducedMismatch: 715 case Sema::TDK_CUDATargetMismatch: 716 case Sema::TDK_NonDependentConversionFailure: 717 return TemplateParameter(); 718 719 case Sema::TDK_Incomplete: 720 case Sema::TDK_InvalidExplicitArguments: 721 return TemplateParameter::getFromOpaqueValue(Data); 722 723 case Sema::TDK_Inconsistent: 724 case Sema::TDK_Underqualified: 725 return static_cast<DFIParamWithArguments*>(Data)->Param; 726 727 // Unhandled 728 case Sema::TDK_MiscellaneousDeductionFailure: 729 break; 730 } 731 732 return TemplateParameter(); 733 } 734 735 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 736 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 737 case Sema::TDK_Success: 738 case Sema::TDK_Invalid: 739 case Sema::TDK_InstantiationDepth: 740 case Sema::TDK_TooManyArguments: 741 case Sema::TDK_TooFewArguments: 742 case Sema::TDK_Incomplete: 743 case Sema::TDK_InvalidExplicitArguments: 744 case Sema::TDK_Inconsistent: 745 case Sema::TDK_Underqualified: 746 case Sema::TDK_NonDeducedMismatch: 747 case Sema::TDK_CUDATargetMismatch: 748 case Sema::TDK_NonDependentConversionFailure: 749 return nullptr; 750 751 case Sema::TDK_DeducedMismatch: 752 case Sema::TDK_DeducedMismatchNested: 753 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 754 755 case Sema::TDK_SubstitutionFailure: 756 return static_cast<TemplateArgumentList*>(Data); 757 758 // Unhandled 759 case Sema::TDK_MiscellaneousDeductionFailure: 760 break; 761 } 762 763 return nullptr; 764 } 765 766 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 767 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 768 case Sema::TDK_Success: 769 case Sema::TDK_Invalid: 770 case Sema::TDK_InstantiationDepth: 771 case Sema::TDK_Incomplete: 772 case Sema::TDK_TooManyArguments: 773 case Sema::TDK_TooFewArguments: 774 case Sema::TDK_InvalidExplicitArguments: 775 case Sema::TDK_SubstitutionFailure: 776 case Sema::TDK_CUDATargetMismatch: 777 case Sema::TDK_NonDependentConversionFailure: 778 return nullptr; 779 780 case Sema::TDK_Inconsistent: 781 case Sema::TDK_Underqualified: 782 case Sema::TDK_DeducedMismatch: 783 case Sema::TDK_DeducedMismatchNested: 784 case Sema::TDK_NonDeducedMismatch: 785 return &static_cast<DFIArguments*>(Data)->FirstArg; 786 787 // Unhandled 788 case Sema::TDK_MiscellaneousDeductionFailure: 789 break; 790 } 791 792 return nullptr; 793 } 794 795 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 796 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 797 case Sema::TDK_Success: 798 case Sema::TDK_Invalid: 799 case Sema::TDK_InstantiationDepth: 800 case Sema::TDK_Incomplete: 801 case Sema::TDK_TooManyArguments: 802 case Sema::TDK_TooFewArguments: 803 case Sema::TDK_InvalidExplicitArguments: 804 case Sema::TDK_SubstitutionFailure: 805 case Sema::TDK_CUDATargetMismatch: 806 case Sema::TDK_NonDependentConversionFailure: 807 return nullptr; 808 809 case Sema::TDK_Inconsistent: 810 case Sema::TDK_Underqualified: 811 case Sema::TDK_DeducedMismatch: 812 case Sema::TDK_DeducedMismatchNested: 813 case Sema::TDK_NonDeducedMismatch: 814 return &static_cast<DFIArguments*>(Data)->SecondArg; 815 816 // Unhandled 817 case Sema::TDK_MiscellaneousDeductionFailure: 818 break; 819 } 820 821 return nullptr; 822 } 823 824 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 825 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 826 case Sema::TDK_DeducedMismatch: 827 case Sema::TDK_DeducedMismatchNested: 828 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 829 830 default: 831 return llvm::None; 832 } 833 } 834 835 void OverloadCandidateSet::destroyCandidates() { 836 for (iterator i = begin(), e = end(); i != e; ++i) { 837 for (auto &C : i->Conversions) 838 C.~ImplicitConversionSequence(); 839 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 840 i->DeductionFailure.Destroy(); 841 } 842 } 843 844 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 845 destroyCandidates(); 846 SlabAllocator.Reset(); 847 NumInlineBytesUsed = 0; 848 Candidates.clear(); 849 Functions.clear(); 850 Kind = CSK; 851 } 852 853 namespace { 854 class UnbridgedCastsSet { 855 struct Entry { 856 Expr **Addr; 857 Expr *Saved; 858 }; 859 SmallVector<Entry, 2> Entries; 860 861 public: 862 void save(Sema &S, Expr *&E) { 863 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 864 Entry entry = { &E, E }; 865 Entries.push_back(entry); 866 E = S.stripARCUnbridgedCast(E); 867 } 868 869 void restore() { 870 for (SmallVectorImpl<Entry>::iterator 871 i = Entries.begin(), e = Entries.end(); i != e; ++i) 872 *i->Addr = i->Saved; 873 } 874 }; 875 } 876 877 /// checkPlaceholderForOverload - Do any interesting placeholder-like 878 /// preprocessing on the given expression. 879 /// 880 /// \param unbridgedCasts a collection to which to add unbridged casts; 881 /// without this, they will be immediately diagnosed as errors 882 /// 883 /// Return true on unrecoverable error. 884 static bool 885 checkPlaceholderForOverload(Sema &S, Expr *&E, 886 UnbridgedCastsSet *unbridgedCasts = nullptr) { 887 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 888 // We can't handle overloaded expressions here because overload 889 // resolution might reasonably tweak them. 890 if (placeholder->getKind() == BuiltinType::Overload) return false; 891 892 // If the context potentially accepts unbridged ARC casts, strip 893 // the unbridged cast and add it to the collection for later restoration. 894 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 895 unbridgedCasts) { 896 unbridgedCasts->save(S, E); 897 return false; 898 } 899 900 // Go ahead and check everything else. 901 ExprResult result = S.CheckPlaceholderExpr(E); 902 if (result.isInvalid()) 903 return true; 904 905 E = result.get(); 906 return false; 907 } 908 909 // Nothing to do. 910 return false; 911 } 912 913 /// checkArgPlaceholdersForOverload - Check a set of call operands for 914 /// placeholders. 915 static bool checkArgPlaceholdersForOverload(Sema &S, 916 MultiExprArg Args, 917 UnbridgedCastsSet &unbridged) { 918 for (unsigned i = 0, e = Args.size(); i != e; ++i) 919 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 920 return true; 921 922 return false; 923 } 924 925 /// Determine whether the given New declaration is an overload of the 926 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 927 /// New and Old cannot be overloaded, e.g., if New has the same signature as 928 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 929 /// functions (or function templates) at all. When it does return Ovl_Match or 930 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 931 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 932 /// declaration. 933 /// 934 /// Example: Given the following input: 935 /// 936 /// void f(int, float); // #1 937 /// void f(int, int); // #2 938 /// int f(int, int); // #3 939 /// 940 /// When we process #1, there is no previous declaration of "f", so IsOverload 941 /// will not be used. 942 /// 943 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 944 /// the parameter types, we see that #1 and #2 are overloaded (since they have 945 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 946 /// unchanged. 947 /// 948 /// When we process #3, Old is an overload set containing #1 and #2. We compare 949 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 950 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 951 /// functions are not part of the signature), IsOverload returns Ovl_Match and 952 /// MatchedDecl will be set to point to the FunctionDecl for #2. 953 /// 954 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 955 /// by a using declaration. The rules for whether to hide shadow declarations 956 /// ignore some properties which otherwise figure into a function template's 957 /// signature. 958 Sema::OverloadKind 959 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 960 NamedDecl *&Match, bool NewIsUsingDecl) { 961 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 962 I != E; ++I) { 963 NamedDecl *OldD = *I; 964 965 bool OldIsUsingDecl = false; 966 if (isa<UsingShadowDecl>(OldD)) { 967 OldIsUsingDecl = true; 968 969 // We can always introduce two using declarations into the same 970 // context, even if they have identical signatures. 971 if (NewIsUsingDecl) continue; 972 973 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 974 } 975 976 // A using-declaration does not conflict with another declaration 977 // if one of them is hidden. 978 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 979 continue; 980 981 // If either declaration was introduced by a using declaration, 982 // we'll need to use slightly different rules for matching. 983 // Essentially, these rules are the normal rules, except that 984 // function templates hide function templates with different 985 // return types or template parameter lists. 986 bool UseMemberUsingDeclRules = 987 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 988 !New->getFriendObjectKind(); 989 990 if (FunctionDecl *OldF = OldD->getAsFunction()) { 991 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 992 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 993 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 994 continue; 995 } 996 997 if (!isa<FunctionTemplateDecl>(OldD) && 998 !shouldLinkPossiblyHiddenDecl(*I, New)) 999 continue; 1000 1001 Match = *I; 1002 return Ovl_Match; 1003 } 1004 1005 // Builtins that have custom typechecking or have a reference should 1006 // not be overloadable or redeclarable. 1007 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1008 Match = *I; 1009 return Ovl_NonFunction; 1010 } 1011 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1012 // We can overload with these, which can show up when doing 1013 // redeclaration checks for UsingDecls. 1014 assert(Old.getLookupKind() == LookupUsingDeclName); 1015 } else if (isa<TagDecl>(OldD)) { 1016 // We can always overload with tags by hiding them. 1017 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1018 // Optimistically assume that an unresolved using decl will 1019 // overload; if it doesn't, we'll have to diagnose during 1020 // template instantiation. 1021 // 1022 // Exception: if the scope is dependent and this is not a class 1023 // member, the using declaration can only introduce an enumerator. 1024 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1025 Match = *I; 1026 return Ovl_NonFunction; 1027 } 1028 } else { 1029 // (C++ 13p1): 1030 // Only function declarations can be overloaded; object and type 1031 // declarations cannot be overloaded. 1032 Match = *I; 1033 return Ovl_NonFunction; 1034 } 1035 } 1036 1037 return Ovl_Overload; 1038 } 1039 1040 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1041 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1042 // C++ [basic.start.main]p2: This function shall not be overloaded. 1043 if (New->isMain()) 1044 return false; 1045 1046 // MSVCRT user defined entry points cannot be overloaded. 1047 if (New->isMSVCRTEntryPoint()) 1048 return false; 1049 1050 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1051 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1052 1053 // C++ [temp.fct]p2: 1054 // A function template can be overloaded with other function templates 1055 // and with normal (non-template) functions. 1056 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1057 return true; 1058 1059 // Is the function New an overload of the function Old? 1060 QualType OldQType = Context.getCanonicalType(Old->getType()); 1061 QualType NewQType = Context.getCanonicalType(New->getType()); 1062 1063 // Compare the signatures (C++ 1.3.10) of the two functions to 1064 // determine whether they are overloads. If we find any mismatch 1065 // in the signature, they are overloads. 1066 1067 // If either of these functions is a K&R-style function (no 1068 // prototype), then we consider them to have matching signatures. 1069 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1070 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1071 return false; 1072 1073 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1074 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1075 1076 // The signature of a function includes the types of its 1077 // parameters (C++ 1.3.10), which includes the presence or absence 1078 // of the ellipsis; see C++ DR 357). 1079 if (OldQType != NewQType && 1080 (OldType->getNumParams() != NewType->getNumParams() || 1081 OldType->isVariadic() != NewType->isVariadic() || 1082 !FunctionParamTypesAreEqual(OldType, NewType))) 1083 return true; 1084 1085 // C++ [temp.over.link]p4: 1086 // The signature of a function template consists of its function 1087 // signature, its return type and its template parameter list. The names 1088 // of the template parameters are significant only for establishing the 1089 // relationship between the template parameters and the rest of the 1090 // signature. 1091 // 1092 // We check the return type and template parameter lists for function 1093 // templates first; the remaining checks follow. 1094 // 1095 // However, we don't consider either of these when deciding whether 1096 // a member introduced by a shadow declaration is hidden. 1097 if (!UseMemberUsingDeclRules && NewTemplate && 1098 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1099 OldTemplate->getTemplateParameters(), 1100 false, TPL_TemplateMatch) || 1101 OldType->getReturnType() != NewType->getReturnType())) 1102 return true; 1103 1104 // If the function is a class member, its signature includes the 1105 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1106 // 1107 // As part of this, also check whether one of the member functions 1108 // is static, in which case they are not overloads (C++ 1109 // 13.1p2). While not part of the definition of the signature, 1110 // this check is important to determine whether these functions 1111 // can be overloaded. 1112 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1113 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1114 if (OldMethod && NewMethod && 1115 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1116 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1117 if (!UseMemberUsingDeclRules && 1118 (OldMethod->getRefQualifier() == RQ_None || 1119 NewMethod->getRefQualifier() == RQ_None)) { 1120 // C++0x [over.load]p2: 1121 // - Member function declarations with the same name and the same 1122 // parameter-type-list as well as member function template 1123 // declarations with the same name, the same parameter-type-list, and 1124 // the same template parameter lists cannot be overloaded if any of 1125 // them, but not all, have a ref-qualifier (8.3.5). 1126 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1127 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1128 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1129 } 1130 return true; 1131 } 1132 1133 // We may not have applied the implicit const for a constexpr member 1134 // function yet (because we haven't yet resolved whether this is a static 1135 // or non-static member function). Add it now, on the assumption that this 1136 // is a redeclaration of OldMethod. 1137 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1138 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1139 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1140 !isa<CXXConstructorDecl>(NewMethod)) 1141 NewQuals |= Qualifiers::Const; 1142 1143 // We do not allow overloading based off of '__restrict'. 1144 OldQuals &= ~Qualifiers::Restrict; 1145 NewQuals &= ~Qualifiers::Restrict; 1146 if (OldQuals != NewQuals) 1147 return true; 1148 } 1149 1150 // Though pass_object_size is placed on parameters and takes an argument, we 1151 // consider it to be a function-level modifier for the sake of function 1152 // identity. Either the function has one or more parameters with 1153 // pass_object_size or it doesn't. 1154 if (functionHasPassObjectSizeParams(New) != 1155 functionHasPassObjectSizeParams(Old)) 1156 return true; 1157 1158 // enable_if attributes are an order-sensitive part of the signature. 1159 for (specific_attr_iterator<EnableIfAttr> 1160 NewI = New->specific_attr_begin<EnableIfAttr>(), 1161 NewE = New->specific_attr_end<EnableIfAttr>(), 1162 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1163 OldE = Old->specific_attr_end<EnableIfAttr>(); 1164 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1165 if (NewI == NewE || OldI == OldE) 1166 return true; 1167 llvm::FoldingSetNodeID NewID, OldID; 1168 NewI->getCond()->Profile(NewID, Context, true); 1169 OldI->getCond()->Profile(OldID, Context, true); 1170 if (NewID != OldID) 1171 return true; 1172 } 1173 1174 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1175 // Don't allow overloading of destructors. (In theory we could, but it 1176 // would be a giant change to clang.) 1177 if (isa<CXXDestructorDecl>(New)) 1178 return false; 1179 1180 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1181 OldTarget = IdentifyCUDATarget(Old); 1182 if (NewTarget == CFT_InvalidTarget) 1183 return false; 1184 1185 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1186 1187 // Allow overloading of functions with same signature and different CUDA 1188 // target attributes. 1189 return NewTarget != OldTarget; 1190 } 1191 1192 // The signatures match; this is not an overload. 1193 return false; 1194 } 1195 1196 /// Checks availability of the function depending on the current 1197 /// function context. Inside an unavailable function, unavailability is ignored. 1198 /// 1199 /// \returns true if \arg FD is unavailable and current context is inside 1200 /// an available function, false otherwise. 1201 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1202 if (!FD->isUnavailable()) 1203 return false; 1204 1205 // Walk up the context of the caller. 1206 Decl *C = cast<Decl>(CurContext); 1207 do { 1208 if (C->isUnavailable()) 1209 return false; 1210 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1211 return true; 1212 } 1213 1214 /// Tries a user-defined conversion from From to ToType. 1215 /// 1216 /// Produces an implicit conversion sequence for when a standard conversion 1217 /// is not an option. See TryImplicitConversion for more information. 1218 static ImplicitConversionSequence 1219 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1220 bool SuppressUserConversions, 1221 bool AllowExplicit, 1222 bool InOverloadResolution, 1223 bool CStyle, 1224 bool AllowObjCWritebackConversion, 1225 bool AllowObjCConversionOnExplicit) { 1226 ImplicitConversionSequence ICS; 1227 1228 if (SuppressUserConversions) { 1229 // We're not in the case above, so there is no conversion that 1230 // we can perform. 1231 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1232 return ICS; 1233 } 1234 1235 // Attempt user-defined conversion. 1236 OverloadCandidateSet Conversions(From->getExprLoc(), 1237 OverloadCandidateSet::CSK_Normal); 1238 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1239 Conversions, AllowExplicit, 1240 AllowObjCConversionOnExplicit)) { 1241 case OR_Success: 1242 case OR_Deleted: 1243 ICS.setUserDefined(); 1244 // C++ [over.ics.user]p4: 1245 // A conversion of an expression of class type to the same class 1246 // type is given Exact Match rank, and a conversion of an 1247 // expression of class type to a base class of that type is 1248 // given Conversion rank, in spite of the fact that a copy 1249 // constructor (i.e., a user-defined conversion function) is 1250 // called for those cases. 1251 if (CXXConstructorDecl *Constructor 1252 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1253 QualType FromCanon 1254 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1255 QualType ToCanon 1256 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1257 if (Constructor->isCopyConstructor() && 1258 (FromCanon == ToCanon || 1259 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1260 // Turn this into a "standard" conversion sequence, so that it 1261 // gets ranked with standard conversion sequences. 1262 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1263 ICS.setStandard(); 1264 ICS.Standard.setAsIdentityConversion(); 1265 ICS.Standard.setFromType(From->getType()); 1266 ICS.Standard.setAllToTypes(ToType); 1267 ICS.Standard.CopyConstructor = Constructor; 1268 ICS.Standard.FoundCopyConstructor = Found; 1269 if (ToCanon != FromCanon) 1270 ICS.Standard.Second = ICK_Derived_To_Base; 1271 } 1272 } 1273 break; 1274 1275 case OR_Ambiguous: 1276 ICS.setAmbiguous(); 1277 ICS.Ambiguous.setFromType(From->getType()); 1278 ICS.Ambiguous.setToType(ToType); 1279 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1280 Cand != Conversions.end(); ++Cand) 1281 if (Cand->Viable) 1282 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1283 break; 1284 1285 // Fall through. 1286 case OR_No_Viable_Function: 1287 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1288 break; 1289 } 1290 1291 return ICS; 1292 } 1293 1294 /// TryImplicitConversion - Attempt to perform an implicit conversion 1295 /// from the given expression (Expr) to the given type (ToType). This 1296 /// function returns an implicit conversion sequence that can be used 1297 /// to perform the initialization. Given 1298 /// 1299 /// void f(float f); 1300 /// void g(int i) { f(i); } 1301 /// 1302 /// this routine would produce an implicit conversion sequence to 1303 /// describe the initialization of f from i, which will be a standard 1304 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1305 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1306 // 1307 /// Note that this routine only determines how the conversion can be 1308 /// performed; it does not actually perform the conversion. As such, 1309 /// it will not produce any diagnostics if no conversion is available, 1310 /// but will instead return an implicit conversion sequence of kind 1311 /// "BadConversion". 1312 /// 1313 /// If @p SuppressUserConversions, then user-defined conversions are 1314 /// not permitted. 1315 /// If @p AllowExplicit, then explicit user-defined conversions are 1316 /// permitted. 1317 /// 1318 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1319 /// writeback conversion, which allows __autoreleasing id* parameters to 1320 /// be initialized with __strong id* or __weak id* arguments. 1321 static ImplicitConversionSequence 1322 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1323 bool SuppressUserConversions, 1324 bool AllowExplicit, 1325 bool InOverloadResolution, 1326 bool CStyle, 1327 bool AllowObjCWritebackConversion, 1328 bool AllowObjCConversionOnExplicit) { 1329 ImplicitConversionSequence ICS; 1330 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1331 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1332 ICS.setStandard(); 1333 return ICS; 1334 } 1335 1336 if (!S.getLangOpts().CPlusPlus) { 1337 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1338 return ICS; 1339 } 1340 1341 // C++ [over.ics.user]p4: 1342 // A conversion of an expression of class type to the same class 1343 // type is given Exact Match rank, and a conversion of an 1344 // expression of class type to a base class of that type is 1345 // given Conversion rank, in spite of the fact that a copy/move 1346 // constructor (i.e., a user-defined conversion function) is 1347 // called for those cases. 1348 QualType FromType = From->getType(); 1349 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1350 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1351 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1352 ICS.setStandard(); 1353 ICS.Standard.setAsIdentityConversion(); 1354 ICS.Standard.setFromType(FromType); 1355 ICS.Standard.setAllToTypes(ToType); 1356 1357 // We don't actually check at this point whether there is a valid 1358 // copy/move constructor, since overloading just assumes that it 1359 // exists. When we actually perform initialization, we'll find the 1360 // appropriate constructor to copy the returned object, if needed. 1361 ICS.Standard.CopyConstructor = nullptr; 1362 1363 // Determine whether this is considered a derived-to-base conversion. 1364 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1365 ICS.Standard.Second = ICK_Derived_To_Base; 1366 1367 return ICS; 1368 } 1369 1370 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1371 AllowExplicit, InOverloadResolution, CStyle, 1372 AllowObjCWritebackConversion, 1373 AllowObjCConversionOnExplicit); 1374 } 1375 1376 ImplicitConversionSequence 1377 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1378 bool SuppressUserConversions, 1379 bool AllowExplicit, 1380 bool InOverloadResolution, 1381 bool CStyle, 1382 bool AllowObjCWritebackConversion) { 1383 return ::TryImplicitConversion(*this, From, ToType, 1384 SuppressUserConversions, AllowExplicit, 1385 InOverloadResolution, CStyle, 1386 AllowObjCWritebackConversion, 1387 /*AllowObjCConversionOnExplicit=*/false); 1388 } 1389 1390 /// PerformImplicitConversion - Perform an implicit conversion of the 1391 /// expression From to the type ToType. Returns the 1392 /// converted expression. Flavor is the kind of conversion we're 1393 /// performing, used in the error message. If @p AllowExplicit, 1394 /// explicit user-defined conversions are permitted. 1395 ExprResult 1396 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1397 AssignmentAction Action, bool AllowExplicit) { 1398 ImplicitConversionSequence ICS; 1399 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1400 } 1401 1402 ExprResult 1403 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1404 AssignmentAction Action, bool AllowExplicit, 1405 ImplicitConversionSequence& ICS) { 1406 if (checkPlaceholderForOverload(*this, From)) 1407 return ExprError(); 1408 1409 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1410 bool AllowObjCWritebackConversion 1411 = getLangOpts().ObjCAutoRefCount && 1412 (Action == AA_Passing || Action == AA_Sending); 1413 if (getLangOpts().ObjC1) 1414 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1415 ToType, From->getType(), From); 1416 ICS = ::TryImplicitConversion(*this, From, ToType, 1417 /*SuppressUserConversions=*/false, 1418 AllowExplicit, 1419 /*InOverloadResolution=*/false, 1420 /*CStyle=*/false, 1421 AllowObjCWritebackConversion, 1422 /*AllowObjCConversionOnExplicit=*/false); 1423 return PerformImplicitConversion(From, ToType, ICS, Action); 1424 } 1425 1426 /// Determine whether the conversion from FromType to ToType is a valid 1427 /// conversion that strips "noexcept" or "noreturn" off the nested function 1428 /// type. 1429 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1430 QualType &ResultTy) { 1431 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1432 return false; 1433 1434 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1435 // or F(t noexcept) -> F(t) 1436 // where F adds one of the following at most once: 1437 // - a pointer 1438 // - a member pointer 1439 // - a block pointer 1440 // Changes here need matching changes in FindCompositePointerType. 1441 CanQualType CanTo = Context.getCanonicalType(ToType); 1442 CanQualType CanFrom = Context.getCanonicalType(FromType); 1443 Type::TypeClass TyClass = CanTo->getTypeClass(); 1444 if (TyClass != CanFrom->getTypeClass()) return false; 1445 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1446 if (TyClass == Type::Pointer) { 1447 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1448 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1449 } else if (TyClass == Type::BlockPointer) { 1450 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1451 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1452 } else if (TyClass == Type::MemberPointer) { 1453 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1454 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1455 // A function pointer conversion cannot change the class of the function. 1456 if (ToMPT->getClass() != FromMPT->getClass()) 1457 return false; 1458 CanTo = ToMPT->getPointeeType(); 1459 CanFrom = FromMPT->getPointeeType(); 1460 } else { 1461 return false; 1462 } 1463 1464 TyClass = CanTo->getTypeClass(); 1465 if (TyClass != CanFrom->getTypeClass()) return false; 1466 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1467 return false; 1468 } 1469 1470 const auto *FromFn = cast<FunctionType>(CanFrom); 1471 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1472 1473 const auto *ToFn = cast<FunctionType>(CanTo); 1474 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1475 1476 bool Changed = false; 1477 1478 // Drop 'noreturn' if not present in target type. 1479 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1480 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1481 Changed = true; 1482 } 1483 1484 // Drop 'noexcept' if not present in target type. 1485 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1486 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1487 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1488 FromFn = cast<FunctionType>( 1489 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1490 EST_None) 1491 .getTypePtr()); 1492 Changed = true; 1493 } 1494 1495 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1496 // only if the ExtParameterInfo lists of the two function prototypes can be 1497 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1498 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1499 bool CanUseToFPT, CanUseFromFPT; 1500 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1501 CanUseFromFPT, NewParamInfos) && 1502 CanUseToFPT && !CanUseFromFPT) { 1503 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1504 ExtInfo.ExtParameterInfos = 1505 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1506 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1507 FromFPT->getParamTypes(), ExtInfo); 1508 FromFn = QT->getAs<FunctionType>(); 1509 Changed = true; 1510 } 1511 } 1512 1513 if (!Changed) 1514 return false; 1515 1516 assert(QualType(FromFn, 0).isCanonical()); 1517 if (QualType(FromFn, 0) != CanTo) return false; 1518 1519 ResultTy = ToType; 1520 return true; 1521 } 1522 1523 /// Determine whether the conversion from FromType to ToType is a valid 1524 /// vector conversion. 1525 /// 1526 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1527 /// conversion. 1528 static bool IsVectorConversion(Sema &S, QualType FromType, 1529 QualType ToType, ImplicitConversionKind &ICK) { 1530 // We need at least one of these types to be a vector type to have a vector 1531 // conversion. 1532 if (!ToType->isVectorType() && !FromType->isVectorType()) 1533 return false; 1534 1535 // Identical types require no conversions. 1536 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1537 return false; 1538 1539 // There are no conversions between extended vector types, only identity. 1540 if (ToType->isExtVectorType()) { 1541 // There are no conversions between extended vector types other than the 1542 // identity conversion. 1543 if (FromType->isExtVectorType()) 1544 return false; 1545 1546 // Vector splat from any arithmetic type to a vector. 1547 if (FromType->isArithmeticType()) { 1548 ICK = ICK_Vector_Splat; 1549 return true; 1550 } 1551 } 1552 1553 // We can perform the conversion between vector types in the following cases: 1554 // 1)vector types are equivalent AltiVec and GCC vector types 1555 // 2)lax vector conversions are permitted and the vector types are of the 1556 // same size 1557 if (ToType->isVectorType() && FromType->isVectorType()) { 1558 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1559 S.isLaxVectorConversion(FromType, ToType)) { 1560 ICK = ICK_Vector_Conversion; 1561 return true; 1562 } 1563 } 1564 1565 return false; 1566 } 1567 1568 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1569 bool InOverloadResolution, 1570 StandardConversionSequence &SCS, 1571 bool CStyle); 1572 1573 /// IsStandardConversion - Determines whether there is a standard 1574 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1575 /// expression From to the type ToType. Standard conversion sequences 1576 /// only consider non-class types; for conversions that involve class 1577 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1578 /// contain the standard conversion sequence required to perform this 1579 /// conversion and this routine will return true. Otherwise, this 1580 /// routine will return false and the value of SCS is unspecified. 1581 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1582 bool InOverloadResolution, 1583 StandardConversionSequence &SCS, 1584 bool CStyle, 1585 bool AllowObjCWritebackConversion) { 1586 QualType FromType = From->getType(); 1587 1588 // Standard conversions (C++ [conv]) 1589 SCS.setAsIdentityConversion(); 1590 SCS.IncompatibleObjC = false; 1591 SCS.setFromType(FromType); 1592 SCS.CopyConstructor = nullptr; 1593 1594 // There are no standard conversions for class types in C++, so 1595 // abort early. When overloading in C, however, we do permit them. 1596 if (S.getLangOpts().CPlusPlus && 1597 (FromType->isRecordType() || ToType->isRecordType())) 1598 return false; 1599 1600 // The first conversion can be an lvalue-to-rvalue conversion, 1601 // array-to-pointer conversion, or function-to-pointer conversion 1602 // (C++ 4p1). 1603 1604 if (FromType == S.Context.OverloadTy) { 1605 DeclAccessPair AccessPair; 1606 if (FunctionDecl *Fn 1607 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1608 AccessPair)) { 1609 // We were able to resolve the address of the overloaded function, 1610 // so we can convert to the type of that function. 1611 FromType = Fn->getType(); 1612 SCS.setFromType(FromType); 1613 1614 // we can sometimes resolve &foo<int> regardless of ToType, so check 1615 // if the type matches (identity) or we are converting to bool 1616 if (!S.Context.hasSameUnqualifiedType( 1617 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1618 QualType resultTy; 1619 // if the function type matches except for [[noreturn]], it's ok 1620 if (!S.IsFunctionConversion(FromType, 1621 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1622 // otherwise, only a boolean conversion is standard 1623 if (!ToType->isBooleanType()) 1624 return false; 1625 } 1626 1627 // Check if the "from" expression is taking the address of an overloaded 1628 // function and recompute the FromType accordingly. Take advantage of the 1629 // fact that non-static member functions *must* have such an address-of 1630 // expression. 1631 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1632 if (Method && !Method->isStatic()) { 1633 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1634 "Non-unary operator on non-static member address"); 1635 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1636 == UO_AddrOf && 1637 "Non-address-of operator on non-static member address"); 1638 const Type *ClassType 1639 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1640 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1641 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1642 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1643 UO_AddrOf && 1644 "Non-address-of operator for overloaded function expression"); 1645 FromType = S.Context.getPointerType(FromType); 1646 } 1647 1648 // Check that we've computed the proper type after overload resolution. 1649 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1650 // be calling it from within an NDEBUG block. 1651 assert(S.Context.hasSameType( 1652 FromType, 1653 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1654 } else { 1655 return false; 1656 } 1657 } 1658 // Lvalue-to-rvalue conversion (C++11 4.1): 1659 // A glvalue (3.10) of a non-function, non-array type T can 1660 // be converted to a prvalue. 1661 bool argIsLValue = From->isGLValue(); 1662 if (argIsLValue && 1663 !FromType->isFunctionType() && !FromType->isArrayType() && 1664 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1665 SCS.First = ICK_Lvalue_To_Rvalue; 1666 1667 // C11 6.3.2.1p2: 1668 // ... if the lvalue has atomic type, the value has the non-atomic version 1669 // of the type of the lvalue ... 1670 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1671 FromType = Atomic->getValueType(); 1672 1673 // If T is a non-class type, the type of the rvalue is the 1674 // cv-unqualified version of T. Otherwise, the type of the rvalue 1675 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1676 // just strip the qualifiers because they don't matter. 1677 FromType = FromType.getUnqualifiedType(); 1678 } else if (FromType->isArrayType()) { 1679 // Array-to-pointer conversion (C++ 4.2) 1680 SCS.First = ICK_Array_To_Pointer; 1681 1682 // An lvalue or rvalue of type "array of N T" or "array of unknown 1683 // bound of T" can be converted to an rvalue of type "pointer to 1684 // T" (C++ 4.2p1). 1685 FromType = S.Context.getArrayDecayedType(FromType); 1686 1687 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1688 // This conversion is deprecated in C++03 (D.4) 1689 SCS.DeprecatedStringLiteralToCharPtr = true; 1690 1691 // For the purpose of ranking in overload resolution 1692 // (13.3.3.1.1), this conversion is considered an 1693 // array-to-pointer conversion followed by a qualification 1694 // conversion (4.4). (C++ 4.2p2) 1695 SCS.Second = ICK_Identity; 1696 SCS.Third = ICK_Qualification; 1697 SCS.QualificationIncludesObjCLifetime = false; 1698 SCS.setAllToTypes(FromType); 1699 return true; 1700 } 1701 } else if (FromType->isFunctionType() && argIsLValue) { 1702 // Function-to-pointer conversion (C++ 4.3). 1703 SCS.First = ICK_Function_To_Pointer; 1704 1705 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1706 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1707 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1708 return false; 1709 1710 // An lvalue of function type T can be converted to an rvalue of 1711 // type "pointer to T." The result is a pointer to the 1712 // function. (C++ 4.3p1). 1713 FromType = S.Context.getPointerType(FromType); 1714 } else { 1715 // We don't require any conversions for the first step. 1716 SCS.First = ICK_Identity; 1717 } 1718 SCS.setToType(0, FromType); 1719 1720 // The second conversion can be an integral promotion, floating 1721 // point promotion, integral conversion, floating point conversion, 1722 // floating-integral conversion, pointer conversion, 1723 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1724 // For overloading in C, this can also be a "compatible-type" 1725 // conversion. 1726 bool IncompatibleObjC = false; 1727 ImplicitConversionKind SecondICK = ICK_Identity; 1728 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1729 // The unqualified versions of the types are the same: there's no 1730 // conversion to do. 1731 SCS.Second = ICK_Identity; 1732 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1733 // Integral promotion (C++ 4.5). 1734 SCS.Second = ICK_Integral_Promotion; 1735 FromType = ToType.getUnqualifiedType(); 1736 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1737 // Floating point promotion (C++ 4.6). 1738 SCS.Second = ICK_Floating_Promotion; 1739 FromType = ToType.getUnqualifiedType(); 1740 } else if (S.IsComplexPromotion(FromType, ToType)) { 1741 // Complex promotion (Clang extension) 1742 SCS.Second = ICK_Complex_Promotion; 1743 FromType = ToType.getUnqualifiedType(); 1744 } else if (ToType->isBooleanType() && 1745 (FromType->isArithmeticType() || 1746 FromType->isAnyPointerType() || 1747 FromType->isBlockPointerType() || 1748 FromType->isMemberPointerType() || 1749 FromType->isNullPtrType())) { 1750 // Boolean conversions (C++ 4.12). 1751 SCS.Second = ICK_Boolean_Conversion; 1752 FromType = S.Context.BoolTy; 1753 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1754 ToType->isIntegralType(S.Context)) { 1755 // Integral conversions (C++ 4.7). 1756 SCS.Second = ICK_Integral_Conversion; 1757 FromType = ToType.getUnqualifiedType(); 1758 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1759 // Complex conversions (C99 6.3.1.6) 1760 SCS.Second = ICK_Complex_Conversion; 1761 FromType = ToType.getUnqualifiedType(); 1762 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1763 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1764 // Complex-real conversions (C99 6.3.1.7) 1765 SCS.Second = ICK_Complex_Real; 1766 FromType = ToType.getUnqualifiedType(); 1767 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1768 // FIXME: disable conversions between long double and __float128 if 1769 // their representation is different until there is back end support 1770 // We of course allow this conversion if long double is really double. 1771 if (&S.Context.getFloatTypeSemantics(FromType) != 1772 &S.Context.getFloatTypeSemantics(ToType)) { 1773 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1774 ToType == S.Context.LongDoubleTy) || 1775 (FromType == S.Context.LongDoubleTy && 1776 ToType == S.Context.Float128Ty)); 1777 if (Float128AndLongDouble && 1778 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1779 &llvm::APFloat::PPCDoubleDouble())) 1780 return false; 1781 } 1782 // Floating point conversions (C++ 4.8). 1783 SCS.Second = ICK_Floating_Conversion; 1784 FromType = ToType.getUnqualifiedType(); 1785 } else if ((FromType->isRealFloatingType() && 1786 ToType->isIntegralType(S.Context)) || 1787 (FromType->isIntegralOrUnscopedEnumerationType() && 1788 ToType->isRealFloatingType())) { 1789 // Floating-integral conversions (C++ 4.9). 1790 SCS.Second = ICK_Floating_Integral; 1791 FromType = ToType.getUnqualifiedType(); 1792 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1793 SCS.Second = ICK_Block_Pointer_Conversion; 1794 } else if (AllowObjCWritebackConversion && 1795 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1796 SCS.Second = ICK_Writeback_Conversion; 1797 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1798 FromType, IncompatibleObjC)) { 1799 // Pointer conversions (C++ 4.10). 1800 SCS.Second = ICK_Pointer_Conversion; 1801 SCS.IncompatibleObjC = IncompatibleObjC; 1802 FromType = FromType.getUnqualifiedType(); 1803 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1804 InOverloadResolution, FromType)) { 1805 // Pointer to member conversions (4.11). 1806 SCS.Second = ICK_Pointer_Member; 1807 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1808 SCS.Second = SecondICK; 1809 FromType = ToType.getUnqualifiedType(); 1810 } else if (!S.getLangOpts().CPlusPlus && 1811 S.Context.typesAreCompatible(ToType, FromType)) { 1812 // Compatible conversions (Clang extension for C function overloading) 1813 SCS.Second = ICK_Compatible_Conversion; 1814 FromType = ToType.getUnqualifiedType(); 1815 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1816 InOverloadResolution, 1817 SCS, CStyle)) { 1818 SCS.Second = ICK_TransparentUnionConversion; 1819 FromType = ToType; 1820 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1821 CStyle)) { 1822 // tryAtomicConversion has updated the standard conversion sequence 1823 // appropriately. 1824 return true; 1825 } else if (ToType->isEventT() && 1826 From->isIntegerConstantExpr(S.getASTContext()) && 1827 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1828 SCS.Second = ICK_Zero_Event_Conversion; 1829 FromType = ToType; 1830 } else if (ToType->isQueueT() && 1831 From->isIntegerConstantExpr(S.getASTContext()) && 1832 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1833 SCS.Second = ICK_Zero_Queue_Conversion; 1834 FromType = ToType; 1835 } else { 1836 // No second conversion required. 1837 SCS.Second = ICK_Identity; 1838 } 1839 SCS.setToType(1, FromType); 1840 1841 // The third conversion can be a function pointer conversion or a 1842 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1843 bool ObjCLifetimeConversion; 1844 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1845 // Function pointer conversions (removing 'noexcept') including removal of 1846 // 'noreturn' (Clang extension). 1847 SCS.Third = ICK_Function_Conversion; 1848 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1849 ObjCLifetimeConversion)) { 1850 SCS.Third = ICK_Qualification; 1851 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1852 FromType = ToType; 1853 } else { 1854 // No conversion required 1855 SCS.Third = ICK_Identity; 1856 } 1857 1858 // C++ [over.best.ics]p6: 1859 // [...] Any difference in top-level cv-qualification is 1860 // subsumed by the initialization itself and does not constitute 1861 // a conversion. [...] 1862 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1863 QualType CanonTo = S.Context.getCanonicalType(ToType); 1864 if (CanonFrom.getLocalUnqualifiedType() 1865 == CanonTo.getLocalUnqualifiedType() && 1866 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1867 FromType = ToType; 1868 CanonFrom = CanonTo; 1869 } 1870 1871 SCS.setToType(2, FromType); 1872 1873 if (CanonFrom == CanonTo) 1874 return true; 1875 1876 // If we have not converted the argument type to the parameter type, 1877 // this is a bad conversion sequence, unless we're resolving an overload in C. 1878 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1879 return false; 1880 1881 ExprResult ER = ExprResult{From}; 1882 Sema::AssignConvertType Conv = 1883 S.CheckSingleAssignmentConstraints(ToType, ER, 1884 /*Diagnose=*/false, 1885 /*DiagnoseCFAudited=*/false, 1886 /*ConvertRHS=*/false); 1887 ImplicitConversionKind SecondConv; 1888 switch (Conv) { 1889 case Sema::Compatible: 1890 SecondConv = ICK_C_Only_Conversion; 1891 break; 1892 // For our purposes, discarding qualifiers is just as bad as using an 1893 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1894 // qualifiers, as well. 1895 case Sema::CompatiblePointerDiscardsQualifiers: 1896 case Sema::IncompatiblePointer: 1897 case Sema::IncompatiblePointerSign: 1898 SecondConv = ICK_Incompatible_Pointer_Conversion; 1899 break; 1900 default: 1901 return false; 1902 } 1903 1904 // First can only be an lvalue conversion, so we pretend that this was the 1905 // second conversion. First should already be valid from earlier in the 1906 // function. 1907 SCS.Second = SecondConv; 1908 SCS.setToType(1, ToType); 1909 1910 // Third is Identity, because Second should rank us worse than any other 1911 // conversion. This could also be ICK_Qualification, but it's simpler to just 1912 // lump everything in with the second conversion, and we don't gain anything 1913 // from making this ICK_Qualification. 1914 SCS.Third = ICK_Identity; 1915 SCS.setToType(2, ToType); 1916 return true; 1917 } 1918 1919 static bool 1920 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1921 QualType &ToType, 1922 bool InOverloadResolution, 1923 StandardConversionSequence &SCS, 1924 bool CStyle) { 1925 1926 const RecordType *UT = ToType->getAsUnionType(); 1927 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1928 return false; 1929 // The field to initialize within the transparent union. 1930 RecordDecl *UD = UT->getDecl(); 1931 // It's compatible if the expression matches any of the fields. 1932 for (const auto *it : UD->fields()) { 1933 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1934 CStyle, /*ObjCWritebackConversion=*/false)) { 1935 ToType = it->getType(); 1936 return true; 1937 } 1938 } 1939 return false; 1940 } 1941 1942 /// IsIntegralPromotion - Determines whether the conversion from the 1943 /// expression From (whose potentially-adjusted type is FromType) to 1944 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1945 /// sets PromotedType to the promoted type. 1946 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1947 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1948 // All integers are built-in. 1949 if (!To) { 1950 return false; 1951 } 1952 1953 // An rvalue of type char, signed char, unsigned char, short int, or 1954 // unsigned short int can be converted to an rvalue of type int if 1955 // int can represent all the values of the source type; otherwise, 1956 // the source rvalue can be converted to an rvalue of type unsigned 1957 // int (C++ 4.5p1). 1958 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1959 !FromType->isEnumeralType()) { 1960 if (// We can promote any signed, promotable integer type to an int 1961 (FromType->isSignedIntegerType() || 1962 // We can promote any unsigned integer type whose size is 1963 // less than int to an int. 1964 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1965 return To->getKind() == BuiltinType::Int; 1966 } 1967 1968 return To->getKind() == BuiltinType::UInt; 1969 } 1970 1971 // C++11 [conv.prom]p3: 1972 // A prvalue of an unscoped enumeration type whose underlying type is not 1973 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1974 // following types that can represent all the values of the enumeration 1975 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1976 // unsigned int, long int, unsigned long int, long long int, or unsigned 1977 // long long int. If none of the types in that list can represent all the 1978 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1979 // type can be converted to an rvalue a prvalue of the extended integer type 1980 // with lowest integer conversion rank (4.13) greater than the rank of long 1981 // long in which all the values of the enumeration can be represented. If 1982 // there are two such extended types, the signed one is chosen. 1983 // C++11 [conv.prom]p4: 1984 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1985 // can be converted to a prvalue of its underlying type. Moreover, if 1986 // integral promotion can be applied to its underlying type, a prvalue of an 1987 // unscoped enumeration type whose underlying type is fixed can also be 1988 // converted to a prvalue of the promoted underlying type. 1989 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1990 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1991 // provided for a scoped enumeration. 1992 if (FromEnumType->getDecl()->isScoped()) 1993 return false; 1994 1995 // We can perform an integral promotion to the underlying type of the enum, 1996 // even if that's not the promoted type. Note that the check for promoting 1997 // the underlying type is based on the type alone, and does not consider 1998 // the bitfield-ness of the actual source expression. 1999 if (FromEnumType->getDecl()->isFixed()) { 2000 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2001 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2002 IsIntegralPromotion(nullptr, Underlying, ToType); 2003 } 2004 2005 // We have already pre-calculated the promotion type, so this is trivial. 2006 if (ToType->isIntegerType() && 2007 isCompleteType(From->getLocStart(), FromType)) 2008 return Context.hasSameUnqualifiedType( 2009 ToType, FromEnumType->getDecl()->getPromotionType()); 2010 } 2011 2012 // C++0x [conv.prom]p2: 2013 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2014 // to an rvalue a prvalue of the first of the following types that can 2015 // represent all the values of its underlying type: int, unsigned int, 2016 // long int, unsigned long int, long long int, or unsigned long long int. 2017 // If none of the types in that list can represent all the values of its 2018 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2019 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2020 // type. 2021 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2022 ToType->isIntegerType()) { 2023 // Determine whether the type we're converting from is signed or 2024 // unsigned. 2025 bool FromIsSigned = FromType->isSignedIntegerType(); 2026 uint64_t FromSize = Context.getTypeSize(FromType); 2027 2028 // The types we'll try to promote to, in the appropriate 2029 // order. Try each of these types. 2030 QualType PromoteTypes[6] = { 2031 Context.IntTy, Context.UnsignedIntTy, 2032 Context.LongTy, Context.UnsignedLongTy , 2033 Context.LongLongTy, Context.UnsignedLongLongTy 2034 }; 2035 for (int Idx = 0; Idx < 6; ++Idx) { 2036 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2037 if (FromSize < ToSize || 2038 (FromSize == ToSize && 2039 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2040 // We found the type that we can promote to. If this is the 2041 // type we wanted, we have a promotion. Otherwise, no 2042 // promotion. 2043 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2044 } 2045 } 2046 } 2047 2048 // An rvalue for an integral bit-field (9.6) can be converted to an 2049 // rvalue of type int if int can represent all the values of the 2050 // bit-field; otherwise, it can be converted to unsigned int if 2051 // unsigned int can represent all the values of the bit-field. If 2052 // the bit-field is larger yet, no integral promotion applies to 2053 // it. If the bit-field has an enumerated type, it is treated as any 2054 // other value of that type for promotion purposes (C++ 4.5p3). 2055 // FIXME: We should delay checking of bit-fields until we actually perform the 2056 // conversion. 2057 if (From) { 2058 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2059 llvm::APSInt BitWidth; 2060 if (FromType->isIntegralType(Context) && 2061 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2062 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2063 ToSize = Context.getTypeSize(ToType); 2064 2065 // Are we promoting to an int from a bitfield that fits in an int? 2066 if (BitWidth < ToSize || 2067 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2068 return To->getKind() == BuiltinType::Int; 2069 } 2070 2071 // Are we promoting to an unsigned int from an unsigned bitfield 2072 // that fits into an unsigned int? 2073 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2074 return To->getKind() == BuiltinType::UInt; 2075 } 2076 2077 return false; 2078 } 2079 } 2080 } 2081 2082 // An rvalue of type bool can be converted to an rvalue of type int, 2083 // with false becoming zero and true becoming one (C++ 4.5p4). 2084 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2085 return true; 2086 } 2087 2088 return false; 2089 } 2090 2091 /// IsFloatingPointPromotion - Determines whether the conversion from 2092 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2093 /// returns true and sets PromotedType to the promoted type. 2094 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2095 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2096 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2097 /// An rvalue of type float can be converted to an rvalue of type 2098 /// double. (C++ 4.6p1). 2099 if (FromBuiltin->getKind() == BuiltinType::Float && 2100 ToBuiltin->getKind() == BuiltinType::Double) 2101 return true; 2102 2103 // C99 6.3.1.5p1: 2104 // When a float is promoted to double or long double, or a 2105 // double is promoted to long double [...]. 2106 if (!getLangOpts().CPlusPlus && 2107 (FromBuiltin->getKind() == BuiltinType::Float || 2108 FromBuiltin->getKind() == BuiltinType::Double) && 2109 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2110 ToBuiltin->getKind() == BuiltinType::Float128)) 2111 return true; 2112 2113 // Half can be promoted to float. 2114 if (!getLangOpts().NativeHalfType && 2115 FromBuiltin->getKind() == BuiltinType::Half && 2116 ToBuiltin->getKind() == BuiltinType::Float) 2117 return true; 2118 } 2119 2120 return false; 2121 } 2122 2123 /// Determine if a conversion is a complex promotion. 2124 /// 2125 /// A complex promotion is defined as a complex -> complex conversion 2126 /// where the conversion between the underlying real types is a 2127 /// floating-point or integral promotion. 2128 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2129 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2130 if (!FromComplex) 2131 return false; 2132 2133 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2134 if (!ToComplex) 2135 return false; 2136 2137 return IsFloatingPointPromotion(FromComplex->getElementType(), 2138 ToComplex->getElementType()) || 2139 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2140 ToComplex->getElementType()); 2141 } 2142 2143 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2144 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2145 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2146 /// if non-empty, will be a pointer to ToType that may or may not have 2147 /// the right set of qualifiers on its pointee. 2148 /// 2149 static QualType 2150 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2151 QualType ToPointee, QualType ToType, 2152 ASTContext &Context, 2153 bool StripObjCLifetime = false) { 2154 assert((FromPtr->getTypeClass() == Type::Pointer || 2155 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2156 "Invalid similarly-qualified pointer type"); 2157 2158 /// Conversions to 'id' subsume cv-qualifier conversions. 2159 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2160 return ToType.getUnqualifiedType(); 2161 2162 QualType CanonFromPointee 2163 = Context.getCanonicalType(FromPtr->getPointeeType()); 2164 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2165 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2166 2167 if (StripObjCLifetime) 2168 Quals.removeObjCLifetime(); 2169 2170 // Exact qualifier match -> return the pointer type we're converting to. 2171 if (CanonToPointee.getLocalQualifiers() == Quals) { 2172 // ToType is exactly what we need. Return it. 2173 if (!ToType.isNull()) 2174 return ToType.getUnqualifiedType(); 2175 2176 // Build a pointer to ToPointee. It has the right qualifiers 2177 // already. 2178 if (isa<ObjCObjectPointerType>(ToType)) 2179 return Context.getObjCObjectPointerType(ToPointee); 2180 return Context.getPointerType(ToPointee); 2181 } 2182 2183 // Just build a canonical type that has the right qualifiers. 2184 QualType QualifiedCanonToPointee 2185 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2186 2187 if (isa<ObjCObjectPointerType>(ToType)) 2188 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2189 return Context.getPointerType(QualifiedCanonToPointee); 2190 } 2191 2192 static bool isNullPointerConstantForConversion(Expr *Expr, 2193 bool InOverloadResolution, 2194 ASTContext &Context) { 2195 // Handle value-dependent integral null pointer constants correctly. 2196 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2197 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2198 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2199 return !InOverloadResolution; 2200 2201 return Expr->isNullPointerConstant(Context, 2202 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2203 : Expr::NPC_ValueDependentIsNull); 2204 } 2205 2206 /// IsPointerConversion - Determines whether the conversion of the 2207 /// expression From, which has the (possibly adjusted) type FromType, 2208 /// can be converted to the type ToType via a pointer conversion (C++ 2209 /// 4.10). If so, returns true and places the converted type (that 2210 /// might differ from ToType in its cv-qualifiers at some level) into 2211 /// ConvertedType. 2212 /// 2213 /// This routine also supports conversions to and from block pointers 2214 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2215 /// pointers to interfaces. FIXME: Once we've determined the 2216 /// appropriate overloading rules for Objective-C, we may want to 2217 /// split the Objective-C checks into a different routine; however, 2218 /// GCC seems to consider all of these conversions to be pointer 2219 /// conversions, so for now they live here. IncompatibleObjC will be 2220 /// set if the conversion is an allowed Objective-C conversion that 2221 /// should result in a warning. 2222 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2223 bool InOverloadResolution, 2224 QualType& ConvertedType, 2225 bool &IncompatibleObjC) { 2226 IncompatibleObjC = false; 2227 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2228 IncompatibleObjC)) 2229 return true; 2230 2231 // Conversion from a null pointer constant to any Objective-C pointer type. 2232 if (ToType->isObjCObjectPointerType() && 2233 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2234 ConvertedType = ToType; 2235 return true; 2236 } 2237 2238 // Blocks: Block pointers can be converted to void*. 2239 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2240 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2241 ConvertedType = ToType; 2242 return true; 2243 } 2244 // Blocks: A null pointer constant can be converted to a block 2245 // pointer type. 2246 if (ToType->isBlockPointerType() && 2247 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2248 ConvertedType = ToType; 2249 return true; 2250 } 2251 2252 // If the left-hand-side is nullptr_t, the right side can be a null 2253 // pointer constant. 2254 if (ToType->isNullPtrType() && 2255 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2256 ConvertedType = ToType; 2257 return true; 2258 } 2259 2260 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2261 if (!ToTypePtr) 2262 return false; 2263 2264 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2265 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2266 ConvertedType = ToType; 2267 return true; 2268 } 2269 2270 // Beyond this point, both types need to be pointers 2271 // , including objective-c pointers. 2272 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2273 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2274 !getLangOpts().ObjCAutoRefCount) { 2275 ConvertedType = BuildSimilarlyQualifiedPointerType( 2276 FromType->getAs<ObjCObjectPointerType>(), 2277 ToPointeeType, 2278 ToType, Context); 2279 return true; 2280 } 2281 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2282 if (!FromTypePtr) 2283 return false; 2284 2285 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2286 2287 // If the unqualified pointee types are the same, this can't be a 2288 // pointer conversion, so don't do all of the work below. 2289 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2290 return false; 2291 2292 // An rvalue of type "pointer to cv T," where T is an object type, 2293 // can be converted to an rvalue of type "pointer to cv void" (C++ 2294 // 4.10p2). 2295 if (FromPointeeType->isIncompleteOrObjectType() && 2296 ToPointeeType->isVoidType()) { 2297 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2298 ToPointeeType, 2299 ToType, Context, 2300 /*StripObjCLifetime=*/true); 2301 return true; 2302 } 2303 2304 // MSVC allows implicit function to void* type conversion. 2305 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2306 ToPointeeType->isVoidType()) { 2307 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2308 ToPointeeType, 2309 ToType, Context); 2310 return true; 2311 } 2312 2313 // When we're overloading in C, we allow a special kind of pointer 2314 // conversion for compatible-but-not-identical pointee types. 2315 if (!getLangOpts().CPlusPlus && 2316 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2317 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2318 ToPointeeType, 2319 ToType, Context); 2320 return true; 2321 } 2322 2323 // C++ [conv.ptr]p3: 2324 // 2325 // An rvalue of type "pointer to cv D," where D is a class type, 2326 // can be converted to an rvalue of type "pointer to cv B," where 2327 // B is a base class (clause 10) of D. If B is an inaccessible 2328 // (clause 11) or ambiguous (10.2) base class of D, a program that 2329 // necessitates this conversion is ill-formed. The result of the 2330 // conversion is a pointer to the base class sub-object of the 2331 // derived class object. The null pointer value is converted to 2332 // the null pointer value of the destination type. 2333 // 2334 // Note that we do not check for ambiguity or inaccessibility 2335 // here. That is handled by CheckPointerConversion. 2336 if (getLangOpts().CPlusPlus && 2337 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2338 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2339 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2340 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2341 ToPointeeType, 2342 ToType, Context); 2343 return true; 2344 } 2345 2346 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2347 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2348 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2349 ToPointeeType, 2350 ToType, Context); 2351 return true; 2352 } 2353 2354 return false; 2355 } 2356 2357 /// Adopt the given qualifiers for the given type. 2358 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2359 Qualifiers TQs = T.getQualifiers(); 2360 2361 // Check whether qualifiers already match. 2362 if (TQs == Qs) 2363 return T; 2364 2365 if (Qs.compatiblyIncludes(TQs)) 2366 return Context.getQualifiedType(T, Qs); 2367 2368 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2369 } 2370 2371 /// isObjCPointerConversion - Determines whether this is an 2372 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2373 /// with the same arguments and return values. 2374 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2375 QualType& ConvertedType, 2376 bool &IncompatibleObjC) { 2377 if (!getLangOpts().ObjC1) 2378 return false; 2379 2380 // The set of qualifiers on the type we're converting from. 2381 Qualifiers FromQualifiers = FromType.getQualifiers(); 2382 2383 // First, we handle all conversions on ObjC object pointer types. 2384 const ObjCObjectPointerType* ToObjCPtr = 2385 ToType->getAs<ObjCObjectPointerType>(); 2386 const ObjCObjectPointerType *FromObjCPtr = 2387 FromType->getAs<ObjCObjectPointerType>(); 2388 2389 if (ToObjCPtr && FromObjCPtr) { 2390 // If the pointee types are the same (ignoring qualifications), 2391 // then this is not a pointer conversion. 2392 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2393 FromObjCPtr->getPointeeType())) 2394 return false; 2395 2396 // Conversion between Objective-C pointers. 2397 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2398 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2399 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2400 if (getLangOpts().CPlusPlus && LHS && RHS && 2401 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2402 FromObjCPtr->getPointeeType())) 2403 return false; 2404 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2405 ToObjCPtr->getPointeeType(), 2406 ToType, Context); 2407 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2408 return true; 2409 } 2410 2411 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2412 // Okay: this is some kind of implicit downcast of Objective-C 2413 // interfaces, which is permitted. However, we're going to 2414 // complain about it. 2415 IncompatibleObjC = true; 2416 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2417 ToObjCPtr->getPointeeType(), 2418 ToType, Context); 2419 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2420 return true; 2421 } 2422 } 2423 // Beyond this point, both types need to be C pointers or block pointers. 2424 QualType ToPointeeType; 2425 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2426 ToPointeeType = ToCPtr->getPointeeType(); 2427 else if (const BlockPointerType *ToBlockPtr = 2428 ToType->getAs<BlockPointerType>()) { 2429 // Objective C++: We're able to convert from a pointer to any object 2430 // to a block pointer type. 2431 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2432 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2433 return true; 2434 } 2435 ToPointeeType = ToBlockPtr->getPointeeType(); 2436 } 2437 else if (FromType->getAs<BlockPointerType>() && 2438 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2439 // Objective C++: We're able to convert from a block pointer type to a 2440 // pointer to any object. 2441 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2442 return true; 2443 } 2444 else 2445 return false; 2446 2447 QualType FromPointeeType; 2448 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2449 FromPointeeType = FromCPtr->getPointeeType(); 2450 else if (const BlockPointerType *FromBlockPtr = 2451 FromType->getAs<BlockPointerType>()) 2452 FromPointeeType = FromBlockPtr->getPointeeType(); 2453 else 2454 return false; 2455 2456 // If we have pointers to pointers, recursively check whether this 2457 // is an Objective-C conversion. 2458 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2459 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2460 IncompatibleObjC)) { 2461 // We always complain about this conversion. 2462 IncompatibleObjC = true; 2463 ConvertedType = Context.getPointerType(ConvertedType); 2464 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2465 return true; 2466 } 2467 // Allow conversion of pointee being objective-c pointer to another one; 2468 // as in I* to id. 2469 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2470 ToPointeeType->getAs<ObjCObjectPointerType>() && 2471 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2472 IncompatibleObjC)) { 2473 2474 ConvertedType = Context.getPointerType(ConvertedType); 2475 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2476 return true; 2477 } 2478 2479 // If we have pointers to functions or blocks, check whether the only 2480 // differences in the argument and result types are in Objective-C 2481 // pointer conversions. If so, we permit the conversion (but 2482 // complain about it). 2483 const FunctionProtoType *FromFunctionType 2484 = FromPointeeType->getAs<FunctionProtoType>(); 2485 const FunctionProtoType *ToFunctionType 2486 = ToPointeeType->getAs<FunctionProtoType>(); 2487 if (FromFunctionType && ToFunctionType) { 2488 // If the function types are exactly the same, this isn't an 2489 // Objective-C pointer conversion. 2490 if (Context.getCanonicalType(FromPointeeType) 2491 == Context.getCanonicalType(ToPointeeType)) 2492 return false; 2493 2494 // Perform the quick checks that will tell us whether these 2495 // function types are obviously different. 2496 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2497 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2498 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2499 return false; 2500 2501 bool HasObjCConversion = false; 2502 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2503 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2504 // Okay, the types match exactly. Nothing to do. 2505 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2506 ToFunctionType->getReturnType(), 2507 ConvertedType, IncompatibleObjC)) { 2508 // Okay, we have an Objective-C pointer conversion. 2509 HasObjCConversion = true; 2510 } else { 2511 // Function types are too different. Abort. 2512 return false; 2513 } 2514 2515 // Check argument types. 2516 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2517 ArgIdx != NumArgs; ++ArgIdx) { 2518 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2519 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2520 if (Context.getCanonicalType(FromArgType) 2521 == Context.getCanonicalType(ToArgType)) { 2522 // Okay, the types match exactly. Nothing to do. 2523 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2524 ConvertedType, IncompatibleObjC)) { 2525 // Okay, we have an Objective-C pointer conversion. 2526 HasObjCConversion = true; 2527 } else { 2528 // Argument types are too different. Abort. 2529 return false; 2530 } 2531 } 2532 2533 if (HasObjCConversion) { 2534 // We had an Objective-C conversion. Allow this pointer 2535 // conversion, but complain about it. 2536 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2537 IncompatibleObjC = true; 2538 return true; 2539 } 2540 } 2541 2542 return false; 2543 } 2544 2545 /// Determine whether this is an Objective-C writeback conversion, 2546 /// used for parameter passing when performing automatic reference counting. 2547 /// 2548 /// \param FromType The type we're converting form. 2549 /// 2550 /// \param ToType The type we're converting to. 2551 /// 2552 /// \param ConvertedType The type that will be produced after applying 2553 /// this conversion. 2554 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2555 QualType &ConvertedType) { 2556 if (!getLangOpts().ObjCAutoRefCount || 2557 Context.hasSameUnqualifiedType(FromType, ToType)) 2558 return false; 2559 2560 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2561 QualType ToPointee; 2562 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2563 ToPointee = ToPointer->getPointeeType(); 2564 else 2565 return false; 2566 2567 Qualifiers ToQuals = ToPointee.getQualifiers(); 2568 if (!ToPointee->isObjCLifetimeType() || 2569 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2570 !ToQuals.withoutObjCLifetime().empty()) 2571 return false; 2572 2573 // Argument must be a pointer to __strong to __weak. 2574 QualType FromPointee; 2575 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2576 FromPointee = FromPointer->getPointeeType(); 2577 else 2578 return false; 2579 2580 Qualifiers FromQuals = FromPointee.getQualifiers(); 2581 if (!FromPointee->isObjCLifetimeType() || 2582 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2583 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2584 return false; 2585 2586 // Make sure that we have compatible qualifiers. 2587 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2588 if (!ToQuals.compatiblyIncludes(FromQuals)) 2589 return false; 2590 2591 // Remove qualifiers from the pointee type we're converting from; they 2592 // aren't used in the compatibility check belong, and we'll be adding back 2593 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2594 FromPointee = FromPointee.getUnqualifiedType(); 2595 2596 // The unqualified form of the pointee types must be compatible. 2597 ToPointee = ToPointee.getUnqualifiedType(); 2598 bool IncompatibleObjC; 2599 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2600 FromPointee = ToPointee; 2601 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2602 IncompatibleObjC)) 2603 return false; 2604 2605 /// Construct the type we're converting to, which is a pointer to 2606 /// __autoreleasing pointee. 2607 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2608 ConvertedType = Context.getPointerType(FromPointee); 2609 return true; 2610 } 2611 2612 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2613 QualType& ConvertedType) { 2614 QualType ToPointeeType; 2615 if (const BlockPointerType *ToBlockPtr = 2616 ToType->getAs<BlockPointerType>()) 2617 ToPointeeType = ToBlockPtr->getPointeeType(); 2618 else 2619 return false; 2620 2621 QualType FromPointeeType; 2622 if (const BlockPointerType *FromBlockPtr = 2623 FromType->getAs<BlockPointerType>()) 2624 FromPointeeType = FromBlockPtr->getPointeeType(); 2625 else 2626 return false; 2627 // We have pointer to blocks, check whether the only 2628 // differences in the argument and result types are in Objective-C 2629 // pointer conversions. If so, we permit the conversion. 2630 2631 const FunctionProtoType *FromFunctionType 2632 = FromPointeeType->getAs<FunctionProtoType>(); 2633 const FunctionProtoType *ToFunctionType 2634 = ToPointeeType->getAs<FunctionProtoType>(); 2635 2636 if (!FromFunctionType || !ToFunctionType) 2637 return false; 2638 2639 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2640 return true; 2641 2642 // Perform the quick checks that will tell us whether these 2643 // function types are obviously different. 2644 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2645 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2646 return false; 2647 2648 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2649 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2650 if (FromEInfo != ToEInfo) 2651 return false; 2652 2653 bool IncompatibleObjC = false; 2654 if (Context.hasSameType(FromFunctionType->getReturnType(), 2655 ToFunctionType->getReturnType())) { 2656 // Okay, the types match exactly. Nothing to do. 2657 } else { 2658 QualType RHS = FromFunctionType->getReturnType(); 2659 QualType LHS = ToFunctionType->getReturnType(); 2660 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2661 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2662 LHS = LHS.getUnqualifiedType(); 2663 2664 if (Context.hasSameType(RHS,LHS)) { 2665 // OK exact match. 2666 } else if (isObjCPointerConversion(RHS, LHS, 2667 ConvertedType, IncompatibleObjC)) { 2668 if (IncompatibleObjC) 2669 return false; 2670 // Okay, we have an Objective-C pointer conversion. 2671 } 2672 else 2673 return false; 2674 } 2675 2676 // Check argument types. 2677 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2678 ArgIdx != NumArgs; ++ArgIdx) { 2679 IncompatibleObjC = false; 2680 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2681 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2682 if (Context.hasSameType(FromArgType, ToArgType)) { 2683 // Okay, the types match exactly. Nothing to do. 2684 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2685 ConvertedType, IncompatibleObjC)) { 2686 if (IncompatibleObjC) 2687 return false; 2688 // Okay, we have an Objective-C pointer conversion. 2689 } else 2690 // Argument types are too different. Abort. 2691 return false; 2692 } 2693 2694 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2695 bool CanUseToFPT, CanUseFromFPT; 2696 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2697 CanUseToFPT, CanUseFromFPT, 2698 NewParamInfos)) 2699 return false; 2700 2701 ConvertedType = ToType; 2702 return true; 2703 } 2704 2705 enum { 2706 ft_default, 2707 ft_different_class, 2708 ft_parameter_arity, 2709 ft_parameter_mismatch, 2710 ft_return_type, 2711 ft_qualifer_mismatch, 2712 ft_noexcept 2713 }; 2714 2715 /// Attempts to get the FunctionProtoType from a Type. Handles 2716 /// MemberFunctionPointers properly. 2717 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2718 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2719 return FPT; 2720 2721 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2722 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2723 2724 return nullptr; 2725 } 2726 2727 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2728 /// function types. Catches different number of parameter, mismatch in 2729 /// parameter types, and different return types. 2730 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2731 QualType FromType, QualType ToType) { 2732 // If either type is not valid, include no extra info. 2733 if (FromType.isNull() || ToType.isNull()) { 2734 PDiag << ft_default; 2735 return; 2736 } 2737 2738 // Get the function type from the pointers. 2739 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2740 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2741 *ToMember = ToType->getAs<MemberPointerType>(); 2742 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2743 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2744 << QualType(FromMember->getClass(), 0); 2745 return; 2746 } 2747 FromType = FromMember->getPointeeType(); 2748 ToType = ToMember->getPointeeType(); 2749 } 2750 2751 if (FromType->isPointerType()) 2752 FromType = FromType->getPointeeType(); 2753 if (ToType->isPointerType()) 2754 ToType = ToType->getPointeeType(); 2755 2756 // Remove references. 2757 FromType = FromType.getNonReferenceType(); 2758 ToType = ToType.getNonReferenceType(); 2759 2760 // Don't print extra info for non-specialized template functions. 2761 if (FromType->isInstantiationDependentType() && 2762 !FromType->getAs<TemplateSpecializationType>()) { 2763 PDiag << ft_default; 2764 return; 2765 } 2766 2767 // No extra info for same types. 2768 if (Context.hasSameType(FromType, ToType)) { 2769 PDiag << ft_default; 2770 return; 2771 } 2772 2773 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2774 *ToFunction = tryGetFunctionProtoType(ToType); 2775 2776 // Both types need to be function types. 2777 if (!FromFunction || !ToFunction) { 2778 PDiag << ft_default; 2779 return; 2780 } 2781 2782 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2783 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2784 << FromFunction->getNumParams(); 2785 return; 2786 } 2787 2788 // Handle different parameter types. 2789 unsigned ArgPos; 2790 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2791 PDiag << ft_parameter_mismatch << ArgPos + 1 2792 << ToFunction->getParamType(ArgPos) 2793 << FromFunction->getParamType(ArgPos); 2794 return; 2795 } 2796 2797 // Handle different return type. 2798 if (!Context.hasSameType(FromFunction->getReturnType(), 2799 ToFunction->getReturnType())) { 2800 PDiag << ft_return_type << ToFunction->getReturnType() 2801 << FromFunction->getReturnType(); 2802 return; 2803 } 2804 2805 unsigned FromQuals = FromFunction->getTypeQuals(), 2806 ToQuals = ToFunction->getTypeQuals(); 2807 if (FromQuals != ToQuals) { 2808 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2809 return; 2810 } 2811 2812 // Handle exception specification differences on canonical type (in C++17 2813 // onwards). 2814 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2815 ->isNothrow() != 2816 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2817 ->isNothrow()) { 2818 PDiag << ft_noexcept; 2819 return; 2820 } 2821 2822 // Unable to find a difference, so add no extra info. 2823 PDiag << ft_default; 2824 } 2825 2826 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2827 /// for equality of their argument types. Caller has already checked that 2828 /// they have same number of arguments. If the parameters are different, 2829 /// ArgPos will have the parameter index of the first different parameter. 2830 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2831 const FunctionProtoType *NewType, 2832 unsigned *ArgPos) { 2833 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2834 N = NewType->param_type_begin(), 2835 E = OldType->param_type_end(); 2836 O && (O != E); ++O, ++N) { 2837 if (!Context.hasSameType(O->getUnqualifiedType(), 2838 N->getUnqualifiedType())) { 2839 if (ArgPos) 2840 *ArgPos = O - OldType->param_type_begin(); 2841 return false; 2842 } 2843 } 2844 return true; 2845 } 2846 2847 /// CheckPointerConversion - Check the pointer conversion from the 2848 /// expression From to the type ToType. This routine checks for 2849 /// ambiguous or inaccessible derived-to-base pointer 2850 /// conversions for which IsPointerConversion has already returned 2851 /// true. It returns true and produces a diagnostic if there was an 2852 /// error, or returns false otherwise. 2853 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2854 CastKind &Kind, 2855 CXXCastPath& BasePath, 2856 bool IgnoreBaseAccess, 2857 bool Diagnose) { 2858 QualType FromType = From->getType(); 2859 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2860 2861 Kind = CK_BitCast; 2862 2863 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2864 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2865 Expr::NPCK_ZeroExpression) { 2866 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2867 DiagRuntimeBehavior(From->getExprLoc(), From, 2868 PDiag(diag::warn_impcast_bool_to_null_pointer) 2869 << ToType << From->getSourceRange()); 2870 else if (!isUnevaluatedContext()) 2871 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2872 << ToType << From->getSourceRange(); 2873 } 2874 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2875 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2876 QualType FromPointeeType = FromPtrType->getPointeeType(), 2877 ToPointeeType = ToPtrType->getPointeeType(); 2878 2879 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2880 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2881 // We must have a derived-to-base conversion. Check an 2882 // ambiguous or inaccessible conversion. 2883 unsigned InaccessibleID = 0; 2884 unsigned AmbigiousID = 0; 2885 if (Diagnose) { 2886 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2887 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2888 } 2889 if (CheckDerivedToBaseConversion( 2890 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2891 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2892 &BasePath, IgnoreBaseAccess)) 2893 return true; 2894 2895 // The conversion was successful. 2896 Kind = CK_DerivedToBase; 2897 } 2898 2899 if (Diagnose && !IsCStyleOrFunctionalCast && 2900 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2901 assert(getLangOpts().MSVCCompat && 2902 "this should only be possible with MSVCCompat!"); 2903 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2904 << From->getSourceRange(); 2905 } 2906 } 2907 } else if (const ObjCObjectPointerType *ToPtrType = 2908 ToType->getAs<ObjCObjectPointerType>()) { 2909 if (const ObjCObjectPointerType *FromPtrType = 2910 FromType->getAs<ObjCObjectPointerType>()) { 2911 // Objective-C++ conversions are always okay. 2912 // FIXME: We should have a different class of conversions for the 2913 // Objective-C++ implicit conversions. 2914 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2915 return false; 2916 } else if (FromType->isBlockPointerType()) { 2917 Kind = CK_BlockPointerToObjCPointerCast; 2918 } else { 2919 Kind = CK_CPointerToObjCPointerCast; 2920 } 2921 } else if (ToType->isBlockPointerType()) { 2922 if (!FromType->isBlockPointerType()) 2923 Kind = CK_AnyPointerToBlockPointerCast; 2924 } 2925 2926 // We shouldn't fall into this case unless it's valid for other 2927 // reasons. 2928 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2929 Kind = CK_NullToPointer; 2930 2931 return false; 2932 } 2933 2934 /// IsMemberPointerConversion - Determines whether the conversion of the 2935 /// expression From, which has the (possibly adjusted) type FromType, can be 2936 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2937 /// If so, returns true and places the converted type (that might differ from 2938 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2939 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2940 QualType ToType, 2941 bool InOverloadResolution, 2942 QualType &ConvertedType) { 2943 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2944 if (!ToTypePtr) 2945 return false; 2946 2947 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2948 if (From->isNullPointerConstant(Context, 2949 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2950 : Expr::NPC_ValueDependentIsNull)) { 2951 ConvertedType = ToType; 2952 return true; 2953 } 2954 2955 // Otherwise, both types have to be member pointers. 2956 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2957 if (!FromTypePtr) 2958 return false; 2959 2960 // A pointer to member of B can be converted to a pointer to member of D, 2961 // where D is derived from B (C++ 4.11p2). 2962 QualType FromClass(FromTypePtr->getClass(), 0); 2963 QualType ToClass(ToTypePtr->getClass(), 0); 2964 2965 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2966 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2967 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2968 ToClass.getTypePtr()); 2969 return true; 2970 } 2971 2972 return false; 2973 } 2974 2975 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2976 /// expression From to the type ToType. This routine checks for ambiguous or 2977 /// virtual or inaccessible base-to-derived member pointer conversions 2978 /// for which IsMemberPointerConversion has already returned true. It returns 2979 /// true and produces a diagnostic if there was an error, or returns false 2980 /// otherwise. 2981 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2982 CastKind &Kind, 2983 CXXCastPath &BasePath, 2984 bool IgnoreBaseAccess) { 2985 QualType FromType = From->getType(); 2986 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2987 if (!FromPtrType) { 2988 // This must be a null pointer to member pointer conversion 2989 assert(From->isNullPointerConstant(Context, 2990 Expr::NPC_ValueDependentIsNull) && 2991 "Expr must be null pointer constant!"); 2992 Kind = CK_NullToMemberPointer; 2993 return false; 2994 } 2995 2996 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2997 assert(ToPtrType && "No member pointer cast has a target type " 2998 "that is not a member pointer."); 2999 3000 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3001 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3002 3003 // FIXME: What about dependent types? 3004 assert(FromClass->isRecordType() && "Pointer into non-class."); 3005 assert(ToClass->isRecordType() && "Pointer into non-class."); 3006 3007 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3008 /*DetectVirtual=*/true); 3009 bool DerivationOkay = 3010 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 3011 assert(DerivationOkay && 3012 "Should not have been called if derivation isn't OK."); 3013 (void)DerivationOkay; 3014 3015 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3016 getUnqualifiedType())) { 3017 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3018 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3019 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3020 return true; 3021 } 3022 3023 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3024 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3025 << FromClass << ToClass << QualType(VBase, 0) 3026 << From->getSourceRange(); 3027 return true; 3028 } 3029 3030 if (!IgnoreBaseAccess) 3031 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3032 Paths.front(), 3033 diag::err_downcast_from_inaccessible_base); 3034 3035 // Must be a base to derived member conversion. 3036 BuildBasePathArray(Paths, BasePath); 3037 Kind = CK_BaseToDerivedMemberPointer; 3038 return false; 3039 } 3040 3041 /// Determine whether the lifetime conversion between the two given 3042 /// qualifiers sets is nontrivial. 3043 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3044 Qualifiers ToQuals) { 3045 // Converting anything to const __unsafe_unretained is trivial. 3046 if (ToQuals.hasConst() && 3047 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3048 return false; 3049 3050 return true; 3051 } 3052 3053 /// IsQualificationConversion - Determines whether the conversion from 3054 /// an rvalue of type FromType to ToType is a qualification conversion 3055 /// (C++ 4.4). 3056 /// 3057 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3058 /// when the qualification conversion involves a change in the Objective-C 3059 /// object lifetime. 3060 bool 3061 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3062 bool CStyle, bool &ObjCLifetimeConversion) { 3063 FromType = Context.getCanonicalType(FromType); 3064 ToType = Context.getCanonicalType(ToType); 3065 ObjCLifetimeConversion = false; 3066 3067 // If FromType and ToType are the same type, this is not a 3068 // qualification conversion. 3069 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3070 return false; 3071 3072 // (C++ 4.4p4): 3073 // A conversion can add cv-qualifiers at levels other than the first 3074 // in multi-level pointers, subject to the following rules: [...] 3075 bool PreviousToQualsIncludeConst = true; 3076 bool UnwrappedAnyPointer = false; 3077 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3078 // Within each iteration of the loop, we check the qualifiers to 3079 // determine if this still looks like a qualification 3080 // conversion. Then, if all is well, we unwrap one more level of 3081 // pointers or pointers-to-members and do it all again 3082 // until there are no more pointers or pointers-to-members left to 3083 // unwrap. 3084 UnwrappedAnyPointer = true; 3085 3086 Qualifiers FromQuals = FromType.getQualifiers(); 3087 Qualifiers ToQuals = ToType.getQualifiers(); 3088 3089 // Ignore __unaligned qualifier if this type is void. 3090 if (ToType.getUnqualifiedType()->isVoidType()) 3091 FromQuals.removeUnaligned(); 3092 3093 // Objective-C ARC: 3094 // Check Objective-C lifetime conversions. 3095 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3096 UnwrappedAnyPointer) { 3097 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3098 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3099 ObjCLifetimeConversion = true; 3100 FromQuals.removeObjCLifetime(); 3101 ToQuals.removeObjCLifetime(); 3102 } else { 3103 // Qualification conversions cannot cast between different 3104 // Objective-C lifetime qualifiers. 3105 return false; 3106 } 3107 } 3108 3109 // Allow addition/removal of GC attributes but not changing GC attributes. 3110 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3111 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3112 FromQuals.removeObjCGCAttr(); 3113 ToQuals.removeObjCGCAttr(); 3114 } 3115 3116 // -- for every j > 0, if const is in cv 1,j then const is in cv 3117 // 2,j, and similarly for volatile. 3118 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3119 return false; 3120 3121 // -- if the cv 1,j and cv 2,j are different, then const is in 3122 // every cv for 0 < k < j. 3123 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3124 && !PreviousToQualsIncludeConst) 3125 return false; 3126 3127 // Keep track of whether all prior cv-qualifiers in the "to" type 3128 // include const. 3129 PreviousToQualsIncludeConst 3130 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3131 } 3132 3133 // We are left with FromType and ToType being the pointee types 3134 // after unwrapping the original FromType and ToType the same number 3135 // of types. If we unwrapped any pointers, and if FromType and 3136 // ToType have the same unqualified type (since we checked 3137 // qualifiers above), then this is a qualification conversion. 3138 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3139 } 3140 3141 /// - Determine whether this is a conversion from a scalar type to an 3142 /// atomic type. 3143 /// 3144 /// If successful, updates \c SCS's second and third steps in the conversion 3145 /// sequence to finish the conversion. 3146 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3147 bool InOverloadResolution, 3148 StandardConversionSequence &SCS, 3149 bool CStyle) { 3150 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3151 if (!ToAtomic) 3152 return false; 3153 3154 StandardConversionSequence InnerSCS; 3155 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3156 InOverloadResolution, InnerSCS, 3157 CStyle, /*AllowObjCWritebackConversion=*/false)) 3158 return false; 3159 3160 SCS.Second = InnerSCS.Second; 3161 SCS.setToType(1, InnerSCS.getToType(1)); 3162 SCS.Third = InnerSCS.Third; 3163 SCS.QualificationIncludesObjCLifetime 3164 = InnerSCS.QualificationIncludesObjCLifetime; 3165 SCS.setToType(2, InnerSCS.getToType(2)); 3166 return true; 3167 } 3168 3169 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3170 CXXConstructorDecl *Constructor, 3171 QualType Type) { 3172 const FunctionProtoType *CtorType = 3173 Constructor->getType()->getAs<FunctionProtoType>(); 3174 if (CtorType->getNumParams() > 0) { 3175 QualType FirstArg = CtorType->getParamType(0); 3176 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3177 return true; 3178 } 3179 return false; 3180 } 3181 3182 static OverloadingResult 3183 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3184 CXXRecordDecl *To, 3185 UserDefinedConversionSequence &User, 3186 OverloadCandidateSet &CandidateSet, 3187 bool AllowExplicit) { 3188 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3189 for (auto *D : S.LookupConstructors(To)) { 3190 auto Info = getConstructorInfo(D); 3191 if (!Info) 3192 continue; 3193 3194 bool Usable = !Info.Constructor->isInvalidDecl() && 3195 S.isInitListConstructor(Info.Constructor) && 3196 (AllowExplicit || !Info.Constructor->isExplicit()); 3197 if (Usable) { 3198 // If the first argument is (a reference to) the target type, 3199 // suppress conversions. 3200 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3201 S.Context, Info.Constructor, ToType); 3202 if (Info.ConstructorTmpl) 3203 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3204 /*ExplicitArgs*/ nullptr, From, 3205 CandidateSet, SuppressUserConversions); 3206 else 3207 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3208 CandidateSet, SuppressUserConversions); 3209 } 3210 } 3211 3212 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3213 3214 OverloadCandidateSet::iterator Best; 3215 switch (auto Result = 3216 CandidateSet.BestViableFunction(S, From->getLocStart(), 3217 Best)) { 3218 case OR_Deleted: 3219 case OR_Success: { 3220 // Record the standard conversion we used and the conversion function. 3221 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3222 QualType ThisType = Constructor->getThisType(S.Context); 3223 // Initializer lists don't have conversions as such. 3224 User.Before.setAsIdentityConversion(); 3225 User.HadMultipleCandidates = HadMultipleCandidates; 3226 User.ConversionFunction = Constructor; 3227 User.FoundConversionFunction = Best->FoundDecl; 3228 User.After.setAsIdentityConversion(); 3229 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3230 User.After.setAllToTypes(ToType); 3231 return Result; 3232 } 3233 3234 case OR_No_Viable_Function: 3235 return OR_No_Viable_Function; 3236 case OR_Ambiguous: 3237 return OR_Ambiguous; 3238 } 3239 3240 llvm_unreachable("Invalid OverloadResult!"); 3241 } 3242 3243 /// Determines whether there is a user-defined conversion sequence 3244 /// (C++ [over.ics.user]) that converts expression From to the type 3245 /// ToType. If such a conversion exists, User will contain the 3246 /// user-defined conversion sequence that performs such a conversion 3247 /// and this routine will return true. Otherwise, this routine returns 3248 /// false and User is unspecified. 3249 /// 3250 /// \param AllowExplicit true if the conversion should consider C++0x 3251 /// "explicit" conversion functions as well as non-explicit conversion 3252 /// functions (C++0x [class.conv.fct]p2). 3253 /// 3254 /// \param AllowObjCConversionOnExplicit true if the conversion should 3255 /// allow an extra Objective-C pointer conversion on uses of explicit 3256 /// constructors. Requires \c AllowExplicit to also be set. 3257 static OverloadingResult 3258 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3259 UserDefinedConversionSequence &User, 3260 OverloadCandidateSet &CandidateSet, 3261 bool AllowExplicit, 3262 bool AllowObjCConversionOnExplicit) { 3263 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3264 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3265 3266 // Whether we will only visit constructors. 3267 bool ConstructorsOnly = false; 3268 3269 // If the type we are conversion to is a class type, enumerate its 3270 // constructors. 3271 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3272 // C++ [over.match.ctor]p1: 3273 // When objects of class type are direct-initialized (8.5), or 3274 // copy-initialized from an expression of the same or a 3275 // derived class type (8.5), overload resolution selects the 3276 // constructor. [...] For copy-initialization, the candidate 3277 // functions are all the converting constructors (12.3.1) of 3278 // that class. The argument list is the expression-list within 3279 // the parentheses of the initializer. 3280 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3281 (From->getType()->getAs<RecordType>() && 3282 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3283 ConstructorsOnly = true; 3284 3285 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3286 // We're not going to find any constructors. 3287 } else if (CXXRecordDecl *ToRecordDecl 3288 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3289 3290 Expr **Args = &From; 3291 unsigned NumArgs = 1; 3292 bool ListInitializing = false; 3293 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3294 // But first, see if there is an init-list-constructor that will work. 3295 OverloadingResult Result = IsInitializerListConstructorConversion( 3296 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3297 if (Result != OR_No_Viable_Function) 3298 return Result; 3299 // Never mind. 3300 CandidateSet.clear( 3301 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3302 3303 // If we're list-initializing, we pass the individual elements as 3304 // arguments, not the entire list. 3305 Args = InitList->getInits(); 3306 NumArgs = InitList->getNumInits(); 3307 ListInitializing = true; 3308 } 3309 3310 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3311 auto Info = getConstructorInfo(D); 3312 if (!Info) 3313 continue; 3314 3315 bool Usable = !Info.Constructor->isInvalidDecl(); 3316 if (ListInitializing) 3317 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3318 else 3319 Usable = Usable && 3320 Info.Constructor->isConvertingConstructor(AllowExplicit); 3321 if (Usable) { 3322 bool SuppressUserConversions = !ConstructorsOnly; 3323 if (SuppressUserConversions && ListInitializing) { 3324 SuppressUserConversions = false; 3325 if (NumArgs == 1) { 3326 // If the first argument is (a reference to) the target type, 3327 // suppress conversions. 3328 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3329 S.Context, Info.Constructor, ToType); 3330 } 3331 } 3332 if (Info.ConstructorTmpl) 3333 S.AddTemplateOverloadCandidate( 3334 Info.ConstructorTmpl, Info.FoundDecl, 3335 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3336 CandidateSet, SuppressUserConversions); 3337 else 3338 // Allow one user-defined conversion when user specifies a 3339 // From->ToType conversion via an static cast (c-style, etc). 3340 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3341 llvm::makeArrayRef(Args, NumArgs), 3342 CandidateSet, SuppressUserConversions); 3343 } 3344 } 3345 } 3346 } 3347 3348 // Enumerate conversion functions, if we're allowed to. 3349 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3350 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3351 // No conversion functions from incomplete types. 3352 } else if (const RecordType *FromRecordType 3353 = From->getType()->getAs<RecordType>()) { 3354 if (CXXRecordDecl *FromRecordDecl 3355 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3356 // Add all of the conversion functions as candidates. 3357 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3358 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3359 DeclAccessPair FoundDecl = I.getPair(); 3360 NamedDecl *D = FoundDecl.getDecl(); 3361 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3362 if (isa<UsingShadowDecl>(D)) 3363 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3364 3365 CXXConversionDecl *Conv; 3366 FunctionTemplateDecl *ConvTemplate; 3367 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3368 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3369 else 3370 Conv = cast<CXXConversionDecl>(D); 3371 3372 if (AllowExplicit || !Conv->isExplicit()) { 3373 if (ConvTemplate) 3374 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3375 ActingContext, From, ToType, 3376 CandidateSet, 3377 AllowObjCConversionOnExplicit); 3378 else 3379 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3380 From, ToType, CandidateSet, 3381 AllowObjCConversionOnExplicit); 3382 } 3383 } 3384 } 3385 } 3386 3387 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3388 3389 OverloadCandidateSet::iterator Best; 3390 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3391 Best)) { 3392 case OR_Success: 3393 case OR_Deleted: 3394 // Record the standard conversion we used and the conversion function. 3395 if (CXXConstructorDecl *Constructor 3396 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3397 // C++ [over.ics.user]p1: 3398 // If the user-defined conversion is specified by a 3399 // constructor (12.3.1), the initial standard conversion 3400 // sequence converts the source type to the type required by 3401 // the argument of the constructor. 3402 // 3403 QualType ThisType = Constructor->getThisType(S.Context); 3404 if (isa<InitListExpr>(From)) { 3405 // Initializer lists don't have conversions as such. 3406 User.Before.setAsIdentityConversion(); 3407 } else { 3408 if (Best->Conversions[0].isEllipsis()) 3409 User.EllipsisConversion = true; 3410 else { 3411 User.Before = Best->Conversions[0].Standard; 3412 User.EllipsisConversion = false; 3413 } 3414 } 3415 User.HadMultipleCandidates = HadMultipleCandidates; 3416 User.ConversionFunction = Constructor; 3417 User.FoundConversionFunction = Best->FoundDecl; 3418 User.After.setAsIdentityConversion(); 3419 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3420 User.After.setAllToTypes(ToType); 3421 return Result; 3422 } 3423 if (CXXConversionDecl *Conversion 3424 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3425 // C++ [over.ics.user]p1: 3426 // 3427 // [...] If the user-defined conversion is specified by a 3428 // conversion function (12.3.2), the initial standard 3429 // conversion sequence converts the source type to the 3430 // implicit object parameter of the conversion function. 3431 User.Before = Best->Conversions[0].Standard; 3432 User.HadMultipleCandidates = HadMultipleCandidates; 3433 User.ConversionFunction = Conversion; 3434 User.FoundConversionFunction = Best->FoundDecl; 3435 User.EllipsisConversion = false; 3436 3437 // C++ [over.ics.user]p2: 3438 // The second standard conversion sequence converts the 3439 // result of the user-defined conversion to the target type 3440 // for the sequence. Since an implicit conversion sequence 3441 // is an initialization, the special rules for 3442 // initialization by user-defined conversion apply when 3443 // selecting the best user-defined conversion for a 3444 // user-defined conversion sequence (see 13.3.3 and 3445 // 13.3.3.1). 3446 User.After = Best->FinalConversion; 3447 return Result; 3448 } 3449 llvm_unreachable("Not a constructor or conversion function?"); 3450 3451 case OR_No_Viable_Function: 3452 return OR_No_Viable_Function; 3453 3454 case OR_Ambiguous: 3455 return OR_Ambiguous; 3456 } 3457 3458 llvm_unreachable("Invalid OverloadResult!"); 3459 } 3460 3461 bool 3462 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3463 ImplicitConversionSequence ICS; 3464 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3465 OverloadCandidateSet::CSK_Normal); 3466 OverloadingResult OvResult = 3467 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3468 CandidateSet, false, false); 3469 if (OvResult == OR_Ambiguous) 3470 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3471 << From->getType() << ToType << From->getSourceRange(); 3472 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3473 if (!RequireCompleteType(From->getLocStart(), ToType, 3474 diag::err_typecheck_nonviable_condition_incomplete, 3475 From->getType(), From->getSourceRange())) 3476 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3477 << false << From->getType() << From->getSourceRange() << ToType; 3478 } else 3479 return false; 3480 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3481 return true; 3482 } 3483 3484 /// Compare the user-defined conversion functions or constructors 3485 /// of two user-defined conversion sequences to determine whether any ordering 3486 /// is possible. 3487 static ImplicitConversionSequence::CompareKind 3488 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3489 FunctionDecl *Function2) { 3490 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3491 return ImplicitConversionSequence::Indistinguishable; 3492 3493 // Objective-C++: 3494 // If both conversion functions are implicitly-declared conversions from 3495 // a lambda closure type to a function pointer and a block pointer, 3496 // respectively, always prefer the conversion to a function pointer, 3497 // because the function pointer is more lightweight and is more likely 3498 // to keep code working. 3499 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3500 if (!Conv1) 3501 return ImplicitConversionSequence::Indistinguishable; 3502 3503 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3504 if (!Conv2) 3505 return ImplicitConversionSequence::Indistinguishable; 3506 3507 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3508 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3509 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3510 if (Block1 != Block2) 3511 return Block1 ? ImplicitConversionSequence::Worse 3512 : ImplicitConversionSequence::Better; 3513 } 3514 3515 return ImplicitConversionSequence::Indistinguishable; 3516 } 3517 3518 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3519 const ImplicitConversionSequence &ICS) { 3520 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3521 (ICS.isUserDefined() && 3522 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3523 } 3524 3525 /// CompareImplicitConversionSequences - Compare two implicit 3526 /// conversion sequences to determine whether one is better than the 3527 /// other or if they are indistinguishable (C++ 13.3.3.2). 3528 static ImplicitConversionSequence::CompareKind 3529 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3530 const ImplicitConversionSequence& ICS1, 3531 const ImplicitConversionSequence& ICS2) 3532 { 3533 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3534 // conversion sequences (as defined in 13.3.3.1) 3535 // -- a standard conversion sequence (13.3.3.1.1) is a better 3536 // conversion sequence than a user-defined conversion sequence or 3537 // an ellipsis conversion sequence, and 3538 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3539 // conversion sequence than an ellipsis conversion sequence 3540 // (13.3.3.1.3). 3541 // 3542 // C++0x [over.best.ics]p10: 3543 // For the purpose of ranking implicit conversion sequences as 3544 // described in 13.3.3.2, the ambiguous conversion sequence is 3545 // treated as a user-defined sequence that is indistinguishable 3546 // from any other user-defined conversion sequence. 3547 3548 // String literal to 'char *' conversion has been deprecated in C++03. It has 3549 // been removed from C++11. We still accept this conversion, if it happens at 3550 // the best viable function. Otherwise, this conversion is considered worse 3551 // than ellipsis conversion. Consider this as an extension; this is not in the 3552 // standard. For example: 3553 // 3554 // int &f(...); // #1 3555 // void f(char*); // #2 3556 // void g() { int &r = f("foo"); } 3557 // 3558 // In C++03, we pick #2 as the best viable function. 3559 // In C++11, we pick #1 as the best viable function, because ellipsis 3560 // conversion is better than string-literal to char* conversion (since there 3561 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3562 // convert arguments, #2 would be the best viable function in C++11. 3563 // If the best viable function has this conversion, a warning will be issued 3564 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3565 3566 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3567 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3568 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3569 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3570 ? ImplicitConversionSequence::Worse 3571 : ImplicitConversionSequence::Better; 3572 3573 if (ICS1.getKindRank() < ICS2.getKindRank()) 3574 return ImplicitConversionSequence::Better; 3575 if (ICS2.getKindRank() < ICS1.getKindRank()) 3576 return ImplicitConversionSequence::Worse; 3577 3578 // The following checks require both conversion sequences to be of 3579 // the same kind. 3580 if (ICS1.getKind() != ICS2.getKind()) 3581 return ImplicitConversionSequence::Indistinguishable; 3582 3583 ImplicitConversionSequence::CompareKind Result = 3584 ImplicitConversionSequence::Indistinguishable; 3585 3586 // Two implicit conversion sequences of the same form are 3587 // indistinguishable conversion sequences unless one of the 3588 // following rules apply: (C++ 13.3.3.2p3): 3589 3590 // List-initialization sequence L1 is a better conversion sequence than 3591 // list-initialization sequence L2 if: 3592 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3593 // if not that, 3594 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3595 // and N1 is smaller than N2., 3596 // even if one of the other rules in this paragraph would otherwise apply. 3597 if (!ICS1.isBad()) { 3598 if (ICS1.isStdInitializerListElement() && 3599 !ICS2.isStdInitializerListElement()) 3600 return ImplicitConversionSequence::Better; 3601 if (!ICS1.isStdInitializerListElement() && 3602 ICS2.isStdInitializerListElement()) 3603 return ImplicitConversionSequence::Worse; 3604 } 3605 3606 if (ICS1.isStandard()) 3607 // Standard conversion sequence S1 is a better conversion sequence than 3608 // standard conversion sequence S2 if [...] 3609 Result = CompareStandardConversionSequences(S, Loc, 3610 ICS1.Standard, ICS2.Standard); 3611 else if (ICS1.isUserDefined()) { 3612 // User-defined conversion sequence U1 is a better conversion 3613 // sequence than another user-defined conversion sequence U2 if 3614 // they contain the same user-defined conversion function or 3615 // constructor and if the second standard conversion sequence of 3616 // U1 is better than the second standard conversion sequence of 3617 // U2 (C++ 13.3.3.2p3). 3618 if (ICS1.UserDefined.ConversionFunction == 3619 ICS2.UserDefined.ConversionFunction) 3620 Result = CompareStandardConversionSequences(S, Loc, 3621 ICS1.UserDefined.After, 3622 ICS2.UserDefined.After); 3623 else 3624 Result = compareConversionFunctions(S, 3625 ICS1.UserDefined.ConversionFunction, 3626 ICS2.UserDefined.ConversionFunction); 3627 } 3628 3629 return Result; 3630 } 3631 3632 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3633 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3634 Qualifiers Quals; 3635 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3636 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3637 } 3638 3639 return Context.hasSameUnqualifiedType(T1, T2); 3640 } 3641 3642 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3643 // determine if one is a proper subset of the other. 3644 static ImplicitConversionSequence::CompareKind 3645 compareStandardConversionSubsets(ASTContext &Context, 3646 const StandardConversionSequence& SCS1, 3647 const StandardConversionSequence& SCS2) { 3648 ImplicitConversionSequence::CompareKind Result 3649 = ImplicitConversionSequence::Indistinguishable; 3650 3651 // the identity conversion sequence is considered to be a subsequence of 3652 // any non-identity conversion sequence 3653 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3654 return ImplicitConversionSequence::Better; 3655 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3656 return ImplicitConversionSequence::Worse; 3657 3658 if (SCS1.Second != SCS2.Second) { 3659 if (SCS1.Second == ICK_Identity) 3660 Result = ImplicitConversionSequence::Better; 3661 else if (SCS2.Second == ICK_Identity) 3662 Result = ImplicitConversionSequence::Worse; 3663 else 3664 return ImplicitConversionSequence::Indistinguishable; 3665 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3666 return ImplicitConversionSequence::Indistinguishable; 3667 3668 if (SCS1.Third == SCS2.Third) { 3669 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3670 : ImplicitConversionSequence::Indistinguishable; 3671 } 3672 3673 if (SCS1.Third == ICK_Identity) 3674 return Result == ImplicitConversionSequence::Worse 3675 ? ImplicitConversionSequence::Indistinguishable 3676 : ImplicitConversionSequence::Better; 3677 3678 if (SCS2.Third == ICK_Identity) 3679 return Result == ImplicitConversionSequence::Better 3680 ? ImplicitConversionSequence::Indistinguishable 3681 : ImplicitConversionSequence::Worse; 3682 3683 return ImplicitConversionSequence::Indistinguishable; 3684 } 3685 3686 /// Determine whether one of the given reference bindings is better 3687 /// than the other based on what kind of bindings they are. 3688 static bool 3689 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3690 const StandardConversionSequence &SCS2) { 3691 // C++0x [over.ics.rank]p3b4: 3692 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3693 // implicit object parameter of a non-static member function declared 3694 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3695 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3696 // lvalue reference to a function lvalue and S2 binds an rvalue 3697 // reference*. 3698 // 3699 // FIXME: Rvalue references. We're going rogue with the above edits, 3700 // because the semantics in the current C++0x working paper (N3225 at the 3701 // time of this writing) break the standard definition of std::forward 3702 // and std::reference_wrapper when dealing with references to functions. 3703 // Proposed wording changes submitted to CWG for consideration. 3704 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3705 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3706 return false; 3707 3708 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3709 SCS2.IsLvalueReference) || 3710 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3711 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3712 } 3713 3714 /// CompareStandardConversionSequences - Compare two standard 3715 /// conversion sequences to determine whether one is better than the 3716 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3717 static ImplicitConversionSequence::CompareKind 3718 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3719 const StandardConversionSequence& SCS1, 3720 const StandardConversionSequence& SCS2) 3721 { 3722 // Standard conversion sequence S1 is a better conversion sequence 3723 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3724 3725 // -- S1 is a proper subsequence of S2 (comparing the conversion 3726 // sequences in the canonical form defined by 13.3.3.1.1, 3727 // excluding any Lvalue Transformation; the identity conversion 3728 // sequence is considered to be a subsequence of any 3729 // non-identity conversion sequence) or, if not that, 3730 if (ImplicitConversionSequence::CompareKind CK 3731 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3732 return CK; 3733 3734 // -- the rank of S1 is better than the rank of S2 (by the rules 3735 // defined below), or, if not that, 3736 ImplicitConversionRank Rank1 = SCS1.getRank(); 3737 ImplicitConversionRank Rank2 = SCS2.getRank(); 3738 if (Rank1 < Rank2) 3739 return ImplicitConversionSequence::Better; 3740 else if (Rank2 < Rank1) 3741 return ImplicitConversionSequence::Worse; 3742 3743 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3744 // are indistinguishable unless one of the following rules 3745 // applies: 3746 3747 // A conversion that is not a conversion of a pointer, or 3748 // pointer to member, to bool is better than another conversion 3749 // that is such a conversion. 3750 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3751 return SCS2.isPointerConversionToBool() 3752 ? ImplicitConversionSequence::Better 3753 : ImplicitConversionSequence::Worse; 3754 3755 // C++ [over.ics.rank]p4b2: 3756 // 3757 // If class B is derived directly or indirectly from class A, 3758 // conversion of B* to A* is better than conversion of B* to 3759 // void*, and conversion of A* to void* is better than conversion 3760 // of B* to void*. 3761 bool SCS1ConvertsToVoid 3762 = SCS1.isPointerConversionToVoidPointer(S.Context); 3763 bool SCS2ConvertsToVoid 3764 = SCS2.isPointerConversionToVoidPointer(S.Context); 3765 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3766 // Exactly one of the conversion sequences is a conversion to 3767 // a void pointer; it's the worse conversion. 3768 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3769 : ImplicitConversionSequence::Worse; 3770 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3771 // Neither conversion sequence converts to a void pointer; compare 3772 // their derived-to-base conversions. 3773 if (ImplicitConversionSequence::CompareKind DerivedCK 3774 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3775 return DerivedCK; 3776 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3777 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3778 // Both conversion sequences are conversions to void 3779 // pointers. Compare the source types to determine if there's an 3780 // inheritance relationship in their sources. 3781 QualType FromType1 = SCS1.getFromType(); 3782 QualType FromType2 = SCS2.getFromType(); 3783 3784 // Adjust the types we're converting from via the array-to-pointer 3785 // conversion, if we need to. 3786 if (SCS1.First == ICK_Array_To_Pointer) 3787 FromType1 = S.Context.getArrayDecayedType(FromType1); 3788 if (SCS2.First == ICK_Array_To_Pointer) 3789 FromType2 = S.Context.getArrayDecayedType(FromType2); 3790 3791 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3792 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3793 3794 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3795 return ImplicitConversionSequence::Better; 3796 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3797 return ImplicitConversionSequence::Worse; 3798 3799 // Objective-C++: If one interface is more specific than the 3800 // other, it is the better one. 3801 const ObjCObjectPointerType* FromObjCPtr1 3802 = FromType1->getAs<ObjCObjectPointerType>(); 3803 const ObjCObjectPointerType* FromObjCPtr2 3804 = FromType2->getAs<ObjCObjectPointerType>(); 3805 if (FromObjCPtr1 && FromObjCPtr2) { 3806 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3807 FromObjCPtr2); 3808 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3809 FromObjCPtr1); 3810 if (AssignLeft != AssignRight) { 3811 return AssignLeft? ImplicitConversionSequence::Better 3812 : ImplicitConversionSequence::Worse; 3813 } 3814 } 3815 } 3816 3817 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3818 // bullet 3). 3819 if (ImplicitConversionSequence::CompareKind QualCK 3820 = CompareQualificationConversions(S, SCS1, SCS2)) 3821 return QualCK; 3822 3823 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3824 // Check for a better reference binding based on the kind of bindings. 3825 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3826 return ImplicitConversionSequence::Better; 3827 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3828 return ImplicitConversionSequence::Worse; 3829 3830 // C++ [over.ics.rank]p3b4: 3831 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3832 // which the references refer are the same type except for 3833 // top-level cv-qualifiers, and the type to which the reference 3834 // initialized by S2 refers is more cv-qualified than the type 3835 // to which the reference initialized by S1 refers. 3836 QualType T1 = SCS1.getToType(2); 3837 QualType T2 = SCS2.getToType(2); 3838 T1 = S.Context.getCanonicalType(T1); 3839 T2 = S.Context.getCanonicalType(T2); 3840 Qualifiers T1Quals, T2Quals; 3841 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3842 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3843 if (UnqualT1 == UnqualT2) { 3844 // Objective-C++ ARC: If the references refer to objects with different 3845 // lifetimes, prefer bindings that don't change lifetime. 3846 if (SCS1.ObjCLifetimeConversionBinding != 3847 SCS2.ObjCLifetimeConversionBinding) { 3848 return SCS1.ObjCLifetimeConversionBinding 3849 ? ImplicitConversionSequence::Worse 3850 : ImplicitConversionSequence::Better; 3851 } 3852 3853 // If the type is an array type, promote the element qualifiers to the 3854 // type for comparison. 3855 if (isa<ArrayType>(T1) && T1Quals) 3856 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3857 if (isa<ArrayType>(T2) && T2Quals) 3858 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3859 if (T2.isMoreQualifiedThan(T1)) 3860 return ImplicitConversionSequence::Better; 3861 else if (T1.isMoreQualifiedThan(T2)) 3862 return ImplicitConversionSequence::Worse; 3863 } 3864 } 3865 3866 // In Microsoft mode, prefer an integral conversion to a 3867 // floating-to-integral conversion if the integral conversion 3868 // is between types of the same size. 3869 // For example: 3870 // void f(float); 3871 // void f(int); 3872 // int main { 3873 // long a; 3874 // f(a); 3875 // } 3876 // Here, MSVC will call f(int) instead of generating a compile error 3877 // as clang will do in standard mode. 3878 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3879 SCS2.Second == ICK_Floating_Integral && 3880 S.Context.getTypeSize(SCS1.getFromType()) == 3881 S.Context.getTypeSize(SCS1.getToType(2))) 3882 return ImplicitConversionSequence::Better; 3883 3884 return ImplicitConversionSequence::Indistinguishable; 3885 } 3886 3887 /// CompareQualificationConversions - Compares two standard conversion 3888 /// sequences to determine whether they can be ranked based on their 3889 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3890 static ImplicitConversionSequence::CompareKind 3891 CompareQualificationConversions(Sema &S, 3892 const StandardConversionSequence& SCS1, 3893 const StandardConversionSequence& SCS2) { 3894 // C++ 13.3.3.2p3: 3895 // -- S1 and S2 differ only in their qualification conversion and 3896 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3897 // cv-qualification signature of type T1 is a proper subset of 3898 // the cv-qualification signature of type T2, and S1 is not the 3899 // deprecated string literal array-to-pointer conversion (4.2). 3900 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3901 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3902 return ImplicitConversionSequence::Indistinguishable; 3903 3904 // FIXME: the example in the standard doesn't use a qualification 3905 // conversion (!) 3906 QualType T1 = SCS1.getToType(2); 3907 QualType T2 = SCS2.getToType(2); 3908 T1 = S.Context.getCanonicalType(T1); 3909 T2 = S.Context.getCanonicalType(T2); 3910 Qualifiers T1Quals, T2Quals; 3911 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3912 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3913 3914 // If the types are the same, we won't learn anything by unwrapped 3915 // them. 3916 if (UnqualT1 == UnqualT2) 3917 return ImplicitConversionSequence::Indistinguishable; 3918 3919 // If the type is an array type, promote the element qualifiers to the type 3920 // for comparison. 3921 if (isa<ArrayType>(T1) && T1Quals) 3922 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3923 if (isa<ArrayType>(T2) && T2Quals) 3924 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3925 3926 ImplicitConversionSequence::CompareKind Result 3927 = ImplicitConversionSequence::Indistinguishable; 3928 3929 // Objective-C++ ARC: 3930 // Prefer qualification conversions not involving a change in lifetime 3931 // to qualification conversions that do not change lifetime. 3932 if (SCS1.QualificationIncludesObjCLifetime != 3933 SCS2.QualificationIncludesObjCLifetime) { 3934 Result = SCS1.QualificationIncludesObjCLifetime 3935 ? ImplicitConversionSequence::Worse 3936 : ImplicitConversionSequence::Better; 3937 } 3938 3939 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3940 // Within each iteration of the loop, we check the qualifiers to 3941 // determine if this still looks like a qualification 3942 // conversion. Then, if all is well, we unwrap one more level of 3943 // pointers or pointers-to-members and do it all again 3944 // until there are no more pointers or pointers-to-members left 3945 // to unwrap. This essentially mimics what 3946 // IsQualificationConversion does, but here we're checking for a 3947 // strict subset of qualifiers. 3948 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3949 // The qualifiers are the same, so this doesn't tell us anything 3950 // about how the sequences rank. 3951 ; 3952 else if (T2.isMoreQualifiedThan(T1)) { 3953 // T1 has fewer qualifiers, so it could be the better sequence. 3954 if (Result == ImplicitConversionSequence::Worse) 3955 // Neither has qualifiers that are a subset of the other's 3956 // qualifiers. 3957 return ImplicitConversionSequence::Indistinguishable; 3958 3959 Result = ImplicitConversionSequence::Better; 3960 } else if (T1.isMoreQualifiedThan(T2)) { 3961 // T2 has fewer qualifiers, so it could be the better sequence. 3962 if (Result == ImplicitConversionSequence::Better) 3963 // Neither has qualifiers that are a subset of the other's 3964 // qualifiers. 3965 return ImplicitConversionSequence::Indistinguishable; 3966 3967 Result = ImplicitConversionSequence::Worse; 3968 } else { 3969 // Qualifiers are disjoint. 3970 return ImplicitConversionSequence::Indistinguishable; 3971 } 3972 3973 // If the types after this point are equivalent, we're done. 3974 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3975 break; 3976 } 3977 3978 // Check that the winning standard conversion sequence isn't using 3979 // the deprecated string literal array to pointer conversion. 3980 switch (Result) { 3981 case ImplicitConversionSequence::Better: 3982 if (SCS1.DeprecatedStringLiteralToCharPtr) 3983 Result = ImplicitConversionSequence::Indistinguishable; 3984 break; 3985 3986 case ImplicitConversionSequence::Indistinguishable: 3987 break; 3988 3989 case ImplicitConversionSequence::Worse: 3990 if (SCS2.DeprecatedStringLiteralToCharPtr) 3991 Result = ImplicitConversionSequence::Indistinguishable; 3992 break; 3993 } 3994 3995 return Result; 3996 } 3997 3998 /// CompareDerivedToBaseConversions - Compares two standard conversion 3999 /// sequences to determine whether they can be ranked based on their 4000 /// various kinds of derived-to-base conversions (C++ 4001 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4002 /// conversions between Objective-C interface types. 4003 static ImplicitConversionSequence::CompareKind 4004 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4005 const StandardConversionSequence& SCS1, 4006 const StandardConversionSequence& SCS2) { 4007 QualType FromType1 = SCS1.getFromType(); 4008 QualType ToType1 = SCS1.getToType(1); 4009 QualType FromType2 = SCS2.getFromType(); 4010 QualType ToType2 = SCS2.getToType(1); 4011 4012 // Adjust the types we're converting from via the array-to-pointer 4013 // conversion, if we need to. 4014 if (SCS1.First == ICK_Array_To_Pointer) 4015 FromType1 = S.Context.getArrayDecayedType(FromType1); 4016 if (SCS2.First == ICK_Array_To_Pointer) 4017 FromType2 = S.Context.getArrayDecayedType(FromType2); 4018 4019 // Canonicalize all of the types. 4020 FromType1 = S.Context.getCanonicalType(FromType1); 4021 ToType1 = S.Context.getCanonicalType(ToType1); 4022 FromType2 = S.Context.getCanonicalType(FromType2); 4023 ToType2 = S.Context.getCanonicalType(ToType2); 4024 4025 // C++ [over.ics.rank]p4b3: 4026 // 4027 // If class B is derived directly or indirectly from class A and 4028 // class C is derived directly or indirectly from B, 4029 // 4030 // Compare based on pointer conversions. 4031 if (SCS1.Second == ICK_Pointer_Conversion && 4032 SCS2.Second == ICK_Pointer_Conversion && 4033 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4034 FromType1->isPointerType() && FromType2->isPointerType() && 4035 ToType1->isPointerType() && ToType2->isPointerType()) { 4036 QualType FromPointee1 4037 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4038 QualType ToPointee1 4039 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4040 QualType FromPointee2 4041 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4042 QualType ToPointee2 4043 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4044 4045 // -- conversion of C* to B* is better than conversion of C* to A*, 4046 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4047 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4048 return ImplicitConversionSequence::Better; 4049 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4050 return ImplicitConversionSequence::Worse; 4051 } 4052 4053 // -- conversion of B* to A* is better than conversion of C* to A*, 4054 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4055 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4056 return ImplicitConversionSequence::Better; 4057 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4058 return ImplicitConversionSequence::Worse; 4059 } 4060 } else if (SCS1.Second == ICK_Pointer_Conversion && 4061 SCS2.Second == ICK_Pointer_Conversion) { 4062 const ObjCObjectPointerType *FromPtr1 4063 = FromType1->getAs<ObjCObjectPointerType>(); 4064 const ObjCObjectPointerType *FromPtr2 4065 = FromType2->getAs<ObjCObjectPointerType>(); 4066 const ObjCObjectPointerType *ToPtr1 4067 = ToType1->getAs<ObjCObjectPointerType>(); 4068 const ObjCObjectPointerType *ToPtr2 4069 = ToType2->getAs<ObjCObjectPointerType>(); 4070 4071 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4072 // Apply the same conversion ranking rules for Objective-C pointer types 4073 // that we do for C++ pointers to class types. However, we employ the 4074 // Objective-C pseudo-subtyping relationship used for assignment of 4075 // Objective-C pointer types. 4076 bool FromAssignLeft 4077 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4078 bool FromAssignRight 4079 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4080 bool ToAssignLeft 4081 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4082 bool ToAssignRight 4083 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4084 4085 // A conversion to an a non-id object pointer type or qualified 'id' 4086 // type is better than a conversion to 'id'. 4087 if (ToPtr1->isObjCIdType() && 4088 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4089 return ImplicitConversionSequence::Worse; 4090 if (ToPtr2->isObjCIdType() && 4091 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4092 return ImplicitConversionSequence::Better; 4093 4094 // A conversion to a non-id object pointer type is better than a 4095 // conversion to a qualified 'id' type 4096 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4097 return ImplicitConversionSequence::Worse; 4098 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4099 return ImplicitConversionSequence::Better; 4100 4101 // A conversion to an a non-Class object pointer type or qualified 'Class' 4102 // type is better than a conversion to 'Class'. 4103 if (ToPtr1->isObjCClassType() && 4104 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4105 return ImplicitConversionSequence::Worse; 4106 if (ToPtr2->isObjCClassType() && 4107 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4108 return ImplicitConversionSequence::Better; 4109 4110 // A conversion to a non-Class object pointer type is better than a 4111 // conversion to a qualified 'Class' type. 4112 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4113 return ImplicitConversionSequence::Worse; 4114 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4115 return ImplicitConversionSequence::Better; 4116 4117 // -- "conversion of C* to B* is better than conversion of C* to A*," 4118 if (S.Context.hasSameType(FromType1, FromType2) && 4119 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4120 (ToAssignLeft != ToAssignRight)) { 4121 if (FromPtr1->isSpecialized()) { 4122 // "conversion of B<A> * to B * is better than conversion of B * to 4123 // C *. 4124 bool IsFirstSame = 4125 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4126 bool IsSecondSame = 4127 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4128 if (IsFirstSame) { 4129 if (!IsSecondSame) 4130 return ImplicitConversionSequence::Better; 4131 } else if (IsSecondSame) 4132 return ImplicitConversionSequence::Worse; 4133 } 4134 return ToAssignLeft? ImplicitConversionSequence::Worse 4135 : ImplicitConversionSequence::Better; 4136 } 4137 4138 // -- "conversion of B* to A* is better than conversion of C* to A*," 4139 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4140 (FromAssignLeft != FromAssignRight)) 4141 return FromAssignLeft? ImplicitConversionSequence::Better 4142 : ImplicitConversionSequence::Worse; 4143 } 4144 } 4145 4146 // Ranking of member-pointer types. 4147 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4148 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4149 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4150 const MemberPointerType * FromMemPointer1 = 4151 FromType1->getAs<MemberPointerType>(); 4152 const MemberPointerType * ToMemPointer1 = 4153 ToType1->getAs<MemberPointerType>(); 4154 const MemberPointerType * FromMemPointer2 = 4155 FromType2->getAs<MemberPointerType>(); 4156 const MemberPointerType * ToMemPointer2 = 4157 ToType2->getAs<MemberPointerType>(); 4158 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4159 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4160 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4161 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4162 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4163 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4164 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4165 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4166 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4167 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4168 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4169 return ImplicitConversionSequence::Worse; 4170 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4171 return ImplicitConversionSequence::Better; 4172 } 4173 // conversion of B::* to C::* is better than conversion of A::* to C::* 4174 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4175 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4176 return ImplicitConversionSequence::Better; 4177 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4178 return ImplicitConversionSequence::Worse; 4179 } 4180 } 4181 4182 if (SCS1.Second == ICK_Derived_To_Base) { 4183 // -- conversion of C to B is better than conversion of C to A, 4184 // -- binding of an expression of type C to a reference of type 4185 // B& is better than binding an expression of type C to a 4186 // reference of type A&, 4187 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4188 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4189 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4190 return ImplicitConversionSequence::Better; 4191 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4192 return ImplicitConversionSequence::Worse; 4193 } 4194 4195 // -- conversion of B to A is better than conversion of C to A. 4196 // -- binding of an expression of type B to a reference of type 4197 // A& is better than binding an expression of type C to a 4198 // reference of type A&, 4199 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4200 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4201 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4202 return ImplicitConversionSequence::Better; 4203 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4204 return ImplicitConversionSequence::Worse; 4205 } 4206 } 4207 4208 return ImplicitConversionSequence::Indistinguishable; 4209 } 4210 4211 /// Determine whether the given type is valid, e.g., it is not an invalid 4212 /// C++ class. 4213 static bool isTypeValid(QualType T) { 4214 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4215 return !Record->isInvalidDecl(); 4216 4217 return true; 4218 } 4219 4220 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4221 /// determine whether they are reference-related, 4222 /// reference-compatible, reference-compatible with added 4223 /// qualification, or incompatible, for use in C++ initialization by 4224 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4225 /// type, and the first type (T1) is the pointee type of the reference 4226 /// type being initialized. 4227 Sema::ReferenceCompareResult 4228 Sema::CompareReferenceRelationship(SourceLocation Loc, 4229 QualType OrigT1, QualType OrigT2, 4230 bool &DerivedToBase, 4231 bool &ObjCConversion, 4232 bool &ObjCLifetimeConversion) { 4233 assert(!OrigT1->isReferenceType() && 4234 "T1 must be the pointee type of the reference type"); 4235 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4236 4237 QualType T1 = Context.getCanonicalType(OrigT1); 4238 QualType T2 = Context.getCanonicalType(OrigT2); 4239 Qualifiers T1Quals, T2Quals; 4240 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4241 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4242 4243 // C++ [dcl.init.ref]p4: 4244 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4245 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4246 // T1 is a base class of T2. 4247 DerivedToBase = false; 4248 ObjCConversion = false; 4249 ObjCLifetimeConversion = false; 4250 QualType ConvertedT2; 4251 if (UnqualT1 == UnqualT2) { 4252 // Nothing to do. 4253 } else if (isCompleteType(Loc, OrigT2) && 4254 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4255 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4256 DerivedToBase = true; 4257 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4258 UnqualT2->isObjCObjectOrInterfaceType() && 4259 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4260 ObjCConversion = true; 4261 else if (UnqualT2->isFunctionType() && 4262 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4263 // C++1z [dcl.init.ref]p4: 4264 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4265 // function" and T1 is "function" 4266 // 4267 // We extend this to also apply to 'noreturn', so allow any function 4268 // conversion between function types. 4269 return Ref_Compatible; 4270 else 4271 return Ref_Incompatible; 4272 4273 // At this point, we know that T1 and T2 are reference-related (at 4274 // least). 4275 4276 // If the type is an array type, promote the element qualifiers to the type 4277 // for comparison. 4278 if (isa<ArrayType>(T1) && T1Quals) 4279 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4280 if (isa<ArrayType>(T2) && T2Quals) 4281 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4282 4283 // C++ [dcl.init.ref]p4: 4284 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4285 // reference-related to T2 and cv1 is the same cv-qualification 4286 // as, or greater cv-qualification than, cv2. For purposes of 4287 // overload resolution, cases for which cv1 is greater 4288 // cv-qualification than cv2 are identified as 4289 // reference-compatible with added qualification (see 13.3.3.2). 4290 // 4291 // Note that we also require equivalence of Objective-C GC and address-space 4292 // qualifiers when performing these computations, so that e.g., an int in 4293 // address space 1 is not reference-compatible with an int in address 4294 // space 2. 4295 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4296 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4297 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4298 ObjCLifetimeConversion = true; 4299 4300 T1Quals.removeObjCLifetime(); 4301 T2Quals.removeObjCLifetime(); 4302 } 4303 4304 // MS compiler ignores __unaligned qualifier for references; do the same. 4305 T1Quals.removeUnaligned(); 4306 T2Quals.removeUnaligned(); 4307 4308 if (T1Quals.compatiblyIncludes(T2Quals)) 4309 return Ref_Compatible; 4310 else 4311 return Ref_Related; 4312 } 4313 4314 /// Look for a user-defined conversion to a value reference-compatible 4315 /// with DeclType. Return true if something definite is found. 4316 static bool 4317 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4318 QualType DeclType, SourceLocation DeclLoc, 4319 Expr *Init, QualType T2, bool AllowRvalues, 4320 bool AllowExplicit) { 4321 assert(T2->isRecordType() && "Can only find conversions of record types."); 4322 CXXRecordDecl *T2RecordDecl 4323 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4324 4325 OverloadCandidateSet CandidateSet( 4326 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4327 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4328 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4329 NamedDecl *D = *I; 4330 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4331 if (isa<UsingShadowDecl>(D)) 4332 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4333 4334 FunctionTemplateDecl *ConvTemplate 4335 = dyn_cast<FunctionTemplateDecl>(D); 4336 CXXConversionDecl *Conv; 4337 if (ConvTemplate) 4338 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4339 else 4340 Conv = cast<CXXConversionDecl>(D); 4341 4342 // If this is an explicit conversion, and we're not allowed to consider 4343 // explicit conversions, skip it. 4344 if (!AllowExplicit && Conv->isExplicit()) 4345 continue; 4346 4347 if (AllowRvalues) { 4348 bool DerivedToBase = false; 4349 bool ObjCConversion = false; 4350 bool ObjCLifetimeConversion = false; 4351 4352 // If we are initializing an rvalue reference, don't permit conversion 4353 // functions that return lvalues. 4354 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4355 const ReferenceType *RefType 4356 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4357 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4358 continue; 4359 } 4360 4361 if (!ConvTemplate && 4362 S.CompareReferenceRelationship( 4363 DeclLoc, 4364 Conv->getConversionType().getNonReferenceType() 4365 .getUnqualifiedType(), 4366 DeclType.getNonReferenceType().getUnqualifiedType(), 4367 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4368 Sema::Ref_Incompatible) 4369 continue; 4370 } else { 4371 // If the conversion function doesn't return a reference type, 4372 // it can't be considered for this conversion. An rvalue reference 4373 // is only acceptable if its referencee is a function type. 4374 4375 const ReferenceType *RefType = 4376 Conv->getConversionType()->getAs<ReferenceType>(); 4377 if (!RefType || 4378 (!RefType->isLValueReferenceType() && 4379 !RefType->getPointeeType()->isFunctionType())) 4380 continue; 4381 } 4382 4383 if (ConvTemplate) 4384 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4385 Init, DeclType, CandidateSet, 4386 /*AllowObjCConversionOnExplicit=*/false); 4387 else 4388 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4389 DeclType, CandidateSet, 4390 /*AllowObjCConversionOnExplicit=*/false); 4391 } 4392 4393 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4394 4395 OverloadCandidateSet::iterator Best; 4396 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4397 case OR_Success: 4398 // C++ [over.ics.ref]p1: 4399 // 4400 // [...] If the parameter binds directly to the result of 4401 // applying a conversion function to the argument 4402 // expression, the implicit conversion sequence is a 4403 // user-defined conversion sequence (13.3.3.1.2), with the 4404 // second standard conversion sequence either an identity 4405 // conversion or, if the conversion function returns an 4406 // entity of a type that is a derived class of the parameter 4407 // type, a derived-to-base Conversion. 4408 if (!Best->FinalConversion.DirectBinding) 4409 return false; 4410 4411 ICS.setUserDefined(); 4412 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4413 ICS.UserDefined.After = Best->FinalConversion; 4414 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4415 ICS.UserDefined.ConversionFunction = Best->Function; 4416 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4417 ICS.UserDefined.EllipsisConversion = false; 4418 assert(ICS.UserDefined.After.ReferenceBinding && 4419 ICS.UserDefined.After.DirectBinding && 4420 "Expected a direct reference binding!"); 4421 return true; 4422 4423 case OR_Ambiguous: 4424 ICS.setAmbiguous(); 4425 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4426 Cand != CandidateSet.end(); ++Cand) 4427 if (Cand->Viable) 4428 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4429 return true; 4430 4431 case OR_No_Viable_Function: 4432 case OR_Deleted: 4433 // There was no suitable conversion, or we found a deleted 4434 // conversion; continue with other checks. 4435 return false; 4436 } 4437 4438 llvm_unreachable("Invalid OverloadResult!"); 4439 } 4440 4441 /// Compute an implicit conversion sequence for reference 4442 /// initialization. 4443 static ImplicitConversionSequence 4444 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4445 SourceLocation DeclLoc, 4446 bool SuppressUserConversions, 4447 bool AllowExplicit) { 4448 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4449 4450 // Most paths end in a failed conversion. 4451 ImplicitConversionSequence ICS; 4452 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4453 4454 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4455 QualType T2 = Init->getType(); 4456 4457 // If the initializer is the address of an overloaded function, try 4458 // to resolve the overloaded function. If all goes well, T2 is the 4459 // type of the resulting function. 4460 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4461 DeclAccessPair Found; 4462 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4463 false, Found)) 4464 T2 = Fn->getType(); 4465 } 4466 4467 // Compute some basic properties of the types and the initializer. 4468 bool isRValRef = DeclType->isRValueReferenceType(); 4469 bool DerivedToBase = false; 4470 bool ObjCConversion = false; 4471 bool ObjCLifetimeConversion = false; 4472 Expr::Classification InitCategory = Init->Classify(S.Context); 4473 Sema::ReferenceCompareResult RefRelationship 4474 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4475 ObjCConversion, ObjCLifetimeConversion); 4476 4477 4478 // C++0x [dcl.init.ref]p5: 4479 // A reference to type "cv1 T1" is initialized by an expression 4480 // of type "cv2 T2" as follows: 4481 4482 // -- If reference is an lvalue reference and the initializer expression 4483 if (!isRValRef) { 4484 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4485 // reference-compatible with "cv2 T2," or 4486 // 4487 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4488 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4489 // C++ [over.ics.ref]p1: 4490 // When a parameter of reference type binds directly (8.5.3) 4491 // to an argument expression, the implicit conversion sequence 4492 // is the identity conversion, unless the argument expression 4493 // has a type that is a derived class of the parameter type, 4494 // in which case the implicit conversion sequence is a 4495 // derived-to-base Conversion (13.3.3.1). 4496 ICS.setStandard(); 4497 ICS.Standard.First = ICK_Identity; 4498 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4499 : ObjCConversion? ICK_Compatible_Conversion 4500 : ICK_Identity; 4501 ICS.Standard.Third = ICK_Identity; 4502 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4503 ICS.Standard.setToType(0, T2); 4504 ICS.Standard.setToType(1, T1); 4505 ICS.Standard.setToType(2, T1); 4506 ICS.Standard.ReferenceBinding = true; 4507 ICS.Standard.DirectBinding = true; 4508 ICS.Standard.IsLvalueReference = !isRValRef; 4509 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4510 ICS.Standard.BindsToRvalue = false; 4511 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4512 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4513 ICS.Standard.CopyConstructor = nullptr; 4514 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4515 4516 // Nothing more to do: the inaccessibility/ambiguity check for 4517 // derived-to-base conversions is suppressed when we're 4518 // computing the implicit conversion sequence (C++ 4519 // [over.best.ics]p2). 4520 return ICS; 4521 } 4522 4523 // -- has a class type (i.e., T2 is a class type), where T1 is 4524 // not reference-related to T2, and can be implicitly 4525 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4526 // is reference-compatible with "cv3 T3" 92) (this 4527 // conversion is selected by enumerating the applicable 4528 // conversion functions (13.3.1.6) and choosing the best 4529 // one through overload resolution (13.3)), 4530 if (!SuppressUserConversions && T2->isRecordType() && 4531 S.isCompleteType(DeclLoc, T2) && 4532 RefRelationship == Sema::Ref_Incompatible) { 4533 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4534 Init, T2, /*AllowRvalues=*/false, 4535 AllowExplicit)) 4536 return ICS; 4537 } 4538 } 4539 4540 // -- Otherwise, the reference shall be an lvalue reference to a 4541 // non-volatile const type (i.e., cv1 shall be const), or the reference 4542 // shall be an rvalue reference. 4543 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4544 return ICS; 4545 4546 // -- If the initializer expression 4547 // 4548 // -- is an xvalue, class prvalue, array prvalue or function 4549 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4550 if (RefRelationship == Sema::Ref_Compatible && 4551 (InitCategory.isXValue() || 4552 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4553 (InitCategory.isLValue() && T2->isFunctionType()))) { 4554 ICS.setStandard(); 4555 ICS.Standard.First = ICK_Identity; 4556 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4557 : ObjCConversion? ICK_Compatible_Conversion 4558 : ICK_Identity; 4559 ICS.Standard.Third = ICK_Identity; 4560 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4561 ICS.Standard.setToType(0, T2); 4562 ICS.Standard.setToType(1, T1); 4563 ICS.Standard.setToType(2, T1); 4564 ICS.Standard.ReferenceBinding = true; 4565 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4566 // binding unless we're binding to a class prvalue. 4567 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4568 // allow the use of rvalue references in C++98/03 for the benefit of 4569 // standard library implementors; therefore, we need the xvalue check here. 4570 ICS.Standard.DirectBinding = 4571 S.getLangOpts().CPlusPlus11 || 4572 !(InitCategory.isPRValue() || T2->isRecordType()); 4573 ICS.Standard.IsLvalueReference = !isRValRef; 4574 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4575 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4576 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4577 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4578 ICS.Standard.CopyConstructor = nullptr; 4579 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4580 return ICS; 4581 } 4582 4583 // -- has a class type (i.e., T2 is a class type), where T1 is not 4584 // reference-related to T2, and can be implicitly converted to 4585 // an xvalue, class prvalue, or function lvalue of type 4586 // "cv3 T3", where "cv1 T1" is reference-compatible with 4587 // "cv3 T3", 4588 // 4589 // then the reference is bound to the value of the initializer 4590 // expression in the first case and to the result of the conversion 4591 // in the second case (or, in either case, to an appropriate base 4592 // class subobject). 4593 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4594 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4595 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4596 Init, T2, /*AllowRvalues=*/true, 4597 AllowExplicit)) { 4598 // In the second case, if the reference is an rvalue reference 4599 // and the second standard conversion sequence of the 4600 // user-defined conversion sequence includes an lvalue-to-rvalue 4601 // conversion, the program is ill-formed. 4602 if (ICS.isUserDefined() && isRValRef && 4603 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4604 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4605 4606 return ICS; 4607 } 4608 4609 // A temporary of function type cannot be created; don't even try. 4610 if (T1->isFunctionType()) 4611 return ICS; 4612 4613 // -- Otherwise, a temporary of type "cv1 T1" is created and 4614 // initialized from the initializer expression using the 4615 // rules for a non-reference copy initialization (8.5). The 4616 // reference is then bound to the temporary. If T1 is 4617 // reference-related to T2, cv1 must be the same 4618 // cv-qualification as, or greater cv-qualification than, 4619 // cv2; otherwise, the program is ill-formed. 4620 if (RefRelationship == Sema::Ref_Related) { 4621 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4622 // we would be reference-compatible or reference-compatible with 4623 // added qualification. But that wasn't the case, so the reference 4624 // initialization fails. 4625 // 4626 // Note that we only want to check address spaces and cvr-qualifiers here. 4627 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4628 Qualifiers T1Quals = T1.getQualifiers(); 4629 Qualifiers T2Quals = T2.getQualifiers(); 4630 T1Quals.removeObjCGCAttr(); 4631 T1Quals.removeObjCLifetime(); 4632 T2Quals.removeObjCGCAttr(); 4633 T2Quals.removeObjCLifetime(); 4634 // MS compiler ignores __unaligned qualifier for references; do the same. 4635 T1Quals.removeUnaligned(); 4636 T2Quals.removeUnaligned(); 4637 if (!T1Quals.compatiblyIncludes(T2Quals)) 4638 return ICS; 4639 } 4640 4641 // If at least one of the types is a class type, the types are not 4642 // related, and we aren't allowed any user conversions, the 4643 // reference binding fails. This case is important for breaking 4644 // recursion, since TryImplicitConversion below will attempt to 4645 // create a temporary through the use of a copy constructor. 4646 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4647 (T1->isRecordType() || T2->isRecordType())) 4648 return ICS; 4649 4650 // If T1 is reference-related to T2 and the reference is an rvalue 4651 // reference, the initializer expression shall not be an lvalue. 4652 if (RefRelationship >= Sema::Ref_Related && 4653 isRValRef && Init->Classify(S.Context).isLValue()) 4654 return ICS; 4655 4656 // C++ [over.ics.ref]p2: 4657 // When a parameter of reference type is not bound directly to 4658 // an argument expression, the conversion sequence is the one 4659 // required to convert the argument expression to the 4660 // underlying type of the reference according to 4661 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4662 // to copy-initializing a temporary of the underlying type with 4663 // the argument expression. Any difference in top-level 4664 // cv-qualification is subsumed by the initialization itself 4665 // and does not constitute a conversion. 4666 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4667 /*AllowExplicit=*/false, 4668 /*InOverloadResolution=*/false, 4669 /*CStyle=*/false, 4670 /*AllowObjCWritebackConversion=*/false, 4671 /*AllowObjCConversionOnExplicit=*/false); 4672 4673 // Of course, that's still a reference binding. 4674 if (ICS.isStandard()) { 4675 ICS.Standard.ReferenceBinding = true; 4676 ICS.Standard.IsLvalueReference = !isRValRef; 4677 ICS.Standard.BindsToFunctionLvalue = false; 4678 ICS.Standard.BindsToRvalue = true; 4679 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4680 ICS.Standard.ObjCLifetimeConversionBinding = false; 4681 } else if (ICS.isUserDefined()) { 4682 const ReferenceType *LValRefType = 4683 ICS.UserDefined.ConversionFunction->getReturnType() 4684 ->getAs<LValueReferenceType>(); 4685 4686 // C++ [over.ics.ref]p3: 4687 // Except for an implicit object parameter, for which see 13.3.1, a 4688 // standard conversion sequence cannot be formed if it requires [...] 4689 // binding an rvalue reference to an lvalue other than a function 4690 // lvalue. 4691 // Note that the function case is not possible here. 4692 if (DeclType->isRValueReferenceType() && LValRefType) { 4693 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4694 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4695 // reference to an rvalue! 4696 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4697 return ICS; 4698 } 4699 4700 ICS.UserDefined.After.ReferenceBinding = true; 4701 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4702 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4703 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4704 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4705 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4706 } 4707 4708 return ICS; 4709 } 4710 4711 static ImplicitConversionSequence 4712 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4713 bool SuppressUserConversions, 4714 bool InOverloadResolution, 4715 bool AllowObjCWritebackConversion, 4716 bool AllowExplicit = false); 4717 4718 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4719 /// initializer list From. 4720 static ImplicitConversionSequence 4721 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4722 bool SuppressUserConversions, 4723 bool InOverloadResolution, 4724 bool AllowObjCWritebackConversion) { 4725 // C++11 [over.ics.list]p1: 4726 // When an argument is an initializer list, it is not an expression and 4727 // special rules apply for converting it to a parameter type. 4728 4729 ImplicitConversionSequence Result; 4730 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4731 4732 // We need a complete type for what follows. Incomplete types can never be 4733 // initialized from init lists. 4734 if (!S.isCompleteType(From->getLocStart(), ToType)) 4735 return Result; 4736 4737 // Per DR1467: 4738 // If the parameter type is a class X and the initializer list has a single 4739 // element of type cv U, where U is X or a class derived from X, the 4740 // implicit conversion sequence is the one required to convert the element 4741 // to the parameter type. 4742 // 4743 // Otherwise, if the parameter type is a character array [... ] 4744 // and the initializer list has a single element that is an 4745 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4746 // implicit conversion sequence is the identity conversion. 4747 if (From->getNumInits() == 1) { 4748 if (ToType->isRecordType()) { 4749 QualType InitType = From->getInit(0)->getType(); 4750 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4751 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4752 return TryCopyInitialization(S, From->getInit(0), ToType, 4753 SuppressUserConversions, 4754 InOverloadResolution, 4755 AllowObjCWritebackConversion); 4756 } 4757 // FIXME: Check the other conditions here: array of character type, 4758 // initializer is a string literal. 4759 if (ToType->isArrayType()) { 4760 InitializedEntity Entity = 4761 InitializedEntity::InitializeParameter(S.Context, ToType, 4762 /*Consumed=*/false); 4763 if (S.CanPerformCopyInitialization(Entity, From)) { 4764 Result.setStandard(); 4765 Result.Standard.setAsIdentityConversion(); 4766 Result.Standard.setFromType(ToType); 4767 Result.Standard.setAllToTypes(ToType); 4768 return Result; 4769 } 4770 } 4771 } 4772 4773 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4774 // C++11 [over.ics.list]p2: 4775 // If the parameter type is std::initializer_list<X> or "array of X" and 4776 // all the elements can be implicitly converted to X, the implicit 4777 // conversion sequence is the worst conversion necessary to convert an 4778 // element of the list to X. 4779 // 4780 // C++14 [over.ics.list]p3: 4781 // Otherwise, if the parameter type is "array of N X", if the initializer 4782 // list has exactly N elements or if it has fewer than N elements and X is 4783 // default-constructible, and if all the elements of the initializer list 4784 // can be implicitly converted to X, the implicit conversion sequence is 4785 // the worst conversion necessary to convert an element of the list to X. 4786 // 4787 // FIXME: We're missing a lot of these checks. 4788 bool toStdInitializerList = false; 4789 QualType X; 4790 if (ToType->isArrayType()) 4791 X = S.Context.getAsArrayType(ToType)->getElementType(); 4792 else 4793 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4794 if (!X.isNull()) { 4795 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4796 Expr *Init = From->getInit(i); 4797 ImplicitConversionSequence ICS = 4798 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4799 InOverloadResolution, 4800 AllowObjCWritebackConversion); 4801 // If a single element isn't convertible, fail. 4802 if (ICS.isBad()) { 4803 Result = ICS; 4804 break; 4805 } 4806 // Otherwise, look for the worst conversion. 4807 if (Result.isBad() || 4808 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4809 Result) == 4810 ImplicitConversionSequence::Worse) 4811 Result = ICS; 4812 } 4813 4814 // For an empty list, we won't have computed any conversion sequence. 4815 // Introduce the identity conversion sequence. 4816 if (From->getNumInits() == 0) { 4817 Result.setStandard(); 4818 Result.Standard.setAsIdentityConversion(); 4819 Result.Standard.setFromType(ToType); 4820 Result.Standard.setAllToTypes(ToType); 4821 } 4822 4823 Result.setStdInitializerListElement(toStdInitializerList); 4824 return Result; 4825 } 4826 4827 // C++14 [over.ics.list]p4: 4828 // C++11 [over.ics.list]p3: 4829 // Otherwise, if the parameter is a non-aggregate class X and overload 4830 // resolution chooses a single best constructor [...] the implicit 4831 // conversion sequence is a user-defined conversion sequence. If multiple 4832 // constructors are viable but none is better than the others, the 4833 // implicit conversion sequence is a user-defined conversion sequence. 4834 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4835 // This function can deal with initializer lists. 4836 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4837 /*AllowExplicit=*/false, 4838 InOverloadResolution, /*CStyle=*/false, 4839 AllowObjCWritebackConversion, 4840 /*AllowObjCConversionOnExplicit=*/false); 4841 } 4842 4843 // C++14 [over.ics.list]p5: 4844 // C++11 [over.ics.list]p4: 4845 // Otherwise, if the parameter has an aggregate type which can be 4846 // initialized from the initializer list [...] the implicit conversion 4847 // sequence is a user-defined conversion sequence. 4848 if (ToType->isAggregateType()) { 4849 // Type is an aggregate, argument is an init list. At this point it comes 4850 // down to checking whether the initialization works. 4851 // FIXME: Find out whether this parameter is consumed or not. 4852 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4853 // need to call into the initialization code here; overload resolution 4854 // should not be doing that. 4855 InitializedEntity Entity = 4856 InitializedEntity::InitializeParameter(S.Context, ToType, 4857 /*Consumed=*/false); 4858 if (S.CanPerformCopyInitialization(Entity, From)) { 4859 Result.setUserDefined(); 4860 Result.UserDefined.Before.setAsIdentityConversion(); 4861 // Initializer lists don't have a type. 4862 Result.UserDefined.Before.setFromType(QualType()); 4863 Result.UserDefined.Before.setAllToTypes(QualType()); 4864 4865 Result.UserDefined.After.setAsIdentityConversion(); 4866 Result.UserDefined.After.setFromType(ToType); 4867 Result.UserDefined.After.setAllToTypes(ToType); 4868 Result.UserDefined.ConversionFunction = nullptr; 4869 } 4870 return Result; 4871 } 4872 4873 // C++14 [over.ics.list]p6: 4874 // C++11 [over.ics.list]p5: 4875 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4876 if (ToType->isReferenceType()) { 4877 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4878 // mention initializer lists in any way. So we go by what list- 4879 // initialization would do and try to extrapolate from that. 4880 4881 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4882 4883 // If the initializer list has a single element that is reference-related 4884 // to the parameter type, we initialize the reference from that. 4885 if (From->getNumInits() == 1) { 4886 Expr *Init = From->getInit(0); 4887 4888 QualType T2 = Init->getType(); 4889 4890 // If the initializer is the address of an overloaded function, try 4891 // to resolve the overloaded function. If all goes well, T2 is the 4892 // type of the resulting function. 4893 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4894 DeclAccessPair Found; 4895 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4896 Init, ToType, false, Found)) 4897 T2 = Fn->getType(); 4898 } 4899 4900 // Compute some basic properties of the types and the initializer. 4901 bool dummy1 = false; 4902 bool dummy2 = false; 4903 bool dummy3 = false; 4904 Sema::ReferenceCompareResult RefRelationship 4905 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4906 dummy2, dummy3); 4907 4908 if (RefRelationship >= Sema::Ref_Related) { 4909 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4910 SuppressUserConversions, 4911 /*AllowExplicit=*/false); 4912 } 4913 } 4914 4915 // Otherwise, we bind the reference to a temporary created from the 4916 // initializer list. 4917 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4918 InOverloadResolution, 4919 AllowObjCWritebackConversion); 4920 if (Result.isFailure()) 4921 return Result; 4922 assert(!Result.isEllipsis() && 4923 "Sub-initialization cannot result in ellipsis conversion."); 4924 4925 // Can we even bind to a temporary? 4926 if (ToType->isRValueReferenceType() || 4927 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4928 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4929 Result.UserDefined.After; 4930 SCS.ReferenceBinding = true; 4931 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4932 SCS.BindsToRvalue = true; 4933 SCS.BindsToFunctionLvalue = false; 4934 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4935 SCS.ObjCLifetimeConversionBinding = false; 4936 } else 4937 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4938 From, ToType); 4939 return Result; 4940 } 4941 4942 // C++14 [over.ics.list]p7: 4943 // C++11 [over.ics.list]p6: 4944 // Otherwise, if the parameter type is not a class: 4945 if (!ToType->isRecordType()) { 4946 // - if the initializer list has one element that is not itself an 4947 // initializer list, the implicit conversion sequence is the one 4948 // required to convert the element to the parameter type. 4949 unsigned NumInits = From->getNumInits(); 4950 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4951 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4952 SuppressUserConversions, 4953 InOverloadResolution, 4954 AllowObjCWritebackConversion); 4955 // - if the initializer list has no elements, the implicit conversion 4956 // sequence is the identity conversion. 4957 else if (NumInits == 0) { 4958 Result.setStandard(); 4959 Result.Standard.setAsIdentityConversion(); 4960 Result.Standard.setFromType(ToType); 4961 Result.Standard.setAllToTypes(ToType); 4962 } 4963 return Result; 4964 } 4965 4966 // C++14 [over.ics.list]p8: 4967 // C++11 [over.ics.list]p7: 4968 // In all cases other than those enumerated above, no conversion is possible 4969 return Result; 4970 } 4971 4972 /// TryCopyInitialization - Try to copy-initialize a value of type 4973 /// ToType from the expression From. Return the implicit conversion 4974 /// sequence required to pass this argument, which may be a bad 4975 /// conversion sequence (meaning that the argument cannot be passed to 4976 /// a parameter of this type). If @p SuppressUserConversions, then we 4977 /// do not permit any user-defined conversion sequences. 4978 static ImplicitConversionSequence 4979 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4980 bool SuppressUserConversions, 4981 bool InOverloadResolution, 4982 bool AllowObjCWritebackConversion, 4983 bool AllowExplicit) { 4984 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4985 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4986 InOverloadResolution,AllowObjCWritebackConversion); 4987 4988 if (ToType->isReferenceType()) 4989 return TryReferenceInit(S, From, ToType, 4990 /*FIXME:*/From->getLocStart(), 4991 SuppressUserConversions, 4992 AllowExplicit); 4993 4994 return TryImplicitConversion(S, From, ToType, 4995 SuppressUserConversions, 4996 /*AllowExplicit=*/false, 4997 InOverloadResolution, 4998 /*CStyle=*/false, 4999 AllowObjCWritebackConversion, 5000 /*AllowObjCConversionOnExplicit=*/false); 5001 } 5002 5003 static bool TryCopyInitialization(const CanQualType FromQTy, 5004 const CanQualType ToQTy, 5005 Sema &S, 5006 SourceLocation Loc, 5007 ExprValueKind FromVK) { 5008 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5009 ImplicitConversionSequence ICS = 5010 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5011 5012 return !ICS.isBad(); 5013 } 5014 5015 /// TryObjectArgumentInitialization - Try to initialize the object 5016 /// parameter of the given member function (@c Method) from the 5017 /// expression @p From. 5018 static ImplicitConversionSequence 5019 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5020 Expr::Classification FromClassification, 5021 CXXMethodDecl *Method, 5022 CXXRecordDecl *ActingContext) { 5023 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5024 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5025 // const volatile object. 5026 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 5027 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 5028 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 5029 5030 // Set up the conversion sequence as a "bad" conversion, to allow us 5031 // to exit early. 5032 ImplicitConversionSequence ICS; 5033 5034 // We need to have an object of class type. 5035 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5036 FromType = PT->getPointeeType(); 5037 5038 // When we had a pointer, it's implicitly dereferenced, so we 5039 // better have an lvalue. 5040 assert(FromClassification.isLValue()); 5041 } 5042 5043 assert(FromType->isRecordType()); 5044 5045 // C++0x [over.match.funcs]p4: 5046 // For non-static member functions, the type of the implicit object 5047 // parameter is 5048 // 5049 // - "lvalue reference to cv X" for functions declared without a 5050 // ref-qualifier or with the & ref-qualifier 5051 // - "rvalue reference to cv X" for functions declared with the && 5052 // ref-qualifier 5053 // 5054 // where X is the class of which the function is a member and cv is the 5055 // cv-qualification on the member function declaration. 5056 // 5057 // However, when finding an implicit conversion sequence for the argument, we 5058 // are not allowed to perform user-defined conversions 5059 // (C++ [over.match.funcs]p5). We perform a simplified version of 5060 // reference binding here, that allows class rvalues to bind to 5061 // non-constant references. 5062 5063 // First check the qualifiers. 5064 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5065 if (ImplicitParamType.getCVRQualifiers() 5066 != FromTypeCanon.getLocalCVRQualifiers() && 5067 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5068 ICS.setBad(BadConversionSequence::bad_qualifiers, 5069 FromType, ImplicitParamType); 5070 return ICS; 5071 } 5072 5073 // Check that we have either the same type or a derived type. It 5074 // affects the conversion rank. 5075 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5076 ImplicitConversionKind SecondKind; 5077 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5078 SecondKind = ICK_Identity; 5079 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5080 SecondKind = ICK_Derived_To_Base; 5081 else { 5082 ICS.setBad(BadConversionSequence::unrelated_class, 5083 FromType, ImplicitParamType); 5084 return ICS; 5085 } 5086 5087 // Check the ref-qualifier. 5088 switch (Method->getRefQualifier()) { 5089 case RQ_None: 5090 // Do nothing; we don't care about lvalueness or rvalueness. 5091 break; 5092 5093 case RQ_LValue: 5094 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5095 // non-const lvalue reference cannot bind to an rvalue 5096 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5097 ImplicitParamType); 5098 return ICS; 5099 } 5100 break; 5101 5102 case RQ_RValue: 5103 if (!FromClassification.isRValue()) { 5104 // rvalue reference cannot bind to an lvalue 5105 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5106 ImplicitParamType); 5107 return ICS; 5108 } 5109 break; 5110 } 5111 5112 // Success. Mark this as a reference binding. 5113 ICS.setStandard(); 5114 ICS.Standard.setAsIdentityConversion(); 5115 ICS.Standard.Second = SecondKind; 5116 ICS.Standard.setFromType(FromType); 5117 ICS.Standard.setAllToTypes(ImplicitParamType); 5118 ICS.Standard.ReferenceBinding = true; 5119 ICS.Standard.DirectBinding = true; 5120 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5121 ICS.Standard.BindsToFunctionLvalue = false; 5122 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5123 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5124 = (Method->getRefQualifier() == RQ_None); 5125 return ICS; 5126 } 5127 5128 /// PerformObjectArgumentInitialization - Perform initialization of 5129 /// the implicit object parameter for the given Method with the given 5130 /// expression. 5131 ExprResult 5132 Sema::PerformObjectArgumentInitialization(Expr *From, 5133 NestedNameSpecifier *Qualifier, 5134 NamedDecl *FoundDecl, 5135 CXXMethodDecl *Method) { 5136 QualType FromRecordType, DestType; 5137 QualType ImplicitParamRecordType = 5138 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5139 5140 Expr::Classification FromClassification; 5141 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5142 FromRecordType = PT->getPointeeType(); 5143 DestType = Method->getThisType(Context); 5144 FromClassification = Expr::Classification::makeSimpleLValue(); 5145 } else { 5146 FromRecordType = From->getType(); 5147 DestType = ImplicitParamRecordType; 5148 FromClassification = From->Classify(Context); 5149 } 5150 5151 // Note that we always use the true parent context when performing 5152 // the actual argument initialization. 5153 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5154 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5155 Method->getParent()); 5156 if (ICS.isBad()) { 5157 switch (ICS.Bad.Kind) { 5158 case BadConversionSequence::bad_qualifiers: { 5159 Qualifiers FromQs = FromRecordType.getQualifiers(); 5160 Qualifiers ToQs = DestType.getQualifiers(); 5161 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5162 if (CVR) { 5163 Diag(From->getLocStart(), 5164 diag::err_member_function_call_bad_cvr) 5165 << Method->getDeclName() << FromRecordType << (CVR - 1) 5166 << From->getSourceRange(); 5167 Diag(Method->getLocation(), diag::note_previous_decl) 5168 << Method->getDeclName(); 5169 return ExprError(); 5170 } 5171 break; 5172 } 5173 5174 case BadConversionSequence::lvalue_ref_to_rvalue: 5175 case BadConversionSequence::rvalue_ref_to_lvalue: { 5176 bool IsRValueQualified = 5177 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5178 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref) 5179 << Method->getDeclName() << FromClassification.isRValue() 5180 << IsRValueQualified; 5181 Diag(Method->getLocation(), diag::note_previous_decl) 5182 << Method->getDeclName(); 5183 return ExprError(); 5184 } 5185 5186 case BadConversionSequence::no_conversion: 5187 case BadConversionSequence::unrelated_class: 5188 break; 5189 } 5190 5191 return Diag(From->getLocStart(), 5192 diag::err_member_function_call_bad_type) 5193 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5194 } 5195 5196 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5197 ExprResult FromRes = 5198 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5199 if (FromRes.isInvalid()) 5200 return ExprError(); 5201 From = FromRes.get(); 5202 } 5203 5204 if (!Context.hasSameType(From->getType(), DestType)) 5205 From = ImpCastExprToType(From, DestType, CK_NoOp, 5206 From->getValueKind()).get(); 5207 return From; 5208 } 5209 5210 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5211 /// expression From to bool (C++0x [conv]p3). 5212 static ImplicitConversionSequence 5213 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5214 return TryImplicitConversion(S, From, S.Context.BoolTy, 5215 /*SuppressUserConversions=*/false, 5216 /*AllowExplicit=*/true, 5217 /*InOverloadResolution=*/false, 5218 /*CStyle=*/false, 5219 /*AllowObjCWritebackConversion=*/false, 5220 /*AllowObjCConversionOnExplicit=*/false); 5221 } 5222 5223 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5224 /// of the expression From to bool (C++0x [conv]p3). 5225 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5226 if (checkPlaceholderForOverload(*this, From)) 5227 return ExprError(); 5228 5229 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5230 if (!ICS.isBad()) 5231 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5232 5233 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5234 return Diag(From->getLocStart(), 5235 diag::err_typecheck_bool_condition) 5236 << From->getType() << From->getSourceRange(); 5237 return ExprError(); 5238 } 5239 5240 /// Check that the specified conversion is permitted in a converted constant 5241 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5242 /// is acceptable. 5243 static bool CheckConvertedConstantConversions(Sema &S, 5244 StandardConversionSequence &SCS) { 5245 // Since we know that the target type is an integral or unscoped enumeration 5246 // type, most conversion kinds are impossible. All possible First and Third 5247 // conversions are fine. 5248 switch (SCS.Second) { 5249 case ICK_Identity: 5250 case ICK_Function_Conversion: 5251 case ICK_Integral_Promotion: 5252 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5253 case ICK_Zero_Queue_Conversion: 5254 return true; 5255 5256 case ICK_Boolean_Conversion: 5257 // Conversion from an integral or unscoped enumeration type to bool is 5258 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5259 // conversion, so we allow it in a converted constant expression. 5260 // 5261 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5262 // a lot of popular code. We should at least add a warning for this 5263 // (non-conforming) extension. 5264 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5265 SCS.getToType(2)->isBooleanType(); 5266 5267 case ICK_Pointer_Conversion: 5268 case ICK_Pointer_Member: 5269 // C++1z: null pointer conversions and null member pointer conversions are 5270 // only permitted if the source type is std::nullptr_t. 5271 return SCS.getFromType()->isNullPtrType(); 5272 5273 case ICK_Floating_Promotion: 5274 case ICK_Complex_Promotion: 5275 case ICK_Floating_Conversion: 5276 case ICK_Complex_Conversion: 5277 case ICK_Floating_Integral: 5278 case ICK_Compatible_Conversion: 5279 case ICK_Derived_To_Base: 5280 case ICK_Vector_Conversion: 5281 case ICK_Vector_Splat: 5282 case ICK_Complex_Real: 5283 case ICK_Block_Pointer_Conversion: 5284 case ICK_TransparentUnionConversion: 5285 case ICK_Writeback_Conversion: 5286 case ICK_Zero_Event_Conversion: 5287 case ICK_C_Only_Conversion: 5288 case ICK_Incompatible_Pointer_Conversion: 5289 return false; 5290 5291 case ICK_Lvalue_To_Rvalue: 5292 case ICK_Array_To_Pointer: 5293 case ICK_Function_To_Pointer: 5294 llvm_unreachable("found a first conversion kind in Second"); 5295 5296 case ICK_Qualification: 5297 llvm_unreachable("found a third conversion kind in Second"); 5298 5299 case ICK_Num_Conversion_Kinds: 5300 break; 5301 } 5302 5303 llvm_unreachable("unknown conversion kind"); 5304 } 5305 5306 /// CheckConvertedConstantExpression - Check that the expression From is a 5307 /// converted constant expression of type T, perform the conversion and produce 5308 /// the converted expression, per C++11 [expr.const]p3. 5309 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5310 QualType T, APValue &Value, 5311 Sema::CCEKind CCE, 5312 bool RequireInt) { 5313 assert(S.getLangOpts().CPlusPlus11 && 5314 "converted constant expression outside C++11"); 5315 5316 if (checkPlaceholderForOverload(S, From)) 5317 return ExprError(); 5318 5319 // C++1z [expr.const]p3: 5320 // A converted constant expression of type T is an expression, 5321 // implicitly converted to type T, where the converted 5322 // expression is a constant expression and the implicit conversion 5323 // sequence contains only [... list of conversions ...]. 5324 // C++1z [stmt.if]p2: 5325 // If the if statement is of the form if constexpr, the value of the 5326 // condition shall be a contextually converted constant expression of type 5327 // bool. 5328 ImplicitConversionSequence ICS = 5329 CCE == Sema::CCEK_ConstexprIf 5330 ? TryContextuallyConvertToBool(S, From) 5331 : TryCopyInitialization(S, From, T, 5332 /*SuppressUserConversions=*/false, 5333 /*InOverloadResolution=*/false, 5334 /*AllowObjcWritebackConversion=*/false, 5335 /*AllowExplicit=*/false); 5336 StandardConversionSequence *SCS = nullptr; 5337 switch (ICS.getKind()) { 5338 case ImplicitConversionSequence::StandardConversion: 5339 SCS = &ICS.Standard; 5340 break; 5341 case ImplicitConversionSequence::UserDefinedConversion: 5342 // We are converting to a non-class type, so the Before sequence 5343 // must be trivial. 5344 SCS = &ICS.UserDefined.After; 5345 break; 5346 case ImplicitConversionSequence::AmbiguousConversion: 5347 case ImplicitConversionSequence::BadConversion: 5348 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5349 return S.Diag(From->getLocStart(), 5350 diag::err_typecheck_converted_constant_expression) 5351 << From->getType() << From->getSourceRange() << T; 5352 return ExprError(); 5353 5354 case ImplicitConversionSequence::EllipsisConversion: 5355 llvm_unreachable("ellipsis conversion in converted constant expression"); 5356 } 5357 5358 // Check that we would only use permitted conversions. 5359 if (!CheckConvertedConstantConversions(S, *SCS)) { 5360 return S.Diag(From->getLocStart(), 5361 diag::err_typecheck_converted_constant_expression_disallowed) 5362 << From->getType() << From->getSourceRange() << T; 5363 } 5364 // [...] and where the reference binding (if any) binds directly. 5365 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5366 return S.Diag(From->getLocStart(), 5367 diag::err_typecheck_converted_constant_expression_indirect) 5368 << From->getType() << From->getSourceRange() << T; 5369 } 5370 5371 ExprResult Result = 5372 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5373 if (Result.isInvalid()) 5374 return Result; 5375 5376 // Check for a narrowing implicit conversion. 5377 APValue PreNarrowingValue; 5378 QualType PreNarrowingType; 5379 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5380 PreNarrowingType)) { 5381 case NK_Dependent_Narrowing: 5382 // Implicit conversion to a narrower type, but the expression is 5383 // value-dependent so we can't tell whether it's actually narrowing. 5384 case NK_Variable_Narrowing: 5385 // Implicit conversion to a narrower type, and the value is not a constant 5386 // expression. We'll diagnose this in a moment. 5387 case NK_Not_Narrowing: 5388 break; 5389 5390 case NK_Constant_Narrowing: 5391 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5392 << CCE << /*Constant*/1 5393 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5394 break; 5395 5396 case NK_Type_Narrowing: 5397 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5398 << CCE << /*Constant*/0 << From->getType() << T; 5399 break; 5400 } 5401 5402 if (Result.get()->isValueDependent()) { 5403 Value = APValue(); 5404 return Result; 5405 } 5406 5407 // Check the expression is a constant expression. 5408 SmallVector<PartialDiagnosticAt, 8> Notes; 5409 Expr::EvalResult Eval; 5410 Eval.Diag = &Notes; 5411 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5412 ? Expr::EvaluateForMangling 5413 : Expr::EvaluateForCodeGen; 5414 5415 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5416 (RequireInt && !Eval.Val.isInt())) { 5417 // The expression can't be folded, so we can't keep it at this position in 5418 // the AST. 5419 Result = ExprError(); 5420 } else { 5421 Value = Eval.Val; 5422 5423 if (Notes.empty()) { 5424 // It's a constant expression. 5425 return Result; 5426 } 5427 } 5428 5429 // It's not a constant expression. Produce an appropriate diagnostic. 5430 if (Notes.size() == 1 && 5431 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5432 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5433 else { 5434 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5435 << CCE << From->getSourceRange(); 5436 for (unsigned I = 0; I < Notes.size(); ++I) 5437 S.Diag(Notes[I].first, Notes[I].second); 5438 } 5439 return ExprError(); 5440 } 5441 5442 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5443 APValue &Value, CCEKind CCE) { 5444 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5445 } 5446 5447 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5448 llvm::APSInt &Value, 5449 CCEKind CCE) { 5450 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5451 5452 APValue V; 5453 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5454 if (!R.isInvalid() && !R.get()->isValueDependent()) 5455 Value = V.getInt(); 5456 return R; 5457 } 5458 5459 5460 /// dropPointerConversions - If the given standard conversion sequence 5461 /// involves any pointer conversions, remove them. This may change 5462 /// the result type of the conversion sequence. 5463 static void dropPointerConversion(StandardConversionSequence &SCS) { 5464 if (SCS.Second == ICK_Pointer_Conversion) { 5465 SCS.Second = ICK_Identity; 5466 SCS.Third = ICK_Identity; 5467 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5468 } 5469 } 5470 5471 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5472 /// convert the expression From to an Objective-C pointer type. 5473 static ImplicitConversionSequence 5474 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5475 // Do an implicit conversion to 'id'. 5476 QualType Ty = S.Context.getObjCIdType(); 5477 ImplicitConversionSequence ICS 5478 = TryImplicitConversion(S, From, Ty, 5479 // FIXME: Are these flags correct? 5480 /*SuppressUserConversions=*/false, 5481 /*AllowExplicit=*/true, 5482 /*InOverloadResolution=*/false, 5483 /*CStyle=*/false, 5484 /*AllowObjCWritebackConversion=*/false, 5485 /*AllowObjCConversionOnExplicit=*/true); 5486 5487 // Strip off any final conversions to 'id'. 5488 switch (ICS.getKind()) { 5489 case ImplicitConversionSequence::BadConversion: 5490 case ImplicitConversionSequence::AmbiguousConversion: 5491 case ImplicitConversionSequence::EllipsisConversion: 5492 break; 5493 5494 case ImplicitConversionSequence::UserDefinedConversion: 5495 dropPointerConversion(ICS.UserDefined.After); 5496 break; 5497 5498 case ImplicitConversionSequence::StandardConversion: 5499 dropPointerConversion(ICS.Standard); 5500 break; 5501 } 5502 5503 return ICS; 5504 } 5505 5506 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5507 /// conversion of the expression From to an Objective-C pointer type. 5508 /// Returns a valid but null ExprResult if no conversion sequence exists. 5509 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5510 if (checkPlaceholderForOverload(*this, From)) 5511 return ExprError(); 5512 5513 QualType Ty = Context.getObjCIdType(); 5514 ImplicitConversionSequence ICS = 5515 TryContextuallyConvertToObjCPointer(*this, From); 5516 if (!ICS.isBad()) 5517 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5518 return ExprResult(); 5519 } 5520 5521 /// Determine whether the provided type is an integral type, or an enumeration 5522 /// type of a permitted flavor. 5523 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5524 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5525 : T->isIntegralOrUnscopedEnumerationType(); 5526 } 5527 5528 static ExprResult 5529 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5530 Sema::ContextualImplicitConverter &Converter, 5531 QualType T, UnresolvedSetImpl &ViableConversions) { 5532 5533 if (Converter.Suppress) 5534 return ExprError(); 5535 5536 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5537 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5538 CXXConversionDecl *Conv = 5539 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5540 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5541 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5542 } 5543 return From; 5544 } 5545 5546 static bool 5547 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5548 Sema::ContextualImplicitConverter &Converter, 5549 QualType T, bool HadMultipleCandidates, 5550 UnresolvedSetImpl &ExplicitConversions) { 5551 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5552 DeclAccessPair Found = ExplicitConversions[0]; 5553 CXXConversionDecl *Conversion = 5554 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5555 5556 // The user probably meant to invoke the given explicit 5557 // conversion; use it. 5558 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5559 std::string TypeStr; 5560 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5561 5562 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5563 << FixItHint::CreateInsertion(From->getLocStart(), 5564 "static_cast<" + TypeStr + ">(") 5565 << FixItHint::CreateInsertion( 5566 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5567 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5568 5569 // If we aren't in a SFINAE context, build a call to the 5570 // explicit conversion function. 5571 if (SemaRef.isSFINAEContext()) 5572 return true; 5573 5574 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5575 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5576 HadMultipleCandidates); 5577 if (Result.isInvalid()) 5578 return true; 5579 // Record usage of conversion in an implicit cast. 5580 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5581 CK_UserDefinedConversion, Result.get(), 5582 nullptr, Result.get()->getValueKind()); 5583 } 5584 return false; 5585 } 5586 5587 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5588 Sema::ContextualImplicitConverter &Converter, 5589 QualType T, bool HadMultipleCandidates, 5590 DeclAccessPair &Found) { 5591 CXXConversionDecl *Conversion = 5592 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5593 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5594 5595 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5596 if (!Converter.SuppressConversion) { 5597 if (SemaRef.isSFINAEContext()) 5598 return true; 5599 5600 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5601 << From->getSourceRange(); 5602 } 5603 5604 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5605 HadMultipleCandidates); 5606 if (Result.isInvalid()) 5607 return true; 5608 // Record usage of conversion in an implicit cast. 5609 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5610 CK_UserDefinedConversion, Result.get(), 5611 nullptr, Result.get()->getValueKind()); 5612 return false; 5613 } 5614 5615 static ExprResult finishContextualImplicitConversion( 5616 Sema &SemaRef, SourceLocation Loc, Expr *From, 5617 Sema::ContextualImplicitConverter &Converter) { 5618 if (!Converter.match(From->getType()) && !Converter.Suppress) 5619 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5620 << From->getSourceRange(); 5621 5622 return SemaRef.DefaultLvalueConversion(From); 5623 } 5624 5625 static void 5626 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5627 UnresolvedSetImpl &ViableConversions, 5628 OverloadCandidateSet &CandidateSet) { 5629 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5630 DeclAccessPair FoundDecl = ViableConversions[I]; 5631 NamedDecl *D = FoundDecl.getDecl(); 5632 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5633 if (isa<UsingShadowDecl>(D)) 5634 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5635 5636 CXXConversionDecl *Conv; 5637 FunctionTemplateDecl *ConvTemplate; 5638 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5639 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5640 else 5641 Conv = cast<CXXConversionDecl>(D); 5642 5643 if (ConvTemplate) 5644 SemaRef.AddTemplateConversionCandidate( 5645 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5646 /*AllowObjCConversionOnExplicit=*/false); 5647 else 5648 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5649 ToType, CandidateSet, 5650 /*AllowObjCConversionOnExplicit=*/false); 5651 } 5652 } 5653 5654 /// Attempt to convert the given expression to a type which is accepted 5655 /// by the given converter. 5656 /// 5657 /// This routine will attempt to convert an expression of class type to a 5658 /// type accepted by the specified converter. In C++11 and before, the class 5659 /// must have a single non-explicit conversion function converting to a matching 5660 /// type. In C++1y, there can be multiple such conversion functions, but only 5661 /// one target type. 5662 /// 5663 /// \param Loc The source location of the construct that requires the 5664 /// conversion. 5665 /// 5666 /// \param From The expression we're converting from. 5667 /// 5668 /// \param Converter Used to control and diagnose the conversion process. 5669 /// 5670 /// \returns The expression, converted to an integral or enumeration type if 5671 /// successful. 5672 ExprResult Sema::PerformContextualImplicitConversion( 5673 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5674 // We can't perform any more checking for type-dependent expressions. 5675 if (From->isTypeDependent()) 5676 return From; 5677 5678 // Process placeholders immediately. 5679 if (From->hasPlaceholderType()) { 5680 ExprResult result = CheckPlaceholderExpr(From); 5681 if (result.isInvalid()) 5682 return result; 5683 From = result.get(); 5684 } 5685 5686 // If the expression already has a matching type, we're golden. 5687 QualType T = From->getType(); 5688 if (Converter.match(T)) 5689 return DefaultLvalueConversion(From); 5690 5691 // FIXME: Check for missing '()' if T is a function type? 5692 5693 // We can only perform contextual implicit conversions on objects of class 5694 // type. 5695 const RecordType *RecordTy = T->getAs<RecordType>(); 5696 if (!RecordTy || !getLangOpts().CPlusPlus) { 5697 if (!Converter.Suppress) 5698 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5699 return From; 5700 } 5701 5702 // We must have a complete class type. 5703 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5704 ContextualImplicitConverter &Converter; 5705 Expr *From; 5706 5707 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5708 : Converter(Converter), From(From) {} 5709 5710 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5711 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5712 } 5713 } IncompleteDiagnoser(Converter, From); 5714 5715 if (Converter.Suppress ? !isCompleteType(Loc, T) 5716 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5717 return From; 5718 5719 // Look for a conversion to an integral or enumeration type. 5720 UnresolvedSet<4> 5721 ViableConversions; // These are *potentially* viable in C++1y. 5722 UnresolvedSet<4> ExplicitConversions; 5723 const auto &Conversions = 5724 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5725 5726 bool HadMultipleCandidates = 5727 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5728 5729 // To check that there is only one target type, in C++1y: 5730 QualType ToType; 5731 bool HasUniqueTargetType = true; 5732 5733 // Collect explicit or viable (potentially in C++1y) conversions. 5734 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5735 NamedDecl *D = (*I)->getUnderlyingDecl(); 5736 CXXConversionDecl *Conversion; 5737 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5738 if (ConvTemplate) { 5739 if (getLangOpts().CPlusPlus14) 5740 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5741 else 5742 continue; // C++11 does not consider conversion operator templates(?). 5743 } else 5744 Conversion = cast<CXXConversionDecl>(D); 5745 5746 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5747 "Conversion operator templates are considered potentially " 5748 "viable in C++1y"); 5749 5750 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5751 if (Converter.match(CurToType) || ConvTemplate) { 5752 5753 if (Conversion->isExplicit()) { 5754 // FIXME: For C++1y, do we need this restriction? 5755 // cf. diagnoseNoViableConversion() 5756 if (!ConvTemplate) 5757 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5758 } else { 5759 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5760 if (ToType.isNull()) 5761 ToType = CurToType.getUnqualifiedType(); 5762 else if (HasUniqueTargetType && 5763 (CurToType.getUnqualifiedType() != ToType)) 5764 HasUniqueTargetType = false; 5765 } 5766 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5767 } 5768 } 5769 } 5770 5771 if (getLangOpts().CPlusPlus14) { 5772 // C++1y [conv]p6: 5773 // ... An expression e of class type E appearing in such a context 5774 // is said to be contextually implicitly converted to a specified 5775 // type T and is well-formed if and only if e can be implicitly 5776 // converted to a type T that is determined as follows: E is searched 5777 // for conversion functions whose return type is cv T or reference to 5778 // cv T such that T is allowed by the context. There shall be 5779 // exactly one such T. 5780 5781 // If no unique T is found: 5782 if (ToType.isNull()) { 5783 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5784 HadMultipleCandidates, 5785 ExplicitConversions)) 5786 return ExprError(); 5787 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5788 } 5789 5790 // If more than one unique Ts are found: 5791 if (!HasUniqueTargetType) 5792 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5793 ViableConversions); 5794 5795 // If one unique T is found: 5796 // First, build a candidate set from the previously recorded 5797 // potentially viable conversions. 5798 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5799 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5800 CandidateSet); 5801 5802 // Then, perform overload resolution over the candidate set. 5803 OverloadCandidateSet::iterator Best; 5804 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5805 case OR_Success: { 5806 // Apply this conversion. 5807 DeclAccessPair Found = 5808 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5809 if (recordConversion(*this, Loc, From, Converter, T, 5810 HadMultipleCandidates, Found)) 5811 return ExprError(); 5812 break; 5813 } 5814 case OR_Ambiguous: 5815 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5816 ViableConversions); 5817 case OR_No_Viable_Function: 5818 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5819 HadMultipleCandidates, 5820 ExplicitConversions)) 5821 return ExprError(); 5822 LLVM_FALLTHROUGH; 5823 case OR_Deleted: 5824 // We'll complain below about a non-integral condition type. 5825 break; 5826 } 5827 } else { 5828 switch (ViableConversions.size()) { 5829 case 0: { 5830 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5831 HadMultipleCandidates, 5832 ExplicitConversions)) 5833 return ExprError(); 5834 5835 // We'll complain below about a non-integral condition type. 5836 break; 5837 } 5838 case 1: { 5839 // Apply this conversion. 5840 DeclAccessPair Found = ViableConversions[0]; 5841 if (recordConversion(*this, Loc, From, Converter, T, 5842 HadMultipleCandidates, Found)) 5843 return ExprError(); 5844 break; 5845 } 5846 default: 5847 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5848 ViableConversions); 5849 } 5850 } 5851 5852 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5853 } 5854 5855 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5856 /// an acceptable non-member overloaded operator for a call whose 5857 /// arguments have types T1 (and, if non-empty, T2). This routine 5858 /// implements the check in C++ [over.match.oper]p3b2 concerning 5859 /// enumeration types. 5860 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5861 FunctionDecl *Fn, 5862 ArrayRef<Expr *> Args) { 5863 QualType T1 = Args[0]->getType(); 5864 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5865 5866 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5867 return true; 5868 5869 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5870 return true; 5871 5872 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5873 if (Proto->getNumParams() < 1) 5874 return false; 5875 5876 if (T1->isEnumeralType()) { 5877 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5878 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5879 return true; 5880 } 5881 5882 if (Proto->getNumParams() < 2) 5883 return false; 5884 5885 if (!T2.isNull() && T2->isEnumeralType()) { 5886 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5887 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5888 return true; 5889 } 5890 5891 return false; 5892 } 5893 5894 /// AddOverloadCandidate - Adds the given function to the set of 5895 /// candidate functions, using the given function call arguments. If 5896 /// @p SuppressUserConversions, then don't allow user-defined 5897 /// conversions via constructors or conversion operators. 5898 /// 5899 /// \param PartialOverloading true if we are performing "partial" overloading 5900 /// based on an incomplete set of function arguments. This feature is used by 5901 /// code completion. 5902 void 5903 Sema::AddOverloadCandidate(FunctionDecl *Function, 5904 DeclAccessPair FoundDecl, 5905 ArrayRef<Expr *> Args, 5906 OverloadCandidateSet &CandidateSet, 5907 bool SuppressUserConversions, 5908 bool PartialOverloading, 5909 bool AllowExplicit, 5910 ConversionSequenceList EarlyConversions) { 5911 const FunctionProtoType *Proto 5912 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5913 assert(Proto && "Functions without a prototype cannot be overloaded"); 5914 assert(!Function->getDescribedFunctionTemplate() && 5915 "Use AddTemplateOverloadCandidate for function templates"); 5916 5917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5918 if (!isa<CXXConstructorDecl>(Method)) { 5919 // If we get here, it's because we're calling a member function 5920 // that is named without a member access expression (e.g., 5921 // "this->f") that was either written explicitly or created 5922 // implicitly. This can happen with a qualified call to a member 5923 // function, e.g., X::f(). We use an empty type for the implied 5924 // object argument (C++ [over.call.func]p3), and the acting context 5925 // is irrelevant. 5926 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5927 Expr::Classification::makeSimpleLValue(), Args, 5928 CandidateSet, SuppressUserConversions, 5929 PartialOverloading, EarlyConversions); 5930 return; 5931 } 5932 // We treat a constructor like a non-member function, since its object 5933 // argument doesn't participate in overload resolution. 5934 } 5935 5936 if (!CandidateSet.isNewCandidate(Function)) 5937 return; 5938 5939 // C++ [over.match.oper]p3: 5940 // if no operand has a class type, only those non-member functions in the 5941 // lookup set that have a first parameter of type T1 or "reference to 5942 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5943 // is a right operand) a second parameter of type T2 or "reference to 5944 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5945 // candidate functions. 5946 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5947 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5948 return; 5949 5950 // C++11 [class.copy]p11: [DR1402] 5951 // A defaulted move constructor that is defined as deleted is ignored by 5952 // overload resolution. 5953 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5954 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5955 Constructor->isMoveConstructor()) 5956 return; 5957 5958 // Overload resolution is always an unevaluated context. 5959 EnterExpressionEvaluationContext Unevaluated( 5960 *this, Sema::ExpressionEvaluationContext::Unevaluated); 5961 5962 // Add this candidate 5963 OverloadCandidate &Candidate = 5964 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5965 Candidate.FoundDecl = FoundDecl; 5966 Candidate.Function = Function; 5967 Candidate.Viable = true; 5968 Candidate.IsSurrogate = false; 5969 Candidate.IgnoreObjectArgument = false; 5970 Candidate.ExplicitCallArguments = Args.size(); 5971 5972 if (Function->isMultiVersion() && 5973 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 5974 Candidate.Viable = false; 5975 Candidate.FailureKind = ovl_non_default_multiversion_function; 5976 return; 5977 } 5978 5979 if (Constructor) { 5980 // C++ [class.copy]p3: 5981 // A member function template is never instantiated to perform the copy 5982 // of a class object to an object of its class type. 5983 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5984 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5985 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5986 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5987 ClassType))) { 5988 Candidate.Viable = false; 5989 Candidate.FailureKind = ovl_fail_illegal_constructor; 5990 return; 5991 } 5992 5993 // C++ [over.match.funcs]p8: (proposed DR resolution) 5994 // A constructor inherited from class type C that has a first parameter 5995 // of type "reference to P" (including such a constructor instantiated 5996 // from a template) is excluded from the set of candidate functions when 5997 // constructing an object of type cv D if the argument list has exactly 5998 // one argument and D is reference-related to P and P is reference-related 5999 // to C. 6000 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6001 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6002 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6003 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6004 QualType C = Context.getRecordType(Constructor->getParent()); 6005 QualType D = Context.getRecordType(Shadow->getParent()); 6006 SourceLocation Loc = Args.front()->getExprLoc(); 6007 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6008 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6009 Candidate.Viable = false; 6010 Candidate.FailureKind = ovl_fail_inhctor_slice; 6011 return; 6012 } 6013 } 6014 } 6015 6016 unsigned NumParams = Proto->getNumParams(); 6017 6018 // (C++ 13.3.2p2): A candidate function having fewer than m 6019 // parameters is viable only if it has an ellipsis in its parameter 6020 // list (8.3.5). 6021 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6022 !Proto->isVariadic()) { 6023 Candidate.Viable = false; 6024 Candidate.FailureKind = ovl_fail_too_many_arguments; 6025 return; 6026 } 6027 6028 // (C++ 13.3.2p2): A candidate function having more than m parameters 6029 // is viable only if the (m+1)st parameter has a default argument 6030 // (8.3.6). For the purposes of overload resolution, the 6031 // parameter list is truncated on the right, so that there are 6032 // exactly m parameters. 6033 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6034 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6035 // Not enough arguments. 6036 Candidate.Viable = false; 6037 Candidate.FailureKind = ovl_fail_too_few_arguments; 6038 return; 6039 } 6040 6041 // (CUDA B.1): Check for invalid calls between targets. 6042 if (getLangOpts().CUDA) 6043 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6044 // Skip the check for callers that are implicit members, because in this 6045 // case we may not yet know what the member's target is; the target is 6046 // inferred for the member automatically, based on the bases and fields of 6047 // the class. 6048 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6049 Candidate.Viable = false; 6050 Candidate.FailureKind = ovl_fail_bad_target; 6051 return; 6052 } 6053 6054 // Determine the implicit conversion sequences for each of the 6055 // arguments. 6056 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6057 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6058 // We already formed a conversion sequence for this parameter during 6059 // template argument deduction. 6060 } else if (ArgIdx < NumParams) { 6061 // (C++ 13.3.2p3): for F to be a viable function, there shall 6062 // exist for each argument an implicit conversion sequence 6063 // (13.3.3.1) that converts that argument to the corresponding 6064 // parameter of F. 6065 QualType ParamType = Proto->getParamType(ArgIdx); 6066 Candidate.Conversions[ArgIdx] 6067 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6068 SuppressUserConversions, 6069 /*InOverloadResolution=*/true, 6070 /*AllowObjCWritebackConversion=*/ 6071 getLangOpts().ObjCAutoRefCount, 6072 AllowExplicit); 6073 if (Candidate.Conversions[ArgIdx].isBad()) { 6074 Candidate.Viable = false; 6075 Candidate.FailureKind = ovl_fail_bad_conversion; 6076 return; 6077 } 6078 } else { 6079 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6080 // argument for which there is no corresponding parameter is 6081 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6082 Candidate.Conversions[ArgIdx].setEllipsis(); 6083 } 6084 } 6085 6086 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6087 Candidate.Viable = false; 6088 Candidate.FailureKind = ovl_fail_enable_if; 6089 Candidate.DeductionFailure.Data = FailedAttr; 6090 return; 6091 } 6092 6093 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6094 Candidate.Viable = false; 6095 Candidate.FailureKind = ovl_fail_ext_disabled; 6096 return; 6097 } 6098 } 6099 6100 ObjCMethodDecl * 6101 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6102 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6103 if (Methods.size() <= 1) 6104 return nullptr; 6105 6106 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6107 bool Match = true; 6108 ObjCMethodDecl *Method = Methods[b]; 6109 unsigned NumNamedArgs = Sel.getNumArgs(); 6110 // Method might have more arguments than selector indicates. This is due 6111 // to addition of c-style arguments in method. 6112 if (Method->param_size() > NumNamedArgs) 6113 NumNamedArgs = Method->param_size(); 6114 if (Args.size() < NumNamedArgs) 6115 continue; 6116 6117 for (unsigned i = 0; i < NumNamedArgs; i++) { 6118 // We can't do any type-checking on a type-dependent argument. 6119 if (Args[i]->isTypeDependent()) { 6120 Match = false; 6121 break; 6122 } 6123 6124 ParmVarDecl *param = Method->parameters()[i]; 6125 Expr *argExpr = Args[i]; 6126 assert(argExpr && "SelectBestMethod(): missing expression"); 6127 6128 // Strip the unbridged-cast placeholder expression off unless it's 6129 // a consumed argument. 6130 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6131 !param->hasAttr<CFConsumedAttr>()) 6132 argExpr = stripARCUnbridgedCast(argExpr); 6133 6134 // If the parameter is __unknown_anytype, move on to the next method. 6135 if (param->getType() == Context.UnknownAnyTy) { 6136 Match = false; 6137 break; 6138 } 6139 6140 ImplicitConversionSequence ConversionState 6141 = TryCopyInitialization(*this, argExpr, param->getType(), 6142 /*SuppressUserConversions*/false, 6143 /*InOverloadResolution=*/true, 6144 /*AllowObjCWritebackConversion=*/ 6145 getLangOpts().ObjCAutoRefCount, 6146 /*AllowExplicit*/false); 6147 // This function looks for a reasonably-exact match, so we consider 6148 // incompatible pointer conversions to be a failure here. 6149 if (ConversionState.isBad() || 6150 (ConversionState.isStandard() && 6151 ConversionState.Standard.Second == 6152 ICK_Incompatible_Pointer_Conversion)) { 6153 Match = false; 6154 break; 6155 } 6156 } 6157 // Promote additional arguments to variadic methods. 6158 if (Match && Method->isVariadic()) { 6159 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6160 if (Args[i]->isTypeDependent()) { 6161 Match = false; 6162 break; 6163 } 6164 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6165 nullptr); 6166 if (Arg.isInvalid()) { 6167 Match = false; 6168 break; 6169 } 6170 } 6171 } else { 6172 // Check for extra arguments to non-variadic methods. 6173 if (Args.size() != NumNamedArgs) 6174 Match = false; 6175 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6176 // Special case when selectors have no argument. In this case, select 6177 // one with the most general result type of 'id'. 6178 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6179 QualType ReturnT = Methods[b]->getReturnType(); 6180 if (ReturnT->isObjCIdType()) 6181 return Methods[b]; 6182 } 6183 } 6184 } 6185 6186 if (Match) 6187 return Method; 6188 } 6189 return nullptr; 6190 } 6191 6192 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6193 // enable_if is order-sensitive. As a result, we need to reverse things 6194 // sometimes. Size of 4 elements is arbitrary. 6195 static SmallVector<EnableIfAttr *, 4> 6196 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6197 SmallVector<EnableIfAttr *, 4> Result; 6198 if (!Function->hasAttrs()) 6199 return Result; 6200 6201 const auto &FuncAttrs = Function->getAttrs(); 6202 for (Attr *Attr : FuncAttrs) 6203 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6204 Result.push_back(EnableIf); 6205 6206 std::reverse(Result.begin(), Result.end()); 6207 return Result; 6208 } 6209 6210 static bool 6211 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6212 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6213 bool MissingImplicitThis, Expr *&ConvertedThis, 6214 SmallVectorImpl<Expr *> &ConvertedArgs) { 6215 if (ThisArg) { 6216 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6217 assert(!isa<CXXConstructorDecl>(Method) && 6218 "Shouldn't have `this` for ctors!"); 6219 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6220 ExprResult R = S.PerformObjectArgumentInitialization( 6221 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6222 if (R.isInvalid()) 6223 return false; 6224 ConvertedThis = R.get(); 6225 } else { 6226 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6227 (void)MD; 6228 assert((MissingImplicitThis || MD->isStatic() || 6229 isa<CXXConstructorDecl>(MD)) && 6230 "Expected `this` for non-ctor instance methods"); 6231 } 6232 ConvertedThis = nullptr; 6233 } 6234 6235 // Ignore any variadic arguments. Converting them is pointless, since the 6236 // user can't refer to them in the function condition. 6237 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6238 6239 // Convert the arguments. 6240 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6241 ExprResult R; 6242 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6243 S.Context, Function->getParamDecl(I)), 6244 SourceLocation(), Args[I]); 6245 6246 if (R.isInvalid()) 6247 return false; 6248 6249 ConvertedArgs.push_back(R.get()); 6250 } 6251 6252 if (Trap.hasErrorOccurred()) 6253 return false; 6254 6255 // Push default arguments if needed. 6256 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6257 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6258 ParmVarDecl *P = Function->getParamDecl(i); 6259 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6260 ? P->getUninstantiatedDefaultArg() 6261 : P->getDefaultArg(); 6262 // This can only happen in code completion, i.e. when PartialOverloading 6263 // is true. 6264 if (!DefArg) 6265 return false; 6266 ExprResult R = 6267 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6268 S.Context, Function->getParamDecl(i)), 6269 SourceLocation(), DefArg); 6270 if (R.isInvalid()) 6271 return false; 6272 ConvertedArgs.push_back(R.get()); 6273 } 6274 6275 if (Trap.hasErrorOccurred()) 6276 return false; 6277 } 6278 return true; 6279 } 6280 6281 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6282 bool MissingImplicitThis) { 6283 SmallVector<EnableIfAttr *, 4> EnableIfAttrs = 6284 getOrderedEnableIfAttrs(Function); 6285 if (EnableIfAttrs.empty()) 6286 return nullptr; 6287 6288 SFINAETrap Trap(*this); 6289 SmallVector<Expr *, 16> ConvertedArgs; 6290 // FIXME: We should look into making enable_if late-parsed. 6291 Expr *DiscardedThis; 6292 if (!convertArgsForAvailabilityChecks( 6293 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6294 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6295 return EnableIfAttrs[0]; 6296 6297 for (auto *EIA : EnableIfAttrs) { 6298 APValue Result; 6299 // FIXME: This doesn't consider value-dependent cases, because doing so is 6300 // very difficult. Ideally, we should handle them more gracefully. 6301 if (!EIA->getCond()->EvaluateWithSubstitution( 6302 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6303 return EIA; 6304 6305 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6306 return EIA; 6307 } 6308 return nullptr; 6309 } 6310 6311 template <typename CheckFn> 6312 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6313 bool ArgDependent, SourceLocation Loc, 6314 CheckFn &&IsSuccessful) { 6315 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6316 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6317 if (ArgDependent == DIA->getArgDependent()) 6318 Attrs.push_back(DIA); 6319 } 6320 6321 // Common case: No diagnose_if attributes, so we can quit early. 6322 if (Attrs.empty()) 6323 return false; 6324 6325 auto WarningBegin = std::stable_partition( 6326 Attrs.begin(), Attrs.end(), 6327 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6328 6329 // Note that diagnose_if attributes are late-parsed, so they appear in the 6330 // correct order (unlike enable_if attributes). 6331 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6332 IsSuccessful); 6333 if (ErrAttr != WarningBegin) { 6334 const DiagnoseIfAttr *DIA = *ErrAttr; 6335 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6336 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6337 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6338 return true; 6339 } 6340 6341 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6342 if (IsSuccessful(DIA)) { 6343 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6344 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6345 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6346 } 6347 6348 return false; 6349 } 6350 6351 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6352 const Expr *ThisArg, 6353 ArrayRef<const Expr *> Args, 6354 SourceLocation Loc) { 6355 return diagnoseDiagnoseIfAttrsWith( 6356 *this, Function, /*ArgDependent=*/true, Loc, 6357 [&](const DiagnoseIfAttr *DIA) { 6358 APValue Result; 6359 // It's sane to use the same Args for any redecl of this function, since 6360 // EvaluateWithSubstitution only cares about the position of each 6361 // argument in the arg list, not the ParmVarDecl* it maps to. 6362 if (!DIA->getCond()->EvaluateWithSubstitution( 6363 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6364 return false; 6365 return Result.isInt() && Result.getInt().getBoolValue(); 6366 }); 6367 } 6368 6369 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6370 SourceLocation Loc) { 6371 return diagnoseDiagnoseIfAttrsWith( 6372 *this, ND, /*ArgDependent=*/false, Loc, 6373 [&](const DiagnoseIfAttr *DIA) { 6374 bool Result; 6375 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6376 Result; 6377 }); 6378 } 6379 6380 /// Add all of the function declarations in the given function set to 6381 /// the overload candidate set. 6382 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6383 ArrayRef<Expr *> Args, 6384 OverloadCandidateSet& CandidateSet, 6385 TemplateArgumentListInfo *ExplicitTemplateArgs, 6386 bool SuppressUserConversions, 6387 bool PartialOverloading, 6388 bool FirstArgumentIsBase) { 6389 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6390 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6391 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6392 ArrayRef<Expr *> FunctionArgs = Args; 6393 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6394 QualType ObjectType; 6395 Expr::Classification ObjectClassification; 6396 if (Args.size() > 0) { 6397 if (Expr *E = Args[0]) { 6398 // Use the explicit base to restrict the lookup: 6399 ObjectType = E->getType(); 6400 ObjectClassification = E->Classify(Context); 6401 } // .. else there is an implit base. 6402 FunctionArgs = Args.slice(1); 6403 } 6404 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6405 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6406 ObjectClassification, FunctionArgs, CandidateSet, 6407 SuppressUserConversions, PartialOverloading); 6408 } else { 6409 // Slice the first argument (which is the base) when we access 6410 // static method as non-static 6411 if (Args.size() > 0 && (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6412 !isa<CXXConstructorDecl>(FD)))) { 6413 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6414 FunctionArgs = Args.slice(1); 6415 } 6416 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6417 SuppressUserConversions, PartialOverloading); 6418 } 6419 } else { 6420 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6421 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6422 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) { 6423 QualType ObjectType; 6424 Expr::Classification ObjectClassification; 6425 if (Expr *E = Args[0]) { 6426 // Use the explicit base to restrict the lookup: 6427 ObjectType = E->getType(); 6428 ObjectClassification = E->Classify(Context); 6429 } // .. else there is an implit base. 6430 AddMethodTemplateCandidate( 6431 FunTmpl, F.getPair(), 6432 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6433 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6434 Args.slice(1), CandidateSet, SuppressUserConversions, 6435 PartialOverloading); 6436 } else { 6437 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6438 ExplicitTemplateArgs, Args, 6439 CandidateSet, SuppressUserConversions, 6440 PartialOverloading); 6441 } 6442 } 6443 } 6444 } 6445 6446 /// AddMethodCandidate - Adds a named decl (which is some kind of 6447 /// method) as a method candidate to the given overload set. 6448 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6449 QualType ObjectType, 6450 Expr::Classification ObjectClassification, 6451 ArrayRef<Expr *> Args, 6452 OverloadCandidateSet& CandidateSet, 6453 bool SuppressUserConversions) { 6454 NamedDecl *Decl = FoundDecl.getDecl(); 6455 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6456 6457 if (isa<UsingShadowDecl>(Decl)) 6458 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6459 6460 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6461 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6462 "Expected a member function template"); 6463 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6464 /*ExplicitArgs*/ nullptr, ObjectType, 6465 ObjectClassification, Args, CandidateSet, 6466 SuppressUserConversions); 6467 } else { 6468 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6469 ObjectType, ObjectClassification, Args, CandidateSet, 6470 SuppressUserConversions); 6471 } 6472 } 6473 6474 /// AddMethodCandidate - Adds the given C++ member function to the set 6475 /// of candidate functions, using the given function call arguments 6476 /// and the object argument (@c Object). For example, in a call 6477 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6478 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6479 /// allow user-defined conversions via constructors or conversion 6480 /// operators. 6481 void 6482 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6483 CXXRecordDecl *ActingContext, QualType ObjectType, 6484 Expr::Classification ObjectClassification, 6485 ArrayRef<Expr *> Args, 6486 OverloadCandidateSet &CandidateSet, 6487 bool SuppressUserConversions, 6488 bool PartialOverloading, 6489 ConversionSequenceList EarlyConversions) { 6490 const FunctionProtoType *Proto 6491 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6492 assert(Proto && "Methods without a prototype cannot be overloaded"); 6493 assert(!isa<CXXConstructorDecl>(Method) && 6494 "Use AddOverloadCandidate for constructors"); 6495 6496 if (!CandidateSet.isNewCandidate(Method)) 6497 return; 6498 6499 // C++11 [class.copy]p23: [DR1402] 6500 // A defaulted move assignment operator that is defined as deleted is 6501 // ignored by overload resolution. 6502 if (Method->isDefaulted() && Method->isDeleted() && 6503 Method->isMoveAssignmentOperator()) 6504 return; 6505 6506 // Overload resolution is always an unevaluated context. 6507 EnterExpressionEvaluationContext Unevaluated( 6508 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6509 6510 // Add this candidate 6511 OverloadCandidate &Candidate = 6512 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6513 Candidate.FoundDecl = FoundDecl; 6514 Candidate.Function = Method; 6515 Candidate.IsSurrogate = false; 6516 Candidate.IgnoreObjectArgument = false; 6517 Candidate.ExplicitCallArguments = Args.size(); 6518 6519 unsigned NumParams = Proto->getNumParams(); 6520 6521 // (C++ 13.3.2p2): A candidate function having fewer than m 6522 // parameters is viable only if it has an ellipsis in its parameter 6523 // list (8.3.5). 6524 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6525 !Proto->isVariadic()) { 6526 Candidate.Viable = false; 6527 Candidate.FailureKind = ovl_fail_too_many_arguments; 6528 return; 6529 } 6530 6531 // (C++ 13.3.2p2): A candidate function having more than m parameters 6532 // is viable only if the (m+1)st parameter has a default argument 6533 // (8.3.6). For the purposes of overload resolution, the 6534 // parameter list is truncated on the right, so that there are 6535 // exactly m parameters. 6536 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6537 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6538 // Not enough arguments. 6539 Candidate.Viable = false; 6540 Candidate.FailureKind = ovl_fail_too_few_arguments; 6541 return; 6542 } 6543 6544 Candidate.Viable = true; 6545 6546 if (Method->isStatic() || ObjectType.isNull()) 6547 // The implicit object argument is ignored. 6548 Candidate.IgnoreObjectArgument = true; 6549 else { 6550 // Determine the implicit conversion sequence for the object 6551 // parameter. 6552 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6553 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6554 Method, ActingContext); 6555 if (Candidate.Conversions[0].isBad()) { 6556 Candidate.Viable = false; 6557 Candidate.FailureKind = ovl_fail_bad_conversion; 6558 return; 6559 } 6560 } 6561 6562 // (CUDA B.1): Check for invalid calls between targets. 6563 if (getLangOpts().CUDA) 6564 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6565 if (!IsAllowedCUDACall(Caller, Method)) { 6566 Candidate.Viable = false; 6567 Candidate.FailureKind = ovl_fail_bad_target; 6568 return; 6569 } 6570 6571 // Determine the implicit conversion sequences for each of the 6572 // arguments. 6573 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6574 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6575 // We already formed a conversion sequence for this parameter during 6576 // template argument deduction. 6577 } else if (ArgIdx < NumParams) { 6578 // (C++ 13.3.2p3): for F to be a viable function, there shall 6579 // exist for each argument an implicit conversion sequence 6580 // (13.3.3.1) that converts that argument to the corresponding 6581 // parameter of F. 6582 QualType ParamType = Proto->getParamType(ArgIdx); 6583 Candidate.Conversions[ArgIdx + 1] 6584 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6585 SuppressUserConversions, 6586 /*InOverloadResolution=*/true, 6587 /*AllowObjCWritebackConversion=*/ 6588 getLangOpts().ObjCAutoRefCount); 6589 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6590 Candidate.Viable = false; 6591 Candidate.FailureKind = ovl_fail_bad_conversion; 6592 return; 6593 } 6594 } else { 6595 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6596 // argument for which there is no corresponding parameter is 6597 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6598 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6599 } 6600 } 6601 6602 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6603 Candidate.Viable = false; 6604 Candidate.FailureKind = ovl_fail_enable_if; 6605 Candidate.DeductionFailure.Data = FailedAttr; 6606 return; 6607 } 6608 6609 if (Method->isMultiVersion() && 6610 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6611 Candidate.Viable = false; 6612 Candidate.FailureKind = ovl_non_default_multiversion_function; 6613 } 6614 } 6615 6616 /// Add a C++ member function template as a candidate to the candidate 6617 /// set, using template argument deduction to produce an appropriate member 6618 /// function template specialization. 6619 void 6620 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6621 DeclAccessPair FoundDecl, 6622 CXXRecordDecl *ActingContext, 6623 TemplateArgumentListInfo *ExplicitTemplateArgs, 6624 QualType ObjectType, 6625 Expr::Classification ObjectClassification, 6626 ArrayRef<Expr *> Args, 6627 OverloadCandidateSet& CandidateSet, 6628 bool SuppressUserConversions, 6629 bool PartialOverloading) { 6630 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6631 return; 6632 6633 // C++ [over.match.funcs]p7: 6634 // In each case where a candidate is a function template, candidate 6635 // function template specializations are generated using template argument 6636 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6637 // candidate functions in the usual way.113) A given name can refer to one 6638 // or more function templates and also to a set of overloaded non-template 6639 // functions. In such a case, the candidate functions generated from each 6640 // function template are combined with the set of non-template candidate 6641 // functions. 6642 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6643 FunctionDecl *Specialization = nullptr; 6644 ConversionSequenceList Conversions; 6645 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6646 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6647 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6648 return CheckNonDependentConversions( 6649 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6650 SuppressUserConversions, ActingContext, ObjectType, 6651 ObjectClassification); 6652 })) { 6653 OverloadCandidate &Candidate = 6654 CandidateSet.addCandidate(Conversions.size(), Conversions); 6655 Candidate.FoundDecl = FoundDecl; 6656 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6657 Candidate.Viable = false; 6658 Candidate.IsSurrogate = false; 6659 Candidate.IgnoreObjectArgument = 6660 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6661 ObjectType.isNull(); 6662 Candidate.ExplicitCallArguments = Args.size(); 6663 if (Result == TDK_NonDependentConversionFailure) 6664 Candidate.FailureKind = ovl_fail_bad_conversion; 6665 else { 6666 Candidate.FailureKind = ovl_fail_bad_deduction; 6667 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6668 Info); 6669 } 6670 return; 6671 } 6672 6673 // Add the function template specialization produced by template argument 6674 // deduction as a candidate. 6675 assert(Specialization && "Missing member function template specialization?"); 6676 assert(isa<CXXMethodDecl>(Specialization) && 6677 "Specialization is not a member function?"); 6678 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6679 ActingContext, ObjectType, ObjectClassification, Args, 6680 CandidateSet, SuppressUserConversions, PartialOverloading, 6681 Conversions); 6682 } 6683 6684 /// Add a C++ function template specialization as a candidate 6685 /// in the candidate set, using template argument deduction to produce 6686 /// an appropriate function template specialization. 6687 void 6688 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6689 DeclAccessPair FoundDecl, 6690 TemplateArgumentListInfo *ExplicitTemplateArgs, 6691 ArrayRef<Expr *> Args, 6692 OverloadCandidateSet& CandidateSet, 6693 bool SuppressUserConversions, 6694 bool PartialOverloading) { 6695 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6696 return; 6697 6698 // C++ [over.match.funcs]p7: 6699 // In each case where a candidate is a function template, candidate 6700 // function template specializations are generated using template argument 6701 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6702 // candidate functions in the usual way.113) A given name can refer to one 6703 // or more function templates and also to a set of overloaded non-template 6704 // functions. In such a case, the candidate functions generated from each 6705 // function template are combined with the set of non-template candidate 6706 // functions. 6707 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6708 FunctionDecl *Specialization = nullptr; 6709 ConversionSequenceList Conversions; 6710 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6711 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6712 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6713 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6714 Args, CandidateSet, Conversions, 6715 SuppressUserConversions); 6716 })) { 6717 OverloadCandidate &Candidate = 6718 CandidateSet.addCandidate(Conversions.size(), Conversions); 6719 Candidate.FoundDecl = FoundDecl; 6720 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6721 Candidate.Viable = false; 6722 Candidate.IsSurrogate = false; 6723 // Ignore the object argument if there is one, since we don't have an object 6724 // type. 6725 Candidate.IgnoreObjectArgument = 6726 isa<CXXMethodDecl>(Candidate.Function) && 6727 !isa<CXXConstructorDecl>(Candidate.Function); 6728 Candidate.ExplicitCallArguments = Args.size(); 6729 if (Result == TDK_NonDependentConversionFailure) 6730 Candidate.FailureKind = ovl_fail_bad_conversion; 6731 else { 6732 Candidate.FailureKind = ovl_fail_bad_deduction; 6733 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6734 Info); 6735 } 6736 return; 6737 } 6738 6739 // Add the function template specialization produced by template argument 6740 // deduction as a candidate. 6741 assert(Specialization && "Missing function template specialization?"); 6742 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6743 SuppressUserConversions, PartialOverloading, 6744 /*AllowExplicit*/false, Conversions); 6745 } 6746 6747 /// Check that implicit conversion sequences can be formed for each argument 6748 /// whose corresponding parameter has a non-dependent type, per DR1391's 6749 /// [temp.deduct.call]p10. 6750 bool Sema::CheckNonDependentConversions( 6751 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6752 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6753 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6754 CXXRecordDecl *ActingContext, QualType ObjectType, 6755 Expr::Classification ObjectClassification) { 6756 // FIXME: The cases in which we allow explicit conversions for constructor 6757 // arguments never consider calling a constructor template. It's not clear 6758 // that is correct. 6759 const bool AllowExplicit = false; 6760 6761 auto *FD = FunctionTemplate->getTemplatedDecl(); 6762 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6763 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6764 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6765 6766 Conversions = 6767 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6768 6769 // Overload resolution is always an unevaluated context. 6770 EnterExpressionEvaluationContext Unevaluated( 6771 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6772 6773 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6774 // require that, but this check should never result in a hard error, and 6775 // overload resolution is permitted to sidestep instantiations. 6776 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6777 !ObjectType.isNull()) { 6778 Conversions[0] = TryObjectArgumentInitialization( 6779 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6780 Method, ActingContext); 6781 if (Conversions[0].isBad()) 6782 return true; 6783 } 6784 6785 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6786 ++I) { 6787 QualType ParamType = ParamTypes[I]; 6788 if (!ParamType->isDependentType()) { 6789 Conversions[ThisConversions + I] 6790 = TryCopyInitialization(*this, Args[I], ParamType, 6791 SuppressUserConversions, 6792 /*InOverloadResolution=*/true, 6793 /*AllowObjCWritebackConversion=*/ 6794 getLangOpts().ObjCAutoRefCount, 6795 AllowExplicit); 6796 if (Conversions[ThisConversions + I].isBad()) 6797 return true; 6798 } 6799 } 6800 6801 return false; 6802 } 6803 6804 /// Determine whether this is an allowable conversion from the result 6805 /// of an explicit conversion operator to the expected type, per C++ 6806 /// [over.match.conv]p1 and [over.match.ref]p1. 6807 /// 6808 /// \param ConvType The return type of the conversion function. 6809 /// 6810 /// \param ToType The type we are converting to. 6811 /// 6812 /// \param AllowObjCPointerConversion Allow a conversion from one 6813 /// Objective-C pointer to another. 6814 /// 6815 /// \returns true if the conversion is allowable, false otherwise. 6816 static bool isAllowableExplicitConversion(Sema &S, 6817 QualType ConvType, QualType ToType, 6818 bool AllowObjCPointerConversion) { 6819 QualType ToNonRefType = ToType.getNonReferenceType(); 6820 6821 // Easy case: the types are the same. 6822 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6823 return true; 6824 6825 // Allow qualification conversions. 6826 bool ObjCLifetimeConversion; 6827 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6828 ObjCLifetimeConversion)) 6829 return true; 6830 6831 // If we're not allowed to consider Objective-C pointer conversions, 6832 // we're done. 6833 if (!AllowObjCPointerConversion) 6834 return false; 6835 6836 // Is this an Objective-C pointer conversion? 6837 bool IncompatibleObjC = false; 6838 QualType ConvertedType; 6839 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6840 IncompatibleObjC); 6841 } 6842 6843 /// AddConversionCandidate - Add a C++ conversion function as a 6844 /// candidate in the candidate set (C++ [over.match.conv], 6845 /// C++ [over.match.copy]). From is the expression we're converting from, 6846 /// and ToType is the type that we're eventually trying to convert to 6847 /// (which may or may not be the same type as the type that the 6848 /// conversion function produces). 6849 void 6850 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6851 DeclAccessPair FoundDecl, 6852 CXXRecordDecl *ActingContext, 6853 Expr *From, QualType ToType, 6854 OverloadCandidateSet& CandidateSet, 6855 bool AllowObjCConversionOnExplicit, 6856 bool AllowResultConversion) { 6857 assert(!Conversion->getDescribedFunctionTemplate() && 6858 "Conversion function templates use AddTemplateConversionCandidate"); 6859 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6860 if (!CandidateSet.isNewCandidate(Conversion)) 6861 return; 6862 6863 // If the conversion function has an undeduced return type, trigger its 6864 // deduction now. 6865 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6866 if (DeduceReturnType(Conversion, From->getExprLoc())) 6867 return; 6868 ConvType = Conversion->getConversionType().getNonReferenceType(); 6869 } 6870 6871 // If we don't allow any conversion of the result type, ignore conversion 6872 // functions that don't convert to exactly (possibly cv-qualified) T. 6873 if (!AllowResultConversion && 6874 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6875 return; 6876 6877 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6878 // operator is only a candidate if its return type is the target type or 6879 // can be converted to the target type with a qualification conversion. 6880 if (Conversion->isExplicit() && 6881 !isAllowableExplicitConversion(*this, ConvType, ToType, 6882 AllowObjCConversionOnExplicit)) 6883 return; 6884 6885 // Overload resolution is always an unevaluated context. 6886 EnterExpressionEvaluationContext Unevaluated( 6887 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6888 6889 // Add this candidate 6890 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6891 Candidate.FoundDecl = FoundDecl; 6892 Candidate.Function = Conversion; 6893 Candidate.IsSurrogate = false; 6894 Candidate.IgnoreObjectArgument = false; 6895 Candidate.FinalConversion.setAsIdentityConversion(); 6896 Candidate.FinalConversion.setFromType(ConvType); 6897 Candidate.FinalConversion.setAllToTypes(ToType); 6898 Candidate.Viable = true; 6899 Candidate.ExplicitCallArguments = 1; 6900 6901 // C++ [over.match.funcs]p4: 6902 // For conversion functions, the function is considered to be a member of 6903 // the class of the implicit implied object argument for the purpose of 6904 // defining the type of the implicit object parameter. 6905 // 6906 // Determine the implicit conversion sequence for the implicit 6907 // object parameter. 6908 QualType ImplicitParamType = From->getType(); 6909 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6910 ImplicitParamType = FromPtrType->getPointeeType(); 6911 CXXRecordDecl *ConversionContext 6912 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6913 6914 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6915 *this, CandidateSet.getLocation(), From->getType(), 6916 From->Classify(Context), Conversion, ConversionContext); 6917 6918 if (Candidate.Conversions[0].isBad()) { 6919 Candidate.Viable = false; 6920 Candidate.FailureKind = ovl_fail_bad_conversion; 6921 return; 6922 } 6923 6924 // We won't go through a user-defined type conversion function to convert a 6925 // derived to base as such conversions are given Conversion Rank. They only 6926 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6927 QualType FromCanon 6928 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6929 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6930 if (FromCanon == ToCanon || 6931 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6932 Candidate.Viable = false; 6933 Candidate.FailureKind = ovl_fail_trivial_conversion; 6934 return; 6935 } 6936 6937 // To determine what the conversion from the result of calling the 6938 // conversion function to the type we're eventually trying to 6939 // convert to (ToType), we need to synthesize a call to the 6940 // conversion function and attempt copy initialization from it. This 6941 // makes sure that we get the right semantics with respect to 6942 // lvalues/rvalues and the type. Fortunately, we can allocate this 6943 // call on the stack and we don't need its arguments to be 6944 // well-formed. 6945 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6946 VK_LValue, From->getLocStart()); 6947 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6948 Context.getPointerType(Conversion->getType()), 6949 CK_FunctionToPointerDecay, 6950 &ConversionRef, VK_RValue); 6951 6952 QualType ConversionType = Conversion->getConversionType(); 6953 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6954 Candidate.Viable = false; 6955 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6956 return; 6957 } 6958 6959 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6960 6961 // Note that it is safe to allocate CallExpr on the stack here because 6962 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6963 // allocator). 6964 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6965 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6966 From->getLocStart()); 6967 ImplicitConversionSequence ICS = 6968 TryCopyInitialization(*this, &Call, ToType, 6969 /*SuppressUserConversions=*/true, 6970 /*InOverloadResolution=*/false, 6971 /*AllowObjCWritebackConversion=*/false); 6972 6973 switch (ICS.getKind()) { 6974 case ImplicitConversionSequence::StandardConversion: 6975 Candidate.FinalConversion = ICS.Standard; 6976 6977 // C++ [over.ics.user]p3: 6978 // If the user-defined conversion is specified by a specialization of a 6979 // conversion function template, the second standard conversion sequence 6980 // shall have exact match rank. 6981 if (Conversion->getPrimaryTemplate() && 6982 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6983 Candidate.Viable = false; 6984 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6985 return; 6986 } 6987 6988 // C++0x [dcl.init.ref]p5: 6989 // In the second case, if the reference is an rvalue reference and 6990 // the second standard conversion sequence of the user-defined 6991 // conversion sequence includes an lvalue-to-rvalue conversion, the 6992 // program is ill-formed. 6993 if (ToType->isRValueReferenceType() && 6994 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6995 Candidate.Viable = false; 6996 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6997 return; 6998 } 6999 break; 7000 7001 case ImplicitConversionSequence::BadConversion: 7002 Candidate.Viable = false; 7003 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7004 return; 7005 7006 default: 7007 llvm_unreachable( 7008 "Can only end up with a standard conversion sequence or failure"); 7009 } 7010 7011 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7012 Candidate.Viable = false; 7013 Candidate.FailureKind = ovl_fail_enable_if; 7014 Candidate.DeductionFailure.Data = FailedAttr; 7015 return; 7016 } 7017 7018 if (Conversion->isMultiVersion() && 7019 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7020 Candidate.Viable = false; 7021 Candidate.FailureKind = ovl_non_default_multiversion_function; 7022 } 7023 } 7024 7025 /// Adds a conversion function template specialization 7026 /// candidate to the overload set, using template argument deduction 7027 /// to deduce the template arguments of the conversion function 7028 /// template from the type that we are converting to (C++ 7029 /// [temp.deduct.conv]). 7030 void 7031 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7032 DeclAccessPair FoundDecl, 7033 CXXRecordDecl *ActingDC, 7034 Expr *From, QualType ToType, 7035 OverloadCandidateSet &CandidateSet, 7036 bool AllowObjCConversionOnExplicit, 7037 bool AllowResultConversion) { 7038 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7039 "Only conversion function templates permitted here"); 7040 7041 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7042 return; 7043 7044 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7045 CXXConversionDecl *Specialization = nullptr; 7046 if (TemplateDeductionResult Result 7047 = DeduceTemplateArguments(FunctionTemplate, ToType, 7048 Specialization, Info)) { 7049 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7050 Candidate.FoundDecl = FoundDecl; 7051 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7052 Candidate.Viable = false; 7053 Candidate.FailureKind = ovl_fail_bad_deduction; 7054 Candidate.IsSurrogate = false; 7055 Candidate.IgnoreObjectArgument = false; 7056 Candidate.ExplicitCallArguments = 1; 7057 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7058 Info); 7059 return; 7060 } 7061 7062 // Add the conversion function template specialization produced by 7063 // template argument deduction as a candidate. 7064 assert(Specialization && "Missing function template specialization?"); 7065 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7066 CandidateSet, AllowObjCConversionOnExplicit, 7067 AllowResultConversion); 7068 } 7069 7070 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7071 /// converts the given @c Object to a function pointer via the 7072 /// conversion function @c Conversion, and then attempts to call it 7073 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7074 /// the type of function that we'll eventually be calling. 7075 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7076 DeclAccessPair FoundDecl, 7077 CXXRecordDecl *ActingContext, 7078 const FunctionProtoType *Proto, 7079 Expr *Object, 7080 ArrayRef<Expr *> Args, 7081 OverloadCandidateSet& CandidateSet) { 7082 if (!CandidateSet.isNewCandidate(Conversion)) 7083 return; 7084 7085 // Overload resolution is always an unevaluated context. 7086 EnterExpressionEvaluationContext Unevaluated( 7087 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7088 7089 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7090 Candidate.FoundDecl = FoundDecl; 7091 Candidate.Function = nullptr; 7092 Candidate.Surrogate = Conversion; 7093 Candidate.Viable = true; 7094 Candidate.IsSurrogate = true; 7095 Candidate.IgnoreObjectArgument = false; 7096 Candidate.ExplicitCallArguments = Args.size(); 7097 7098 // Determine the implicit conversion sequence for the implicit 7099 // object parameter. 7100 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7101 *this, CandidateSet.getLocation(), Object->getType(), 7102 Object->Classify(Context), Conversion, ActingContext); 7103 if (ObjectInit.isBad()) { 7104 Candidate.Viable = false; 7105 Candidate.FailureKind = ovl_fail_bad_conversion; 7106 Candidate.Conversions[0] = ObjectInit; 7107 return; 7108 } 7109 7110 // The first conversion is actually a user-defined conversion whose 7111 // first conversion is ObjectInit's standard conversion (which is 7112 // effectively a reference binding). Record it as such. 7113 Candidate.Conversions[0].setUserDefined(); 7114 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7115 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7116 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7117 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7118 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7119 Candidate.Conversions[0].UserDefined.After 7120 = Candidate.Conversions[0].UserDefined.Before; 7121 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7122 7123 // Find the 7124 unsigned NumParams = Proto->getNumParams(); 7125 7126 // (C++ 13.3.2p2): A candidate function having fewer than m 7127 // parameters is viable only if it has an ellipsis in its parameter 7128 // list (8.3.5). 7129 if (Args.size() > NumParams && !Proto->isVariadic()) { 7130 Candidate.Viable = false; 7131 Candidate.FailureKind = ovl_fail_too_many_arguments; 7132 return; 7133 } 7134 7135 // Function types don't have any default arguments, so just check if 7136 // we have enough arguments. 7137 if (Args.size() < NumParams) { 7138 // Not enough arguments. 7139 Candidate.Viable = false; 7140 Candidate.FailureKind = ovl_fail_too_few_arguments; 7141 return; 7142 } 7143 7144 // Determine the implicit conversion sequences for each of the 7145 // arguments. 7146 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7147 if (ArgIdx < NumParams) { 7148 // (C++ 13.3.2p3): for F to be a viable function, there shall 7149 // exist for each argument an implicit conversion sequence 7150 // (13.3.3.1) that converts that argument to the corresponding 7151 // parameter of F. 7152 QualType ParamType = Proto->getParamType(ArgIdx); 7153 Candidate.Conversions[ArgIdx + 1] 7154 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7155 /*SuppressUserConversions=*/false, 7156 /*InOverloadResolution=*/false, 7157 /*AllowObjCWritebackConversion=*/ 7158 getLangOpts().ObjCAutoRefCount); 7159 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7160 Candidate.Viable = false; 7161 Candidate.FailureKind = ovl_fail_bad_conversion; 7162 return; 7163 } 7164 } else { 7165 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7166 // argument for which there is no corresponding parameter is 7167 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7168 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7169 } 7170 } 7171 7172 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7173 Candidate.Viable = false; 7174 Candidate.FailureKind = ovl_fail_enable_if; 7175 Candidate.DeductionFailure.Data = FailedAttr; 7176 return; 7177 } 7178 } 7179 7180 /// Add overload candidates for overloaded operators that are 7181 /// member functions. 7182 /// 7183 /// Add the overloaded operator candidates that are member functions 7184 /// for the operator Op that was used in an operator expression such 7185 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7186 /// CandidateSet will store the added overload candidates. (C++ 7187 /// [over.match.oper]). 7188 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7189 SourceLocation OpLoc, 7190 ArrayRef<Expr *> Args, 7191 OverloadCandidateSet& CandidateSet, 7192 SourceRange OpRange) { 7193 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7194 7195 // C++ [over.match.oper]p3: 7196 // For a unary operator @ with an operand of a type whose 7197 // cv-unqualified version is T1, and for a binary operator @ with 7198 // a left operand of a type whose cv-unqualified version is T1 and 7199 // a right operand of a type whose cv-unqualified version is T2, 7200 // three sets of candidate functions, designated member 7201 // candidates, non-member candidates and built-in candidates, are 7202 // constructed as follows: 7203 QualType T1 = Args[0]->getType(); 7204 7205 // -- If T1 is a complete class type or a class currently being 7206 // defined, the set of member candidates is the result of the 7207 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7208 // the set of member candidates is empty. 7209 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7210 // Complete the type if it can be completed. 7211 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7212 return; 7213 // If the type is neither complete nor being defined, bail out now. 7214 if (!T1Rec->getDecl()->getDefinition()) 7215 return; 7216 7217 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7218 LookupQualifiedName(Operators, T1Rec->getDecl()); 7219 Operators.suppressDiagnostics(); 7220 7221 for (LookupResult::iterator Oper = Operators.begin(), 7222 OperEnd = Operators.end(); 7223 Oper != OperEnd; 7224 ++Oper) 7225 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7226 Args[0]->Classify(Context), Args.slice(1), 7227 CandidateSet, /*SuppressUserConversions=*/false); 7228 } 7229 } 7230 7231 /// AddBuiltinCandidate - Add a candidate for a built-in 7232 /// operator. ResultTy and ParamTys are the result and parameter types 7233 /// of the built-in candidate, respectively. Args and NumArgs are the 7234 /// arguments being passed to the candidate. IsAssignmentOperator 7235 /// should be true when this built-in candidate is an assignment 7236 /// operator. NumContextualBoolArguments is the number of arguments 7237 /// (at the beginning of the argument list) that will be contextually 7238 /// converted to bool. 7239 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7240 OverloadCandidateSet& CandidateSet, 7241 bool IsAssignmentOperator, 7242 unsigned NumContextualBoolArguments) { 7243 // Overload resolution is always an unevaluated context. 7244 EnterExpressionEvaluationContext Unevaluated( 7245 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7246 7247 // Add this candidate 7248 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7249 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7250 Candidate.Function = nullptr; 7251 Candidate.IsSurrogate = false; 7252 Candidate.IgnoreObjectArgument = false; 7253 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7254 7255 // Determine the implicit conversion sequences for each of the 7256 // arguments. 7257 Candidate.Viable = true; 7258 Candidate.ExplicitCallArguments = Args.size(); 7259 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7260 // C++ [over.match.oper]p4: 7261 // For the built-in assignment operators, conversions of the 7262 // left operand are restricted as follows: 7263 // -- no temporaries are introduced to hold the left operand, and 7264 // -- no user-defined conversions are applied to the left 7265 // operand to achieve a type match with the left-most 7266 // parameter of a built-in candidate. 7267 // 7268 // We block these conversions by turning off user-defined 7269 // conversions, since that is the only way that initialization of 7270 // a reference to a non-class type can occur from something that 7271 // is not of the same type. 7272 if (ArgIdx < NumContextualBoolArguments) { 7273 assert(ParamTys[ArgIdx] == Context.BoolTy && 7274 "Contextual conversion to bool requires bool type"); 7275 Candidate.Conversions[ArgIdx] 7276 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7277 } else { 7278 Candidate.Conversions[ArgIdx] 7279 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7280 ArgIdx == 0 && IsAssignmentOperator, 7281 /*InOverloadResolution=*/false, 7282 /*AllowObjCWritebackConversion=*/ 7283 getLangOpts().ObjCAutoRefCount); 7284 } 7285 if (Candidate.Conversions[ArgIdx].isBad()) { 7286 Candidate.Viable = false; 7287 Candidate.FailureKind = ovl_fail_bad_conversion; 7288 break; 7289 } 7290 } 7291 } 7292 7293 namespace { 7294 7295 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7296 /// candidate operator functions for built-in operators (C++ 7297 /// [over.built]). The types are separated into pointer types and 7298 /// enumeration types. 7299 class BuiltinCandidateTypeSet { 7300 /// TypeSet - A set of types. 7301 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7302 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7303 7304 /// PointerTypes - The set of pointer types that will be used in the 7305 /// built-in candidates. 7306 TypeSet PointerTypes; 7307 7308 /// MemberPointerTypes - The set of member pointer types that will be 7309 /// used in the built-in candidates. 7310 TypeSet MemberPointerTypes; 7311 7312 /// EnumerationTypes - The set of enumeration types that will be 7313 /// used in the built-in candidates. 7314 TypeSet EnumerationTypes; 7315 7316 /// The set of vector types that will be used in the built-in 7317 /// candidates. 7318 TypeSet VectorTypes; 7319 7320 /// A flag indicating non-record types are viable candidates 7321 bool HasNonRecordTypes; 7322 7323 /// A flag indicating whether either arithmetic or enumeration types 7324 /// were present in the candidate set. 7325 bool HasArithmeticOrEnumeralTypes; 7326 7327 /// A flag indicating whether the nullptr type was present in the 7328 /// candidate set. 7329 bool HasNullPtrType; 7330 7331 /// Sema - The semantic analysis instance where we are building the 7332 /// candidate type set. 7333 Sema &SemaRef; 7334 7335 /// Context - The AST context in which we will build the type sets. 7336 ASTContext &Context; 7337 7338 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7339 const Qualifiers &VisibleQuals); 7340 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7341 7342 public: 7343 /// iterator - Iterates through the types that are part of the set. 7344 typedef TypeSet::iterator iterator; 7345 7346 BuiltinCandidateTypeSet(Sema &SemaRef) 7347 : HasNonRecordTypes(false), 7348 HasArithmeticOrEnumeralTypes(false), 7349 HasNullPtrType(false), 7350 SemaRef(SemaRef), 7351 Context(SemaRef.Context) { } 7352 7353 void AddTypesConvertedFrom(QualType Ty, 7354 SourceLocation Loc, 7355 bool AllowUserConversions, 7356 bool AllowExplicitConversions, 7357 const Qualifiers &VisibleTypeConversionsQuals); 7358 7359 /// pointer_begin - First pointer type found; 7360 iterator pointer_begin() { return PointerTypes.begin(); } 7361 7362 /// pointer_end - Past the last pointer type found; 7363 iterator pointer_end() { return PointerTypes.end(); } 7364 7365 /// member_pointer_begin - First member pointer type found; 7366 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7367 7368 /// member_pointer_end - Past the last member pointer type found; 7369 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7370 7371 /// enumeration_begin - First enumeration type found; 7372 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7373 7374 /// enumeration_end - Past the last enumeration type found; 7375 iterator enumeration_end() { return EnumerationTypes.end(); } 7376 7377 iterator vector_begin() { return VectorTypes.begin(); } 7378 iterator vector_end() { return VectorTypes.end(); } 7379 7380 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7381 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7382 bool hasNullPtrType() const { return HasNullPtrType; } 7383 }; 7384 7385 } // end anonymous namespace 7386 7387 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7388 /// the set of pointer types along with any more-qualified variants of 7389 /// that type. For example, if @p Ty is "int const *", this routine 7390 /// will add "int const *", "int const volatile *", "int const 7391 /// restrict *", and "int const volatile restrict *" to the set of 7392 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7393 /// false otherwise. 7394 /// 7395 /// FIXME: what to do about extended qualifiers? 7396 bool 7397 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7398 const Qualifiers &VisibleQuals) { 7399 7400 // Insert this type. 7401 if (!PointerTypes.insert(Ty)) 7402 return false; 7403 7404 QualType PointeeTy; 7405 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7406 bool buildObjCPtr = false; 7407 if (!PointerTy) { 7408 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7409 PointeeTy = PTy->getPointeeType(); 7410 buildObjCPtr = true; 7411 } else { 7412 PointeeTy = PointerTy->getPointeeType(); 7413 } 7414 7415 // Don't add qualified variants of arrays. For one, they're not allowed 7416 // (the qualifier would sink to the element type), and for another, the 7417 // only overload situation where it matters is subscript or pointer +- int, 7418 // and those shouldn't have qualifier variants anyway. 7419 if (PointeeTy->isArrayType()) 7420 return true; 7421 7422 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7423 bool hasVolatile = VisibleQuals.hasVolatile(); 7424 bool hasRestrict = VisibleQuals.hasRestrict(); 7425 7426 // Iterate through all strict supersets of BaseCVR. 7427 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7428 if ((CVR | BaseCVR) != CVR) continue; 7429 // Skip over volatile if no volatile found anywhere in the types. 7430 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7431 7432 // Skip over restrict if no restrict found anywhere in the types, or if 7433 // the type cannot be restrict-qualified. 7434 if ((CVR & Qualifiers::Restrict) && 7435 (!hasRestrict || 7436 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7437 continue; 7438 7439 // Build qualified pointee type. 7440 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7441 7442 // Build qualified pointer type. 7443 QualType QPointerTy; 7444 if (!buildObjCPtr) 7445 QPointerTy = Context.getPointerType(QPointeeTy); 7446 else 7447 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7448 7449 // Insert qualified pointer type. 7450 PointerTypes.insert(QPointerTy); 7451 } 7452 7453 return true; 7454 } 7455 7456 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7457 /// to the set of pointer types along with any more-qualified variants of 7458 /// that type. For example, if @p Ty is "int const *", this routine 7459 /// will add "int const *", "int const volatile *", "int const 7460 /// restrict *", and "int const volatile restrict *" to the set of 7461 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7462 /// false otherwise. 7463 /// 7464 /// FIXME: what to do about extended qualifiers? 7465 bool 7466 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7467 QualType Ty) { 7468 // Insert this type. 7469 if (!MemberPointerTypes.insert(Ty)) 7470 return false; 7471 7472 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7473 assert(PointerTy && "type was not a member pointer type!"); 7474 7475 QualType PointeeTy = PointerTy->getPointeeType(); 7476 // Don't add qualified variants of arrays. For one, they're not allowed 7477 // (the qualifier would sink to the element type), and for another, the 7478 // only overload situation where it matters is subscript or pointer +- int, 7479 // and those shouldn't have qualifier variants anyway. 7480 if (PointeeTy->isArrayType()) 7481 return true; 7482 const Type *ClassTy = PointerTy->getClass(); 7483 7484 // Iterate through all strict supersets of the pointee type's CVR 7485 // qualifiers. 7486 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7487 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7488 if ((CVR | BaseCVR) != CVR) continue; 7489 7490 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7491 MemberPointerTypes.insert( 7492 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7493 } 7494 7495 return true; 7496 } 7497 7498 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7499 /// Ty can be implicit converted to the given set of @p Types. We're 7500 /// primarily interested in pointer types and enumeration types. We also 7501 /// take member pointer types, for the conditional operator. 7502 /// AllowUserConversions is true if we should look at the conversion 7503 /// functions of a class type, and AllowExplicitConversions if we 7504 /// should also include the explicit conversion functions of a class 7505 /// type. 7506 void 7507 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7508 SourceLocation Loc, 7509 bool AllowUserConversions, 7510 bool AllowExplicitConversions, 7511 const Qualifiers &VisibleQuals) { 7512 // Only deal with canonical types. 7513 Ty = Context.getCanonicalType(Ty); 7514 7515 // Look through reference types; they aren't part of the type of an 7516 // expression for the purposes of conversions. 7517 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7518 Ty = RefTy->getPointeeType(); 7519 7520 // If we're dealing with an array type, decay to the pointer. 7521 if (Ty->isArrayType()) 7522 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7523 7524 // Otherwise, we don't care about qualifiers on the type. 7525 Ty = Ty.getLocalUnqualifiedType(); 7526 7527 // Flag if we ever add a non-record type. 7528 const RecordType *TyRec = Ty->getAs<RecordType>(); 7529 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7530 7531 // Flag if we encounter an arithmetic type. 7532 HasArithmeticOrEnumeralTypes = 7533 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7534 7535 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7536 PointerTypes.insert(Ty); 7537 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7538 // Insert our type, and its more-qualified variants, into the set 7539 // of types. 7540 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7541 return; 7542 } else if (Ty->isMemberPointerType()) { 7543 // Member pointers are far easier, since the pointee can't be converted. 7544 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7545 return; 7546 } else if (Ty->isEnumeralType()) { 7547 HasArithmeticOrEnumeralTypes = true; 7548 EnumerationTypes.insert(Ty); 7549 } else if (Ty->isVectorType()) { 7550 // We treat vector types as arithmetic types in many contexts as an 7551 // extension. 7552 HasArithmeticOrEnumeralTypes = true; 7553 VectorTypes.insert(Ty); 7554 } else if (Ty->isNullPtrType()) { 7555 HasNullPtrType = true; 7556 } else if (AllowUserConversions && TyRec) { 7557 // No conversion functions in incomplete types. 7558 if (!SemaRef.isCompleteType(Loc, Ty)) 7559 return; 7560 7561 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7562 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7563 if (isa<UsingShadowDecl>(D)) 7564 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7565 7566 // Skip conversion function templates; they don't tell us anything 7567 // about which builtin types we can convert to. 7568 if (isa<FunctionTemplateDecl>(D)) 7569 continue; 7570 7571 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7572 if (AllowExplicitConversions || !Conv->isExplicit()) { 7573 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7574 VisibleQuals); 7575 } 7576 } 7577 } 7578 } 7579 7580 /// Helper function for AddBuiltinOperatorCandidates() that adds 7581 /// the volatile- and non-volatile-qualified assignment operators for the 7582 /// given type to the candidate set. 7583 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7584 QualType T, 7585 ArrayRef<Expr *> Args, 7586 OverloadCandidateSet &CandidateSet) { 7587 QualType ParamTypes[2]; 7588 7589 // T& operator=(T&, T) 7590 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7591 ParamTypes[1] = T; 7592 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7593 /*IsAssignmentOperator=*/true); 7594 7595 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7596 // volatile T& operator=(volatile T&, T) 7597 ParamTypes[0] 7598 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7599 ParamTypes[1] = T; 7600 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7601 /*IsAssignmentOperator=*/true); 7602 } 7603 } 7604 7605 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7606 /// if any, found in visible type conversion functions found in ArgExpr's type. 7607 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7608 Qualifiers VRQuals; 7609 const RecordType *TyRec; 7610 if (const MemberPointerType *RHSMPType = 7611 ArgExpr->getType()->getAs<MemberPointerType>()) 7612 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7613 else 7614 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7615 if (!TyRec) { 7616 // Just to be safe, assume the worst case. 7617 VRQuals.addVolatile(); 7618 VRQuals.addRestrict(); 7619 return VRQuals; 7620 } 7621 7622 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7623 if (!ClassDecl->hasDefinition()) 7624 return VRQuals; 7625 7626 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7627 if (isa<UsingShadowDecl>(D)) 7628 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7629 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7630 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7631 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7632 CanTy = ResTypeRef->getPointeeType(); 7633 // Need to go down the pointer/mempointer chain and add qualifiers 7634 // as see them. 7635 bool done = false; 7636 while (!done) { 7637 if (CanTy.isRestrictQualified()) 7638 VRQuals.addRestrict(); 7639 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7640 CanTy = ResTypePtr->getPointeeType(); 7641 else if (const MemberPointerType *ResTypeMPtr = 7642 CanTy->getAs<MemberPointerType>()) 7643 CanTy = ResTypeMPtr->getPointeeType(); 7644 else 7645 done = true; 7646 if (CanTy.isVolatileQualified()) 7647 VRQuals.addVolatile(); 7648 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7649 return VRQuals; 7650 } 7651 } 7652 } 7653 return VRQuals; 7654 } 7655 7656 namespace { 7657 7658 /// Helper class to manage the addition of builtin operator overload 7659 /// candidates. It provides shared state and utility methods used throughout 7660 /// the process, as well as a helper method to add each group of builtin 7661 /// operator overloads from the standard to a candidate set. 7662 class BuiltinOperatorOverloadBuilder { 7663 // Common instance state available to all overload candidate addition methods. 7664 Sema &S; 7665 ArrayRef<Expr *> Args; 7666 Qualifiers VisibleTypeConversionsQuals; 7667 bool HasArithmeticOrEnumeralCandidateType; 7668 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7669 OverloadCandidateSet &CandidateSet; 7670 7671 static constexpr int ArithmeticTypesCap = 24; 7672 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7673 7674 // Define some indices used to iterate over the arithemetic types in 7675 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7676 // types are that preserved by promotion (C++ [over.built]p2). 7677 unsigned FirstIntegralType, 7678 LastIntegralType; 7679 unsigned FirstPromotedIntegralType, 7680 LastPromotedIntegralType; 7681 unsigned FirstPromotedArithmeticType, 7682 LastPromotedArithmeticType; 7683 unsigned NumArithmeticTypes; 7684 7685 void InitArithmeticTypes() { 7686 // Start of promoted types. 7687 FirstPromotedArithmeticType = 0; 7688 ArithmeticTypes.push_back(S.Context.FloatTy); 7689 ArithmeticTypes.push_back(S.Context.DoubleTy); 7690 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7691 if (S.Context.getTargetInfo().hasFloat128Type()) 7692 ArithmeticTypes.push_back(S.Context.Float128Ty); 7693 7694 // Start of integral types. 7695 FirstIntegralType = ArithmeticTypes.size(); 7696 FirstPromotedIntegralType = ArithmeticTypes.size(); 7697 ArithmeticTypes.push_back(S.Context.IntTy); 7698 ArithmeticTypes.push_back(S.Context.LongTy); 7699 ArithmeticTypes.push_back(S.Context.LongLongTy); 7700 if (S.Context.getTargetInfo().hasInt128Type()) 7701 ArithmeticTypes.push_back(S.Context.Int128Ty); 7702 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7703 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7704 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7705 if (S.Context.getTargetInfo().hasInt128Type()) 7706 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7707 LastPromotedIntegralType = ArithmeticTypes.size(); 7708 LastPromotedArithmeticType = ArithmeticTypes.size(); 7709 // End of promoted types. 7710 7711 ArithmeticTypes.push_back(S.Context.BoolTy); 7712 ArithmeticTypes.push_back(S.Context.CharTy); 7713 ArithmeticTypes.push_back(S.Context.WCharTy); 7714 if (S.Context.getLangOpts().Char8) 7715 ArithmeticTypes.push_back(S.Context.Char8Ty); 7716 ArithmeticTypes.push_back(S.Context.Char16Ty); 7717 ArithmeticTypes.push_back(S.Context.Char32Ty); 7718 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7719 ArithmeticTypes.push_back(S.Context.ShortTy); 7720 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7721 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7722 LastIntegralType = ArithmeticTypes.size(); 7723 NumArithmeticTypes = ArithmeticTypes.size(); 7724 // End of integral types. 7725 // FIXME: What about complex? What about half? 7726 7727 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7728 "Enough inline storage for all arithmetic types."); 7729 } 7730 7731 /// Helper method to factor out the common pattern of adding overloads 7732 /// for '++' and '--' builtin operators. 7733 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7734 bool HasVolatile, 7735 bool HasRestrict) { 7736 QualType ParamTypes[2] = { 7737 S.Context.getLValueReferenceType(CandidateTy), 7738 S.Context.IntTy 7739 }; 7740 7741 // Non-volatile version. 7742 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7743 7744 // Use a heuristic to reduce number of builtin candidates in the set: 7745 // add volatile version only if there are conversions to a volatile type. 7746 if (HasVolatile) { 7747 ParamTypes[0] = 7748 S.Context.getLValueReferenceType( 7749 S.Context.getVolatileType(CandidateTy)); 7750 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7751 } 7752 7753 // Add restrict version only if there are conversions to a restrict type 7754 // and our candidate type is a non-restrict-qualified pointer. 7755 if (HasRestrict && CandidateTy->isAnyPointerType() && 7756 !CandidateTy.isRestrictQualified()) { 7757 ParamTypes[0] 7758 = S.Context.getLValueReferenceType( 7759 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7760 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7761 7762 if (HasVolatile) { 7763 ParamTypes[0] 7764 = S.Context.getLValueReferenceType( 7765 S.Context.getCVRQualifiedType(CandidateTy, 7766 (Qualifiers::Volatile | 7767 Qualifiers::Restrict))); 7768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7769 } 7770 } 7771 7772 } 7773 7774 public: 7775 BuiltinOperatorOverloadBuilder( 7776 Sema &S, ArrayRef<Expr *> Args, 7777 Qualifiers VisibleTypeConversionsQuals, 7778 bool HasArithmeticOrEnumeralCandidateType, 7779 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7780 OverloadCandidateSet &CandidateSet) 7781 : S(S), Args(Args), 7782 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7783 HasArithmeticOrEnumeralCandidateType( 7784 HasArithmeticOrEnumeralCandidateType), 7785 CandidateTypes(CandidateTypes), 7786 CandidateSet(CandidateSet) { 7787 7788 InitArithmeticTypes(); 7789 } 7790 7791 // Increment is deprecated for bool since C++17. 7792 // 7793 // C++ [over.built]p3: 7794 // 7795 // For every pair (T, VQ), where T is an arithmetic type other 7796 // than bool, and VQ is either volatile or empty, there exist 7797 // candidate operator functions of the form 7798 // 7799 // VQ T& operator++(VQ T&); 7800 // T operator++(VQ T&, int); 7801 // 7802 // C++ [over.built]p4: 7803 // 7804 // For every pair (T, VQ), where T is an arithmetic type other 7805 // than bool, and VQ is either volatile or empty, there exist 7806 // candidate operator functions of the form 7807 // 7808 // VQ T& operator--(VQ T&); 7809 // T operator--(VQ T&, int); 7810 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7811 if (!HasArithmeticOrEnumeralCandidateType) 7812 return; 7813 7814 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7815 const auto TypeOfT = ArithmeticTypes[Arith]; 7816 if (TypeOfT == S.Context.BoolTy) { 7817 if (Op == OO_MinusMinus) 7818 continue; 7819 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7820 continue; 7821 } 7822 addPlusPlusMinusMinusStyleOverloads( 7823 TypeOfT, 7824 VisibleTypeConversionsQuals.hasVolatile(), 7825 VisibleTypeConversionsQuals.hasRestrict()); 7826 } 7827 } 7828 7829 // C++ [over.built]p5: 7830 // 7831 // For every pair (T, VQ), where T is a cv-qualified or 7832 // cv-unqualified object type, and VQ is either volatile or 7833 // empty, there exist candidate operator functions of the form 7834 // 7835 // T*VQ& operator++(T*VQ&); 7836 // T*VQ& operator--(T*VQ&); 7837 // T* operator++(T*VQ&, int); 7838 // T* operator--(T*VQ&, int); 7839 void addPlusPlusMinusMinusPointerOverloads() { 7840 for (BuiltinCandidateTypeSet::iterator 7841 Ptr = CandidateTypes[0].pointer_begin(), 7842 PtrEnd = CandidateTypes[0].pointer_end(); 7843 Ptr != PtrEnd; ++Ptr) { 7844 // Skip pointer types that aren't pointers to object types. 7845 if (!(*Ptr)->getPointeeType()->isObjectType()) 7846 continue; 7847 7848 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7849 (!(*Ptr).isVolatileQualified() && 7850 VisibleTypeConversionsQuals.hasVolatile()), 7851 (!(*Ptr).isRestrictQualified() && 7852 VisibleTypeConversionsQuals.hasRestrict())); 7853 } 7854 } 7855 7856 // C++ [over.built]p6: 7857 // For every cv-qualified or cv-unqualified object type T, there 7858 // exist candidate operator functions of the form 7859 // 7860 // T& operator*(T*); 7861 // 7862 // C++ [over.built]p7: 7863 // For every function type T that does not have cv-qualifiers or a 7864 // ref-qualifier, there exist candidate operator functions of the form 7865 // T& operator*(T*); 7866 void addUnaryStarPointerOverloads() { 7867 for (BuiltinCandidateTypeSet::iterator 7868 Ptr = CandidateTypes[0].pointer_begin(), 7869 PtrEnd = CandidateTypes[0].pointer_end(); 7870 Ptr != PtrEnd; ++Ptr) { 7871 QualType ParamTy = *Ptr; 7872 QualType PointeeTy = ParamTy->getPointeeType(); 7873 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7874 continue; 7875 7876 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7877 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7878 continue; 7879 7880 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7881 } 7882 } 7883 7884 // C++ [over.built]p9: 7885 // For every promoted arithmetic type T, there exist candidate 7886 // operator functions of the form 7887 // 7888 // T operator+(T); 7889 // T operator-(T); 7890 void addUnaryPlusOrMinusArithmeticOverloads() { 7891 if (!HasArithmeticOrEnumeralCandidateType) 7892 return; 7893 7894 for (unsigned Arith = FirstPromotedArithmeticType; 7895 Arith < LastPromotedArithmeticType; ++Arith) { 7896 QualType ArithTy = ArithmeticTypes[Arith]; 7897 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7898 } 7899 7900 // Extension: We also add these operators for vector types. 7901 for (BuiltinCandidateTypeSet::iterator 7902 Vec = CandidateTypes[0].vector_begin(), 7903 VecEnd = CandidateTypes[0].vector_end(); 7904 Vec != VecEnd; ++Vec) { 7905 QualType VecTy = *Vec; 7906 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7907 } 7908 } 7909 7910 // C++ [over.built]p8: 7911 // For every type T, there exist candidate operator functions of 7912 // the form 7913 // 7914 // T* operator+(T*); 7915 void addUnaryPlusPointerOverloads() { 7916 for (BuiltinCandidateTypeSet::iterator 7917 Ptr = CandidateTypes[0].pointer_begin(), 7918 PtrEnd = CandidateTypes[0].pointer_end(); 7919 Ptr != PtrEnd; ++Ptr) { 7920 QualType ParamTy = *Ptr; 7921 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7922 } 7923 } 7924 7925 // C++ [over.built]p10: 7926 // For every promoted integral type T, there exist candidate 7927 // operator functions of the form 7928 // 7929 // T operator~(T); 7930 void addUnaryTildePromotedIntegralOverloads() { 7931 if (!HasArithmeticOrEnumeralCandidateType) 7932 return; 7933 7934 for (unsigned Int = FirstPromotedIntegralType; 7935 Int < LastPromotedIntegralType; ++Int) { 7936 QualType IntTy = ArithmeticTypes[Int]; 7937 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 7938 } 7939 7940 // Extension: We also add this operator for vector types. 7941 for (BuiltinCandidateTypeSet::iterator 7942 Vec = CandidateTypes[0].vector_begin(), 7943 VecEnd = CandidateTypes[0].vector_end(); 7944 Vec != VecEnd; ++Vec) { 7945 QualType VecTy = *Vec; 7946 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7947 } 7948 } 7949 7950 // C++ [over.match.oper]p16: 7951 // For every pointer to member type T or type std::nullptr_t, there 7952 // exist candidate operator functions of the form 7953 // 7954 // bool operator==(T,T); 7955 // bool operator!=(T,T); 7956 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7957 /// Set of (canonical) types that we've already handled. 7958 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7959 7960 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7961 for (BuiltinCandidateTypeSet::iterator 7962 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7963 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7964 MemPtr != MemPtrEnd; 7965 ++MemPtr) { 7966 // Don't add the same builtin candidate twice. 7967 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7968 continue; 7969 7970 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7971 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7972 } 7973 7974 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7975 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7976 if (AddedTypes.insert(NullPtrTy).second) { 7977 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7978 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7979 } 7980 } 7981 } 7982 } 7983 7984 // C++ [over.built]p15: 7985 // 7986 // For every T, where T is an enumeration type or a pointer type, 7987 // there exist candidate operator functions of the form 7988 // 7989 // bool operator<(T, T); 7990 // bool operator>(T, T); 7991 // bool operator<=(T, T); 7992 // bool operator>=(T, T); 7993 // bool operator==(T, T); 7994 // bool operator!=(T, T); 7995 // R operator<=>(T, T) 7996 void addGenericBinaryPointerOrEnumeralOverloads() { 7997 // C++ [over.match.oper]p3: 7998 // [...]the built-in candidates include all of the candidate operator 7999 // functions defined in 13.6 that, compared to the given operator, [...] 8000 // do not have the same parameter-type-list as any non-template non-member 8001 // candidate. 8002 // 8003 // Note that in practice, this only affects enumeration types because there 8004 // aren't any built-in candidates of record type, and a user-defined operator 8005 // must have an operand of record or enumeration type. Also, the only other 8006 // overloaded operator with enumeration arguments, operator=, 8007 // cannot be overloaded for enumeration types, so this is the only place 8008 // where we must suppress candidates like this. 8009 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8010 UserDefinedBinaryOperators; 8011 8012 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8013 if (CandidateTypes[ArgIdx].enumeration_begin() != 8014 CandidateTypes[ArgIdx].enumeration_end()) { 8015 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8016 CEnd = CandidateSet.end(); 8017 C != CEnd; ++C) { 8018 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8019 continue; 8020 8021 if (C->Function->isFunctionTemplateSpecialization()) 8022 continue; 8023 8024 QualType FirstParamType = 8025 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8026 QualType SecondParamType = 8027 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8028 8029 // Skip if either parameter isn't of enumeral type. 8030 if (!FirstParamType->isEnumeralType() || 8031 !SecondParamType->isEnumeralType()) 8032 continue; 8033 8034 // Add this operator to the set of known user-defined operators. 8035 UserDefinedBinaryOperators.insert( 8036 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8037 S.Context.getCanonicalType(SecondParamType))); 8038 } 8039 } 8040 } 8041 8042 /// Set of (canonical) types that we've already handled. 8043 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8044 8045 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8046 for (BuiltinCandidateTypeSet::iterator 8047 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8048 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8049 Ptr != PtrEnd; ++Ptr) { 8050 // Don't add the same builtin candidate twice. 8051 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8052 continue; 8053 8054 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8055 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8056 } 8057 for (BuiltinCandidateTypeSet::iterator 8058 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8059 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8060 Enum != EnumEnd; ++Enum) { 8061 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8062 8063 // Don't add the same builtin candidate twice, or if a user defined 8064 // candidate exists. 8065 if (!AddedTypes.insert(CanonType).second || 8066 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8067 CanonType))) 8068 continue; 8069 QualType ParamTypes[2] = { *Enum, *Enum }; 8070 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8071 } 8072 } 8073 } 8074 8075 // C++ [over.built]p13: 8076 // 8077 // For every cv-qualified or cv-unqualified object type T 8078 // there exist candidate operator functions of the form 8079 // 8080 // T* operator+(T*, ptrdiff_t); 8081 // T& operator[](T*, ptrdiff_t); [BELOW] 8082 // T* operator-(T*, ptrdiff_t); 8083 // T* operator+(ptrdiff_t, T*); 8084 // T& operator[](ptrdiff_t, T*); [BELOW] 8085 // 8086 // C++ [over.built]p14: 8087 // 8088 // For every T, where T is a pointer to object type, there 8089 // exist candidate operator functions of the form 8090 // 8091 // ptrdiff_t operator-(T, T); 8092 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8093 /// Set of (canonical) types that we've already handled. 8094 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8095 8096 for (int Arg = 0; Arg < 2; ++Arg) { 8097 QualType AsymmetricParamTypes[2] = { 8098 S.Context.getPointerDiffType(), 8099 S.Context.getPointerDiffType(), 8100 }; 8101 for (BuiltinCandidateTypeSet::iterator 8102 Ptr = CandidateTypes[Arg].pointer_begin(), 8103 PtrEnd = CandidateTypes[Arg].pointer_end(); 8104 Ptr != PtrEnd; ++Ptr) { 8105 QualType PointeeTy = (*Ptr)->getPointeeType(); 8106 if (!PointeeTy->isObjectType()) 8107 continue; 8108 8109 AsymmetricParamTypes[Arg] = *Ptr; 8110 if (Arg == 0 || Op == OO_Plus) { 8111 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8112 // T* operator+(ptrdiff_t, T*); 8113 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8114 } 8115 if (Op == OO_Minus) { 8116 // ptrdiff_t operator-(T, T); 8117 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8118 continue; 8119 8120 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8121 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8122 } 8123 } 8124 } 8125 } 8126 8127 // C++ [over.built]p12: 8128 // 8129 // For every pair of promoted arithmetic types L and R, there 8130 // exist candidate operator functions of the form 8131 // 8132 // LR operator*(L, R); 8133 // LR operator/(L, R); 8134 // LR operator+(L, R); 8135 // LR operator-(L, R); 8136 // bool operator<(L, R); 8137 // bool operator>(L, R); 8138 // bool operator<=(L, R); 8139 // bool operator>=(L, R); 8140 // bool operator==(L, R); 8141 // bool operator!=(L, R); 8142 // 8143 // where LR is the result of the usual arithmetic conversions 8144 // between types L and R. 8145 // 8146 // C++ [over.built]p24: 8147 // 8148 // For every pair of promoted arithmetic types L and R, there exist 8149 // candidate operator functions of the form 8150 // 8151 // LR operator?(bool, L, R); 8152 // 8153 // where LR is the result of the usual arithmetic conversions 8154 // between types L and R. 8155 // Our candidates ignore the first parameter. 8156 void addGenericBinaryArithmeticOverloads() { 8157 if (!HasArithmeticOrEnumeralCandidateType) 8158 return; 8159 8160 for (unsigned Left = FirstPromotedArithmeticType; 8161 Left < LastPromotedArithmeticType; ++Left) { 8162 for (unsigned Right = FirstPromotedArithmeticType; 8163 Right < LastPromotedArithmeticType; ++Right) { 8164 QualType LandR[2] = { ArithmeticTypes[Left], 8165 ArithmeticTypes[Right] }; 8166 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8167 } 8168 } 8169 8170 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8171 // conditional operator for vector types. 8172 for (BuiltinCandidateTypeSet::iterator 8173 Vec1 = CandidateTypes[0].vector_begin(), 8174 Vec1End = CandidateTypes[0].vector_end(); 8175 Vec1 != Vec1End; ++Vec1) { 8176 for (BuiltinCandidateTypeSet::iterator 8177 Vec2 = CandidateTypes[1].vector_begin(), 8178 Vec2End = CandidateTypes[1].vector_end(); 8179 Vec2 != Vec2End; ++Vec2) { 8180 QualType LandR[2] = { *Vec1, *Vec2 }; 8181 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8182 } 8183 } 8184 } 8185 8186 // C++2a [over.built]p14: 8187 // 8188 // For every integral type T there exists a candidate operator function 8189 // of the form 8190 // 8191 // std::strong_ordering operator<=>(T, T) 8192 // 8193 // C++2a [over.built]p15: 8194 // 8195 // For every pair of floating-point types L and R, there exists a candidate 8196 // operator function of the form 8197 // 8198 // std::partial_ordering operator<=>(L, R); 8199 // 8200 // FIXME: The current specification for integral types doesn't play nice with 8201 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8202 // comparisons. Under the current spec this can lead to ambiguity during 8203 // overload resolution. For example: 8204 // 8205 // enum A : int {a}; 8206 // auto x = (a <=> (long)42); 8207 // 8208 // error: call is ambiguous for arguments 'A' and 'long'. 8209 // note: candidate operator<=>(int, int) 8210 // note: candidate operator<=>(long, long) 8211 // 8212 // To avoid this error, this function deviates from the specification and adds 8213 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8214 // arithmetic types (the same as the generic relational overloads). 8215 // 8216 // For now this function acts as a placeholder. 8217 void addThreeWayArithmeticOverloads() { 8218 addGenericBinaryArithmeticOverloads(); 8219 } 8220 8221 // C++ [over.built]p17: 8222 // 8223 // For every pair of promoted integral types L and R, there 8224 // exist candidate operator functions of the form 8225 // 8226 // LR operator%(L, R); 8227 // LR operator&(L, R); 8228 // LR operator^(L, R); 8229 // LR operator|(L, R); 8230 // L operator<<(L, R); 8231 // L operator>>(L, R); 8232 // 8233 // where LR is the result of the usual arithmetic conversions 8234 // between types L and R. 8235 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8236 if (!HasArithmeticOrEnumeralCandidateType) 8237 return; 8238 8239 for (unsigned Left = FirstPromotedIntegralType; 8240 Left < LastPromotedIntegralType; ++Left) { 8241 for (unsigned Right = FirstPromotedIntegralType; 8242 Right < LastPromotedIntegralType; ++Right) { 8243 QualType LandR[2] = { ArithmeticTypes[Left], 8244 ArithmeticTypes[Right] }; 8245 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8246 } 8247 } 8248 } 8249 8250 // C++ [over.built]p20: 8251 // 8252 // For every pair (T, VQ), where T is an enumeration or 8253 // pointer to member type and VQ is either volatile or 8254 // empty, there exist candidate operator functions of the form 8255 // 8256 // VQ T& operator=(VQ T&, T); 8257 void addAssignmentMemberPointerOrEnumeralOverloads() { 8258 /// Set of (canonical) types that we've already handled. 8259 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8260 8261 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8262 for (BuiltinCandidateTypeSet::iterator 8263 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8264 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8265 Enum != EnumEnd; ++Enum) { 8266 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8267 continue; 8268 8269 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8270 } 8271 8272 for (BuiltinCandidateTypeSet::iterator 8273 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8274 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8275 MemPtr != MemPtrEnd; ++MemPtr) { 8276 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8277 continue; 8278 8279 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8280 } 8281 } 8282 } 8283 8284 // C++ [over.built]p19: 8285 // 8286 // For every pair (T, VQ), where T is any type and VQ is either 8287 // volatile or empty, there exist candidate operator functions 8288 // of the form 8289 // 8290 // T*VQ& operator=(T*VQ&, T*); 8291 // 8292 // C++ [over.built]p21: 8293 // 8294 // For every pair (T, VQ), where T is a cv-qualified or 8295 // cv-unqualified object type and VQ is either volatile or 8296 // empty, there exist candidate operator functions of the form 8297 // 8298 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8299 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8300 void addAssignmentPointerOverloads(bool isEqualOp) { 8301 /// Set of (canonical) types that we've already handled. 8302 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8303 8304 for (BuiltinCandidateTypeSet::iterator 8305 Ptr = CandidateTypes[0].pointer_begin(), 8306 PtrEnd = CandidateTypes[0].pointer_end(); 8307 Ptr != PtrEnd; ++Ptr) { 8308 // If this is operator=, keep track of the builtin candidates we added. 8309 if (isEqualOp) 8310 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8311 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8312 continue; 8313 8314 // non-volatile version 8315 QualType ParamTypes[2] = { 8316 S.Context.getLValueReferenceType(*Ptr), 8317 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8318 }; 8319 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8320 /*IsAssigmentOperator=*/ isEqualOp); 8321 8322 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8323 VisibleTypeConversionsQuals.hasVolatile(); 8324 if (NeedVolatile) { 8325 // volatile version 8326 ParamTypes[0] = 8327 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8328 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8329 /*IsAssigmentOperator=*/isEqualOp); 8330 } 8331 8332 if (!(*Ptr).isRestrictQualified() && 8333 VisibleTypeConversionsQuals.hasRestrict()) { 8334 // restrict version 8335 ParamTypes[0] 8336 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8337 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8338 /*IsAssigmentOperator=*/isEqualOp); 8339 8340 if (NeedVolatile) { 8341 // volatile restrict version 8342 ParamTypes[0] 8343 = S.Context.getLValueReferenceType( 8344 S.Context.getCVRQualifiedType(*Ptr, 8345 (Qualifiers::Volatile | 8346 Qualifiers::Restrict))); 8347 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8348 /*IsAssigmentOperator=*/isEqualOp); 8349 } 8350 } 8351 } 8352 8353 if (isEqualOp) { 8354 for (BuiltinCandidateTypeSet::iterator 8355 Ptr = CandidateTypes[1].pointer_begin(), 8356 PtrEnd = CandidateTypes[1].pointer_end(); 8357 Ptr != PtrEnd; ++Ptr) { 8358 // Make sure we don't add the same candidate twice. 8359 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8360 continue; 8361 8362 QualType ParamTypes[2] = { 8363 S.Context.getLValueReferenceType(*Ptr), 8364 *Ptr, 8365 }; 8366 8367 // non-volatile version 8368 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8369 /*IsAssigmentOperator=*/true); 8370 8371 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8372 VisibleTypeConversionsQuals.hasVolatile(); 8373 if (NeedVolatile) { 8374 // volatile version 8375 ParamTypes[0] = 8376 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8377 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8378 /*IsAssigmentOperator=*/true); 8379 } 8380 8381 if (!(*Ptr).isRestrictQualified() && 8382 VisibleTypeConversionsQuals.hasRestrict()) { 8383 // restrict version 8384 ParamTypes[0] 8385 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8386 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8387 /*IsAssigmentOperator=*/true); 8388 8389 if (NeedVolatile) { 8390 // volatile restrict version 8391 ParamTypes[0] 8392 = S.Context.getLValueReferenceType( 8393 S.Context.getCVRQualifiedType(*Ptr, 8394 (Qualifiers::Volatile | 8395 Qualifiers::Restrict))); 8396 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8397 /*IsAssigmentOperator=*/true); 8398 } 8399 } 8400 } 8401 } 8402 } 8403 8404 // C++ [over.built]p18: 8405 // 8406 // For every triple (L, VQ, R), where L is an arithmetic type, 8407 // VQ is either volatile or empty, and R is a promoted 8408 // arithmetic type, there exist candidate operator functions of 8409 // the form 8410 // 8411 // VQ L& operator=(VQ L&, R); 8412 // VQ L& operator*=(VQ L&, R); 8413 // VQ L& operator/=(VQ L&, R); 8414 // VQ L& operator+=(VQ L&, R); 8415 // VQ L& operator-=(VQ L&, R); 8416 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8417 if (!HasArithmeticOrEnumeralCandidateType) 8418 return; 8419 8420 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8421 for (unsigned Right = FirstPromotedArithmeticType; 8422 Right < LastPromotedArithmeticType; ++Right) { 8423 QualType ParamTypes[2]; 8424 ParamTypes[1] = ArithmeticTypes[Right]; 8425 8426 // Add this built-in operator as a candidate (VQ is empty). 8427 ParamTypes[0] = 8428 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8429 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8430 /*IsAssigmentOperator=*/isEqualOp); 8431 8432 // Add this built-in operator as a candidate (VQ is 'volatile'). 8433 if (VisibleTypeConversionsQuals.hasVolatile()) { 8434 ParamTypes[0] = 8435 S.Context.getVolatileType(ArithmeticTypes[Left]); 8436 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8437 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8438 /*IsAssigmentOperator=*/isEqualOp); 8439 } 8440 } 8441 } 8442 8443 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8444 for (BuiltinCandidateTypeSet::iterator 8445 Vec1 = CandidateTypes[0].vector_begin(), 8446 Vec1End = CandidateTypes[0].vector_end(); 8447 Vec1 != Vec1End; ++Vec1) { 8448 for (BuiltinCandidateTypeSet::iterator 8449 Vec2 = CandidateTypes[1].vector_begin(), 8450 Vec2End = CandidateTypes[1].vector_end(); 8451 Vec2 != Vec2End; ++Vec2) { 8452 QualType ParamTypes[2]; 8453 ParamTypes[1] = *Vec2; 8454 // Add this built-in operator as a candidate (VQ is empty). 8455 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8456 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8457 /*IsAssigmentOperator=*/isEqualOp); 8458 8459 // Add this built-in operator as a candidate (VQ is 'volatile'). 8460 if (VisibleTypeConversionsQuals.hasVolatile()) { 8461 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8462 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8463 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8464 /*IsAssigmentOperator=*/isEqualOp); 8465 } 8466 } 8467 } 8468 } 8469 8470 // C++ [over.built]p22: 8471 // 8472 // For every triple (L, VQ, R), where L is an integral type, VQ 8473 // is either volatile or empty, and R is a promoted integral 8474 // type, there exist candidate operator functions of the form 8475 // 8476 // VQ L& operator%=(VQ L&, R); 8477 // VQ L& operator<<=(VQ L&, R); 8478 // VQ L& operator>>=(VQ L&, R); 8479 // VQ L& operator&=(VQ L&, R); 8480 // VQ L& operator^=(VQ L&, R); 8481 // VQ L& operator|=(VQ L&, R); 8482 void addAssignmentIntegralOverloads() { 8483 if (!HasArithmeticOrEnumeralCandidateType) 8484 return; 8485 8486 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8487 for (unsigned Right = FirstPromotedIntegralType; 8488 Right < LastPromotedIntegralType; ++Right) { 8489 QualType ParamTypes[2]; 8490 ParamTypes[1] = ArithmeticTypes[Right]; 8491 8492 // Add this built-in operator as a candidate (VQ is empty). 8493 ParamTypes[0] = 8494 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8495 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8496 if (VisibleTypeConversionsQuals.hasVolatile()) { 8497 // Add this built-in operator as a candidate (VQ is 'volatile'). 8498 ParamTypes[0] = ArithmeticTypes[Left]; 8499 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8500 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8501 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8502 } 8503 } 8504 } 8505 } 8506 8507 // C++ [over.operator]p23: 8508 // 8509 // There also exist candidate operator functions of the form 8510 // 8511 // bool operator!(bool); 8512 // bool operator&&(bool, bool); 8513 // bool operator||(bool, bool); 8514 void addExclaimOverload() { 8515 QualType ParamTy = S.Context.BoolTy; 8516 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8517 /*IsAssignmentOperator=*/false, 8518 /*NumContextualBoolArguments=*/1); 8519 } 8520 void addAmpAmpOrPipePipeOverload() { 8521 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8522 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8523 /*IsAssignmentOperator=*/false, 8524 /*NumContextualBoolArguments=*/2); 8525 } 8526 8527 // C++ [over.built]p13: 8528 // 8529 // For every cv-qualified or cv-unqualified object type T there 8530 // exist candidate operator functions of the form 8531 // 8532 // T* operator+(T*, ptrdiff_t); [ABOVE] 8533 // T& operator[](T*, ptrdiff_t); 8534 // T* operator-(T*, ptrdiff_t); [ABOVE] 8535 // T* operator+(ptrdiff_t, T*); [ABOVE] 8536 // T& operator[](ptrdiff_t, T*); 8537 void addSubscriptOverloads() { 8538 for (BuiltinCandidateTypeSet::iterator 8539 Ptr = CandidateTypes[0].pointer_begin(), 8540 PtrEnd = CandidateTypes[0].pointer_end(); 8541 Ptr != PtrEnd; ++Ptr) { 8542 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8543 QualType PointeeType = (*Ptr)->getPointeeType(); 8544 if (!PointeeType->isObjectType()) 8545 continue; 8546 8547 // T& operator[](T*, ptrdiff_t) 8548 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8549 } 8550 8551 for (BuiltinCandidateTypeSet::iterator 8552 Ptr = CandidateTypes[1].pointer_begin(), 8553 PtrEnd = CandidateTypes[1].pointer_end(); 8554 Ptr != PtrEnd; ++Ptr) { 8555 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8556 QualType PointeeType = (*Ptr)->getPointeeType(); 8557 if (!PointeeType->isObjectType()) 8558 continue; 8559 8560 // T& operator[](ptrdiff_t, T*) 8561 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8562 } 8563 } 8564 8565 // C++ [over.built]p11: 8566 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8567 // C1 is the same type as C2 or is a derived class of C2, T is an object 8568 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8569 // there exist candidate operator functions of the form 8570 // 8571 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8572 // 8573 // where CV12 is the union of CV1 and CV2. 8574 void addArrowStarOverloads() { 8575 for (BuiltinCandidateTypeSet::iterator 8576 Ptr = CandidateTypes[0].pointer_begin(), 8577 PtrEnd = CandidateTypes[0].pointer_end(); 8578 Ptr != PtrEnd; ++Ptr) { 8579 QualType C1Ty = (*Ptr); 8580 QualType C1; 8581 QualifierCollector Q1; 8582 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8583 if (!isa<RecordType>(C1)) 8584 continue; 8585 // heuristic to reduce number of builtin candidates in the set. 8586 // Add volatile/restrict version only if there are conversions to a 8587 // volatile/restrict type. 8588 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8589 continue; 8590 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8591 continue; 8592 for (BuiltinCandidateTypeSet::iterator 8593 MemPtr = CandidateTypes[1].member_pointer_begin(), 8594 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8595 MemPtr != MemPtrEnd; ++MemPtr) { 8596 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8597 QualType C2 = QualType(mptr->getClass(), 0); 8598 C2 = C2.getUnqualifiedType(); 8599 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8600 break; 8601 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8602 // build CV12 T& 8603 QualType T = mptr->getPointeeType(); 8604 if (!VisibleTypeConversionsQuals.hasVolatile() && 8605 T.isVolatileQualified()) 8606 continue; 8607 if (!VisibleTypeConversionsQuals.hasRestrict() && 8608 T.isRestrictQualified()) 8609 continue; 8610 T = Q1.apply(S.Context, T); 8611 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8612 } 8613 } 8614 } 8615 8616 // Note that we don't consider the first argument, since it has been 8617 // contextually converted to bool long ago. The candidates below are 8618 // therefore added as binary. 8619 // 8620 // C++ [over.built]p25: 8621 // For every type T, where T is a pointer, pointer-to-member, or scoped 8622 // enumeration type, there exist candidate operator functions of the form 8623 // 8624 // T operator?(bool, T, T); 8625 // 8626 void addConditionalOperatorOverloads() { 8627 /// Set of (canonical) types that we've already handled. 8628 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8629 8630 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8631 for (BuiltinCandidateTypeSet::iterator 8632 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8633 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8634 Ptr != PtrEnd; ++Ptr) { 8635 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8636 continue; 8637 8638 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8639 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8640 } 8641 8642 for (BuiltinCandidateTypeSet::iterator 8643 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8644 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8645 MemPtr != MemPtrEnd; ++MemPtr) { 8646 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8647 continue; 8648 8649 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8650 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8651 } 8652 8653 if (S.getLangOpts().CPlusPlus11) { 8654 for (BuiltinCandidateTypeSet::iterator 8655 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8656 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8657 Enum != EnumEnd; ++Enum) { 8658 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8659 continue; 8660 8661 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8662 continue; 8663 8664 QualType ParamTypes[2] = { *Enum, *Enum }; 8665 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8666 } 8667 } 8668 } 8669 } 8670 }; 8671 8672 } // end anonymous namespace 8673 8674 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8675 /// operator overloads to the candidate set (C++ [over.built]), based 8676 /// on the operator @p Op and the arguments given. For example, if the 8677 /// operator is a binary '+', this routine might add "int 8678 /// operator+(int, int)" to cover integer addition. 8679 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8680 SourceLocation OpLoc, 8681 ArrayRef<Expr *> Args, 8682 OverloadCandidateSet &CandidateSet) { 8683 // Find all of the types that the arguments can convert to, but only 8684 // if the operator we're looking at has built-in operator candidates 8685 // that make use of these types. Also record whether we encounter non-record 8686 // candidate types or either arithmetic or enumeral candidate types. 8687 Qualifiers VisibleTypeConversionsQuals; 8688 VisibleTypeConversionsQuals.addConst(); 8689 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8690 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8691 8692 bool HasNonRecordCandidateType = false; 8693 bool HasArithmeticOrEnumeralCandidateType = false; 8694 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8695 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8696 CandidateTypes.emplace_back(*this); 8697 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8698 OpLoc, 8699 true, 8700 (Op == OO_Exclaim || 8701 Op == OO_AmpAmp || 8702 Op == OO_PipePipe), 8703 VisibleTypeConversionsQuals); 8704 HasNonRecordCandidateType = HasNonRecordCandidateType || 8705 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8706 HasArithmeticOrEnumeralCandidateType = 8707 HasArithmeticOrEnumeralCandidateType || 8708 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8709 } 8710 8711 // Exit early when no non-record types have been added to the candidate set 8712 // for any of the arguments to the operator. 8713 // 8714 // We can't exit early for !, ||, or &&, since there we have always have 8715 // 'bool' overloads. 8716 if (!HasNonRecordCandidateType && 8717 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8718 return; 8719 8720 // Setup an object to manage the common state for building overloads. 8721 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8722 VisibleTypeConversionsQuals, 8723 HasArithmeticOrEnumeralCandidateType, 8724 CandidateTypes, CandidateSet); 8725 8726 // Dispatch over the operation to add in only those overloads which apply. 8727 switch (Op) { 8728 case OO_None: 8729 case NUM_OVERLOADED_OPERATORS: 8730 llvm_unreachable("Expected an overloaded operator"); 8731 8732 case OO_New: 8733 case OO_Delete: 8734 case OO_Array_New: 8735 case OO_Array_Delete: 8736 case OO_Call: 8737 llvm_unreachable( 8738 "Special operators don't use AddBuiltinOperatorCandidates"); 8739 8740 case OO_Comma: 8741 case OO_Arrow: 8742 case OO_Coawait: 8743 // C++ [over.match.oper]p3: 8744 // -- For the operator ',', the unary operator '&', the 8745 // operator '->', or the operator 'co_await', the 8746 // built-in candidates set is empty. 8747 break; 8748 8749 case OO_Plus: // '+' is either unary or binary 8750 if (Args.size() == 1) 8751 OpBuilder.addUnaryPlusPointerOverloads(); 8752 LLVM_FALLTHROUGH; 8753 8754 case OO_Minus: // '-' is either unary or binary 8755 if (Args.size() == 1) { 8756 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8757 } else { 8758 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8759 OpBuilder.addGenericBinaryArithmeticOverloads(); 8760 } 8761 break; 8762 8763 case OO_Star: // '*' is either unary or binary 8764 if (Args.size() == 1) 8765 OpBuilder.addUnaryStarPointerOverloads(); 8766 else 8767 OpBuilder.addGenericBinaryArithmeticOverloads(); 8768 break; 8769 8770 case OO_Slash: 8771 OpBuilder.addGenericBinaryArithmeticOverloads(); 8772 break; 8773 8774 case OO_PlusPlus: 8775 case OO_MinusMinus: 8776 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8777 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8778 break; 8779 8780 case OO_EqualEqual: 8781 case OO_ExclaimEqual: 8782 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8783 LLVM_FALLTHROUGH; 8784 8785 case OO_Less: 8786 case OO_Greater: 8787 case OO_LessEqual: 8788 case OO_GreaterEqual: 8789 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8790 OpBuilder.addGenericBinaryArithmeticOverloads(); 8791 break; 8792 8793 case OO_Spaceship: 8794 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8795 OpBuilder.addThreeWayArithmeticOverloads(); 8796 break; 8797 8798 case OO_Percent: 8799 case OO_Caret: 8800 case OO_Pipe: 8801 case OO_LessLess: 8802 case OO_GreaterGreater: 8803 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8804 break; 8805 8806 case OO_Amp: // '&' is either unary or binary 8807 if (Args.size() == 1) 8808 // C++ [over.match.oper]p3: 8809 // -- For the operator ',', the unary operator '&', or the 8810 // operator '->', the built-in candidates set is empty. 8811 break; 8812 8813 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8814 break; 8815 8816 case OO_Tilde: 8817 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8818 break; 8819 8820 case OO_Equal: 8821 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8822 LLVM_FALLTHROUGH; 8823 8824 case OO_PlusEqual: 8825 case OO_MinusEqual: 8826 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8827 LLVM_FALLTHROUGH; 8828 8829 case OO_StarEqual: 8830 case OO_SlashEqual: 8831 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8832 break; 8833 8834 case OO_PercentEqual: 8835 case OO_LessLessEqual: 8836 case OO_GreaterGreaterEqual: 8837 case OO_AmpEqual: 8838 case OO_CaretEqual: 8839 case OO_PipeEqual: 8840 OpBuilder.addAssignmentIntegralOverloads(); 8841 break; 8842 8843 case OO_Exclaim: 8844 OpBuilder.addExclaimOverload(); 8845 break; 8846 8847 case OO_AmpAmp: 8848 case OO_PipePipe: 8849 OpBuilder.addAmpAmpOrPipePipeOverload(); 8850 break; 8851 8852 case OO_Subscript: 8853 OpBuilder.addSubscriptOverloads(); 8854 break; 8855 8856 case OO_ArrowStar: 8857 OpBuilder.addArrowStarOverloads(); 8858 break; 8859 8860 case OO_Conditional: 8861 OpBuilder.addConditionalOperatorOverloads(); 8862 OpBuilder.addGenericBinaryArithmeticOverloads(); 8863 break; 8864 } 8865 } 8866 8867 /// Add function candidates found via argument-dependent lookup 8868 /// to the set of overloading candidates. 8869 /// 8870 /// This routine performs argument-dependent name lookup based on the 8871 /// given function name (which may also be an operator name) and adds 8872 /// all of the overload candidates found by ADL to the overload 8873 /// candidate set (C++ [basic.lookup.argdep]). 8874 void 8875 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8876 SourceLocation Loc, 8877 ArrayRef<Expr *> Args, 8878 TemplateArgumentListInfo *ExplicitTemplateArgs, 8879 OverloadCandidateSet& CandidateSet, 8880 bool PartialOverloading) { 8881 ADLResult Fns; 8882 8883 // FIXME: This approach for uniquing ADL results (and removing 8884 // redundant candidates from the set) relies on pointer-equality, 8885 // which means we need to key off the canonical decl. However, 8886 // always going back to the canonical decl might not get us the 8887 // right set of default arguments. What default arguments are 8888 // we supposed to consider on ADL candidates, anyway? 8889 8890 // FIXME: Pass in the explicit template arguments? 8891 ArgumentDependentLookup(Name, Loc, Args, Fns); 8892 8893 // Erase all of the candidates we already knew about. 8894 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8895 CandEnd = CandidateSet.end(); 8896 Cand != CandEnd; ++Cand) 8897 if (Cand->Function) { 8898 Fns.erase(Cand->Function); 8899 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8900 Fns.erase(FunTmpl); 8901 } 8902 8903 // For each of the ADL candidates we found, add it to the overload 8904 // set. 8905 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8906 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8907 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8908 if (ExplicitTemplateArgs) 8909 continue; 8910 8911 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8912 PartialOverloading); 8913 } else 8914 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8915 FoundDecl, ExplicitTemplateArgs, 8916 Args, CandidateSet, PartialOverloading); 8917 } 8918 } 8919 8920 namespace { 8921 enum class Comparison { Equal, Better, Worse }; 8922 } 8923 8924 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8925 /// overload resolution. 8926 /// 8927 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8928 /// Cand1's first N enable_if attributes have precisely the same conditions as 8929 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8930 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8931 /// 8932 /// Note that you can have a pair of candidates such that Cand1's enable_if 8933 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8934 /// worse than Cand1's. 8935 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8936 const FunctionDecl *Cand2) { 8937 // Common case: One (or both) decls don't have enable_if attrs. 8938 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8939 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8940 if (!Cand1Attr || !Cand2Attr) { 8941 if (Cand1Attr == Cand2Attr) 8942 return Comparison::Equal; 8943 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8944 } 8945 8946 // FIXME: The next several lines are just 8947 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8948 // instead of reverse order which is how they're stored in the AST. 8949 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8950 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8951 8952 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8953 // has fewer enable_if attributes than Cand2. 8954 if (Cand1Attrs.size() < Cand2Attrs.size()) 8955 return Comparison::Worse; 8956 8957 auto Cand1I = Cand1Attrs.begin(); 8958 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8959 for (auto &Cand2A : Cand2Attrs) { 8960 Cand1ID.clear(); 8961 Cand2ID.clear(); 8962 8963 auto &Cand1A = *Cand1I++; 8964 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8965 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8966 if (Cand1ID != Cand2ID) 8967 return Comparison::Worse; 8968 } 8969 8970 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8971 } 8972 8973 /// isBetterOverloadCandidate - Determines whether the first overload 8974 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8975 bool clang::isBetterOverloadCandidate( 8976 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 8977 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 8978 // Define viable functions to be better candidates than non-viable 8979 // functions. 8980 if (!Cand2.Viable) 8981 return Cand1.Viable; 8982 else if (!Cand1.Viable) 8983 return false; 8984 8985 // C++ [over.match.best]p1: 8986 // 8987 // -- if F is a static member function, ICS1(F) is defined such 8988 // that ICS1(F) is neither better nor worse than ICS1(G) for 8989 // any function G, and, symmetrically, ICS1(G) is neither 8990 // better nor worse than ICS1(F). 8991 unsigned StartArg = 0; 8992 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8993 StartArg = 1; 8994 8995 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8996 // We don't allow incompatible pointer conversions in C++. 8997 if (!S.getLangOpts().CPlusPlus) 8998 return ICS.isStandard() && 8999 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9000 9001 // The only ill-formed conversion we allow in C++ is the string literal to 9002 // char* conversion, which is only considered ill-formed after C++11. 9003 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9004 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9005 }; 9006 9007 // Define functions that don't require ill-formed conversions for a given 9008 // argument to be better candidates than functions that do. 9009 unsigned NumArgs = Cand1.Conversions.size(); 9010 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9011 bool HasBetterConversion = false; 9012 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9013 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9014 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9015 if (Cand1Bad != Cand2Bad) { 9016 if (Cand1Bad) 9017 return false; 9018 HasBetterConversion = true; 9019 } 9020 } 9021 9022 if (HasBetterConversion) 9023 return true; 9024 9025 // C++ [over.match.best]p1: 9026 // A viable function F1 is defined to be a better function than another 9027 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9028 // conversion sequence than ICSi(F2), and then... 9029 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9030 switch (CompareImplicitConversionSequences(S, Loc, 9031 Cand1.Conversions[ArgIdx], 9032 Cand2.Conversions[ArgIdx])) { 9033 case ImplicitConversionSequence::Better: 9034 // Cand1 has a better conversion sequence. 9035 HasBetterConversion = true; 9036 break; 9037 9038 case ImplicitConversionSequence::Worse: 9039 // Cand1 can't be better than Cand2. 9040 return false; 9041 9042 case ImplicitConversionSequence::Indistinguishable: 9043 // Do nothing. 9044 break; 9045 } 9046 } 9047 9048 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9049 // ICSj(F2), or, if not that, 9050 if (HasBetterConversion) 9051 return true; 9052 9053 // -- the context is an initialization by user-defined conversion 9054 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9055 // from the return type of F1 to the destination type (i.e., 9056 // the type of the entity being initialized) is a better 9057 // conversion sequence than the standard conversion sequence 9058 // from the return type of F2 to the destination type. 9059 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9060 Cand1.Function && Cand2.Function && 9061 isa<CXXConversionDecl>(Cand1.Function) && 9062 isa<CXXConversionDecl>(Cand2.Function)) { 9063 // First check whether we prefer one of the conversion functions over the 9064 // other. This only distinguishes the results in non-standard, extension 9065 // cases such as the conversion from a lambda closure type to a function 9066 // pointer or block. 9067 ImplicitConversionSequence::CompareKind Result = 9068 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9069 if (Result == ImplicitConversionSequence::Indistinguishable) 9070 Result = CompareStandardConversionSequences(S, Loc, 9071 Cand1.FinalConversion, 9072 Cand2.FinalConversion); 9073 9074 if (Result != ImplicitConversionSequence::Indistinguishable) 9075 return Result == ImplicitConversionSequence::Better; 9076 9077 // FIXME: Compare kind of reference binding if conversion functions 9078 // convert to a reference type used in direct reference binding, per 9079 // C++14 [over.match.best]p1 section 2 bullet 3. 9080 } 9081 9082 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9083 // as combined with the resolution to CWG issue 243. 9084 // 9085 // When the context is initialization by constructor ([over.match.ctor] or 9086 // either phase of [over.match.list]), a constructor is preferred over 9087 // a conversion function. 9088 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9089 Cand1.Function && Cand2.Function && 9090 isa<CXXConstructorDecl>(Cand1.Function) != 9091 isa<CXXConstructorDecl>(Cand2.Function)) 9092 return isa<CXXConstructorDecl>(Cand1.Function); 9093 9094 // -- F1 is a non-template function and F2 is a function template 9095 // specialization, or, if not that, 9096 bool Cand1IsSpecialization = Cand1.Function && 9097 Cand1.Function->getPrimaryTemplate(); 9098 bool Cand2IsSpecialization = Cand2.Function && 9099 Cand2.Function->getPrimaryTemplate(); 9100 if (Cand1IsSpecialization != Cand2IsSpecialization) 9101 return Cand2IsSpecialization; 9102 9103 // -- F1 and F2 are function template specializations, and the function 9104 // template for F1 is more specialized than the template for F2 9105 // according to the partial ordering rules described in 14.5.5.2, or, 9106 // if not that, 9107 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9108 if (FunctionTemplateDecl *BetterTemplate 9109 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9110 Cand2.Function->getPrimaryTemplate(), 9111 Loc, 9112 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9113 : TPOC_Call, 9114 Cand1.ExplicitCallArguments, 9115 Cand2.ExplicitCallArguments)) 9116 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9117 } 9118 9119 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9120 // A derived-class constructor beats an (inherited) base class constructor. 9121 bool Cand1IsInherited = 9122 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9123 bool Cand2IsInherited = 9124 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9125 if (Cand1IsInherited != Cand2IsInherited) 9126 return Cand2IsInherited; 9127 else if (Cand1IsInherited) { 9128 assert(Cand2IsInherited); 9129 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9130 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9131 if (Cand1Class->isDerivedFrom(Cand2Class)) 9132 return true; 9133 if (Cand2Class->isDerivedFrom(Cand1Class)) 9134 return false; 9135 // Inherited from sibling base classes: still ambiguous. 9136 } 9137 9138 // Check C++17 tie-breakers for deduction guides. 9139 { 9140 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9141 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9142 if (Guide1 && Guide2) { 9143 // -- F1 is generated from a deduction-guide and F2 is not 9144 if (Guide1->isImplicit() != Guide2->isImplicit()) 9145 return Guide2->isImplicit(); 9146 9147 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9148 if (Guide1->isCopyDeductionCandidate()) 9149 return true; 9150 } 9151 } 9152 9153 // Check for enable_if value-based overload resolution. 9154 if (Cand1.Function && Cand2.Function) { 9155 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9156 if (Cmp != Comparison::Equal) 9157 return Cmp == Comparison::Better; 9158 } 9159 9160 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9161 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9162 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9163 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9164 } 9165 9166 bool HasPS1 = Cand1.Function != nullptr && 9167 functionHasPassObjectSizeParams(Cand1.Function); 9168 bool HasPS2 = Cand2.Function != nullptr && 9169 functionHasPassObjectSizeParams(Cand2.Function); 9170 return HasPS1 != HasPS2 && HasPS1; 9171 } 9172 9173 /// Determine whether two declarations are "equivalent" for the purposes of 9174 /// name lookup and overload resolution. This applies when the same internal/no 9175 /// linkage entity is defined by two modules (probably by textually including 9176 /// the same header). In such a case, we don't consider the declarations to 9177 /// declare the same entity, but we also don't want lookups with both 9178 /// declarations visible to be ambiguous in some cases (this happens when using 9179 /// a modularized libstdc++). 9180 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9181 const NamedDecl *B) { 9182 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9183 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9184 if (!VA || !VB) 9185 return false; 9186 9187 // The declarations must be declaring the same name as an internal linkage 9188 // entity in different modules. 9189 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9190 VB->getDeclContext()->getRedeclContext()) || 9191 getOwningModule(const_cast<ValueDecl *>(VA)) == 9192 getOwningModule(const_cast<ValueDecl *>(VB)) || 9193 VA->isExternallyVisible() || VB->isExternallyVisible()) 9194 return false; 9195 9196 // Check that the declarations appear to be equivalent. 9197 // 9198 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9199 // For constants and functions, we should check the initializer or body is 9200 // the same. For non-constant variables, we shouldn't allow it at all. 9201 if (Context.hasSameType(VA->getType(), VB->getType())) 9202 return true; 9203 9204 // Enum constants within unnamed enumerations will have different types, but 9205 // may still be similar enough to be interchangeable for our purposes. 9206 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9207 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9208 // Only handle anonymous enums. If the enumerations were named and 9209 // equivalent, they would have been merged to the same type. 9210 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9211 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9212 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9213 !Context.hasSameType(EnumA->getIntegerType(), 9214 EnumB->getIntegerType())) 9215 return false; 9216 // Allow this only if the value is the same for both enumerators. 9217 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9218 } 9219 } 9220 9221 // Nothing else is sufficiently similar. 9222 return false; 9223 } 9224 9225 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9226 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9227 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9228 9229 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9230 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9231 << !M << (M ? M->getFullModuleName() : ""); 9232 9233 for (auto *E : Equiv) { 9234 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9235 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9236 << !M << (M ? M->getFullModuleName() : ""); 9237 } 9238 } 9239 9240 /// Computes the best viable function (C++ 13.3.3) 9241 /// within an overload candidate set. 9242 /// 9243 /// \param Loc The location of the function name (or operator symbol) for 9244 /// which overload resolution occurs. 9245 /// 9246 /// \param Best If overload resolution was successful or found a deleted 9247 /// function, \p Best points to the candidate function found. 9248 /// 9249 /// \returns The result of overload resolution. 9250 OverloadingResult 9251 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9252 iterator &Best) { 9253 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9254 std::transform(begin(), end(), std::back_inserter(Candidates), 9255 [](OverloadCandidate &Cand) { return &Cand; }); 9256 9257 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9258 // are accepted by both clang and NVCC. However, during a particular 9259 // compilation mode only one call variant is viable. We need to 9260 // exclude non-viable overload candidates from consideration based 9261 // only on their host/device attributes. Specifically, if one 9262 // candidate call is WrongSide and the other is SameSide, we ignore 9263 // the WrongSide candidate. 9264 if (S.getLangOpts().CUDA) { 9265 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9266 bool ContainsSameSideCandidate = 9267 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9268 return Cand->Function && 9269 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9270 Sema::CFP_SameSide; 9271 }); 9272 if (ContainsSameSideCandidate) { 9273 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9274 return Cand->Function && 9275 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9276 Sema::CFP_WrongSide; 9277 }; 9278 llvm::erase_if(Candidates, IsWrongSideCandidate); 9279 } 9280 } 9281 9282 // Find the best viable function. 9283 Best = end(); 9284 for (auto *Cand : Candidates) 9285 if (Cand->Viable) 9286 if (Best == end() || 9287 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9288 Best = Cand; 9289 9290 // If we didn't find any viable functions, abort. 9291 if (Best == end()) 9292 return OR_No_Viable_Function; 9293 9294 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9295 9296 // Make sure that this function is better than every other viable 9297 // function. If not, we have an ambiguity. 9298 for (auto *Cand : Candidates) { 9299 if (Cand->Viable && Cand != Best && 9300 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9301 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9302 Cand->Function)) { 9303 EquivalentCands.push_back(Cand->Function); 9304 continue; 9305 } 9306 9307 Best = end(); 9308 return OR_Ambiguous; 9309 } 9310 } 9311 9312 // Best is the best viable function. 9313 if (Best->Function && 9314 (Best->Function->isDeleted() || 9315 S.isFunctionConsideredUnavailable(Best->Function))) 9316 return OR_Deleted; 9317 9318 if (!EquivalentCands.empty()) 9319 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9320 EquivalentCands); 9321 9322 return OR_Success; 9323 } 9324 9325 namespace { 9326 9327 enum OverloadCandidateKind { 9328 oc_function, 9329 oc_method, 9330 oc_constructor, 9331 oc_implicit_default_constructor, 9332 oc_implicit_copy_constructor, 9333 oc_implicit_move_constructor, 9334 oc_implicit_copy_assignment, 9335 oc_implicit_move_assignment, 9336 oc_inherited_constructor 9337 }; 9338 9339 enum OverloadCandidateSelect { 9340 ocs_non_template, 9341 ocs_template, 9342 ocs_described_template, 9343 }; 9344 9345 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9346 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9347 std::string &Description) { 9348 9349 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9350 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9351 isTemplate = true; 9352 Description = S.getTemplateArgumentBindingsText( 9353 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9354 } 9355 9356 OverloadCandidateSelect Select = [&]() { 9357 if (!Description.empty()) 9358 return ocs_described_template; 9359 return isTemplate ? ocs_template : ocs_non_template; 9360 }(); 9361 9362 OverloadCandidateKind Kind = [&]() { 9363 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9364 if (!Ctor->isImplicit()) { 9365 if (isa<ConstructorUsingShadowDecl>(Found)) 9366 return oc_inherited_constructor; 9367 else 9368 return oc_constructor; 9369 } 9370 9371 if (Ctor->isDefaultConstructor()) 9372 return oc_implicit_default_constructor; 9373 9374 if (Ctor->isMoveConstructor()) 9375 return oc_implicit_move_constructor; 9376 9377 assert(Ctor->isCopyConstructor() && 9378 "unexpected sort of implicit constructor"); 9379 return oc_implicit_copy_constructor; 9380 } 9381 9382 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9383 // This actually gets spelled 'candidate function' for now, but 9384 // it doesn't hurt to split it out. 9385 if (!Meth->isImplicit()) 9386 return oc_method; 9387 9388 if (Meth->isMoveAssignmentOperator()) 9389 return oc_implicit_move_assignment; 9390 9391 if (Meth->isCopyAssignmentOperator()) 9392 return oc_implicit_copy_assignment; 9393 9394 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9395 return oc_method; 9396 } 9397 9398 return oc_function; 9399 }(); 9400 9401 return std::make_pair(Kind, Select); 9402 } 9403 9404 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9405 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9406 // set. 9407 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9408 S.Diag(FoundDecl->getLocation(), 9409 diag::note_ovl_candidate_inherited_constructor) 9410 << Shadow->getNominatedBaseClass(); 9411 } 9412 9413 } // end anonymous namespace 9414 9415 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9416 const FunctionDecl *FD) { 9417 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9418 bool AlwaysTrue; 9419 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9420 return false; 9421 if (!AlwaysTrue) 9422 return false; 9423 } 9424 return true; 9425 } 9426 9427 /// Returns true if we can take the address of the function. 9428 /// 9429 /// \param Complain - If true, we'll emit a diagnostic 9430 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9431 /// we in overload resolution? 9432 /// \param Loc - The location of the statement we're complaining about. Ignored 9433 /// if we're not complaining, or if we're in overload resolution. 9434 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9435 bool Complain, 9436 bool InOverloadResolution, 9437 SourceLocation Loc) { 9438 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9439 if (Complain) { 9440 if (InOverloadResolution) 9441 S.Diag(FD->getLocStart(), 9442 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9443 else 9444 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9445 } 9446 return false; 9447 } 9448 9449 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9450 return P->hasAttr<PassObjectSizeAttr>(); 9451 }); 9452 if (I == FD->param_end()) 9453 return true; 9454 9455 if (Complain) { 9456 // Add one to ParamNo because it's user-facing 9457 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9458 if (InOverloadResolution) 9459 S.Diag(FD->getLocation(), 9460 diag::note_ovl_candidate_has_pass_object_size_params) 9461 << ParamNo; 9462 else 9463 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9464 << FD << ParamNo; 9465 } 9466 return false; 9467 } 9468 9469 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9470 const FunctionDecl *FD) { 9471 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9472 /*InOverloadResolution=*/true, 9473 /*Loc=*/SourceLocation()); 9474 } 9475 9476 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9477 bool Complain, 9478 SourceLocation Loc) { 9479 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9480 /*InOverloadResolution=*/false, 9481 Loc); 9482 } 9483 9484 // Notes the location of an overload candidate. 9485 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9486 QualType DestType, bool TakingAddress) { 9487 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9488 return; 9489 if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9490 return; 9491 9492 std::string FnDesc; 9493 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9494 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9495 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9496 << (unsigned)KSPair.first << (unsigned)KSPair.second 9497 << Fn << FnDesc; 9498 9499 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9500 Diag(Fn->getLocation(), PD); 9501 MaybeEmitInheritedConstructorNote(*this, Found); 9502 } 9503 9504 // Notes the location of all overload candidates designated through 9505 // OverloadedExpr 9506 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9507 bool TakingAddress) { 9508 assert(OverloadedExpr->getType() == Context.OverloadTy); 9509 9510 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9511 OverloadExpr *OvlExpr = Ovl.Expression; 9512 9513 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9514 IEnd = OvlExpr->decls_end(); 9515 I != IEnd; ++I) { 9516 if (FunctionTemplateDecl *FunTmpl = 9517 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9518 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9519 TakingAddress); 9520 } else if (FunctionDecl *Fun 9521 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9522 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9523 } 9524 } 9525 } 9526 9527 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9528 /// "lead" diagnostic; it will be given two arguments, the source and 9529 /// target types of the conversion. 9530 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9531 Sema &S, 9532 SourceLocation CaretLoc, 9533 const PartialDiagnostic &PDiag) const { 9534 S.Diag(CaretLoc, PDiag) 9535 << Ambiguous.getFromType() << Ambiguous.getToType(); 9536 // FIXME: The note limiting machinery is borrowed from 9537 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9538 // refactoring here. 9539 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9540 unsigned CandsShown = 0; 9541 AmbiguousConversionSequence::const_iterator I, E; 9542 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9543 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9544 break; 9545 ++CandsShown; 9546 S.NoteOverloadCandidate(I->first, I->second); 9547 } 9548 if (I != E) 9549 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9550 } 9551 9552 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9553 unsigned I, bool TakingCandidateAddress) { 9554 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9555 assert(Conv.isBad()); 9556 assert(Cand->Function && "for now, candidate must be a function"); 9557 FunctionDecl *Fn = Cand->Function; 9558 9559 // There's a conversion slot for the object argument if this is a 9560 // non-constructor method. Note that 'I' corresponds the 9561 // conversion-slot index. 9562 bool isObjectArgument = false; 9563 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9564 if (I == 0) 9565 isObjectArgument = true; 9566 else 9567 I--; 9568 } 9569 9570 std::string FnDesc; 9571 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9572 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9573 9574 Expr *FromExpr = Conv.Bad.FromExpr; 9575 QualType FromTy = Conv.Bad.getFromType(); 9576 QualType ToTy = Conv.Bad.getToType(); 9577 9578 if (FromTy == S.Context.OverloadTy) { 9579 assert(FromExpr && "overload set argument came from implicit argument?"); 9580 Expr *E = FromExpr->IgnoreParens(); 9581 if (isa<UnaryOperator>(E)) 9582 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9583 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9584 9585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9586 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9587 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9588 << Name << I + 1; 9589 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9590 return; 9591 } 9592 9593 // Do some hand-waving analysis to see if the non-viability is due 9594 // to a qualifier mismatch. 9595 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9596 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9597 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9598 CToTy = RT->getPointeeType(); 9599 else { 9600 // TODO: detect and diagnose the full richness of const mismatches. 9601 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9602 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9603 CFromTy = FromPT->getPointeeType(); 9604 CToTy = ToPT->getPointeeType(); 9605 } 9606 } 9607 9608 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9609 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9610 Qualifiers FromQs = CFromTy.getQualifiers(); 9611 Qualifiers ToQs = CToTy.getQualifiers(); 9612 9613 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9614 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9615 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9616 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9617 << FromQs.getAddressSpaceAttributePrintValue() 9618 << ToQs.getAddressSpaceAttributePrintValue() 9619 << (unsigned)isObjectArgument << I + 1; 9620 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9621 return; 9622 } 9623 9624 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9625 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9626 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9627 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9628 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9629 << (unsigned)isObjectArgument << I + 1; 9630 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9631 return; 9632 } 9633 9634 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9635 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9636 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9637 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9638 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9639 << (unsigned)isObjectArgument << I + 1; 9640 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9641 return; 9642 } 9643 9644 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9645 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9646 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9647 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9648 << FromQs.hasUnaligned() << I + 1; 9649 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9650 return; 9651 } 9652 9653 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9654 assert(CVR && "unexpected qualifiers mismatch"); 9655 9656 if (isObjectArgument) { 9657 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9658 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9660 << (CVR - 1); 9661 } else { 9662 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9663 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9664 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9665 << (CVR - 1) << I + 1; 9666 } 9667 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9668 return; 9669 } 9670 9671 // Special diagnostic for failure to convert an initializer list, since 9672 // telling the user that it has type void is not useful. 9673 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9674 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9675 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9676 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9677 << ToTy << (unsigned)isObjectArgument << I + 1; 9678 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9679 return; 9680 } 9681 9682 // Diagnose references or pointers to incomplete types differently, 9683 // since it's far from impossible that the incompleteness triggered 9684 // the failure. 9685 QualType TempFromTy = FromTy.getNonReferenceType(); 9686 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9687 TempFromTy = PTy->getPointeeType(); 9688 if (TempFromTy->isIncompleteType()) { 9689 // Emit the generic diagnostic and, optionally, add the hints to it. 9690 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9691 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9692 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9693 << ToTy << (unsigned)isObjectArgument << I + 1 9694 << (unsigned)(Cand->Fix.Kind); 9695 9696 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9697 return; 9698 } 9699 9700 // Diagnose base -> derived pointer conversions. 9701 unsigned BaseToDerivedConversion = 0; 9702 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9703 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9704 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9705 FromPtrTy->getPointeeType()) && 9706 !FromPtrTy->getPointeeType()->isIncompleteType() && 9707 !ToPtrTy->getPointeeType()->isIncompleteType() && 9708 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9709 FromPtrTy->getPointeeType())) 9710 BaseToDerivedConversion = 1; 9711 } 9712 } else if (const ObjCObjectPointerType *FromPtrTy 9713 = FromTy->getAs<ObjCObjectPointerType>()) { 9714 if (const ObjCObjectPointerType *ToPtrTy 9715 = ToTy->getAs<ObjCObjectPointerType>()) 9716 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9717 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9718 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9719 FromPtrTy->getPointeeType()) && 9720 FromIface->isSuperClassOf(ToIface)) 9721 BaseToDerivedConversion = 2; 9722 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9723 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9724 !FromTy->isIncompleteType() && 9725 !ToRefTy->getPointeeType()->isIncompleteType() && 9726 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9727 BaseToDerivedConversion = 3; 9728 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9729 ToTy.getNonReferenceType().getCanonicalType() == 9730 FromTy.getNonReferenceType().getCanonicalType()) { 9731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9732 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9733 << (unsigned)isObjectArgument << I + 1 9734 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9735 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9736 return; 9737 } 9738 } 9739 9740 if (BaseToDerivedConversion) { 9741 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9742 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9743 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9744 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9745 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9746 return; 9747 } 9748 9749 if (isa<ObjCObjectPointerType>(CFromTy) && 9750 isa<PointerType>(CToTy)) { 9751 Qualifiers FromQs = CFromTy.getQualifiers(); 9752 Qualifiers ToQs = CToTy.getQualifiers(); 9753 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9755 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9756 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9757 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9758 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9759 return; 9760 } 9761 } 9762 9763 if (TakingCandidateAddress && 9764 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9765 return; 9766 9767 // Emit the generic diagnostic and, optionally, add the hints to it. 9768 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9769 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9770 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9771 << ToTy << (unsigned)isObjectArgument << I + 1 9772 << (unsigned)(Cand->Fix.Kind); 9773 9774 // If we can fix the conversion, suggest the FixIts. 9775 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9776 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9777 FDiag << *HI; 9778 S.Diag(Fn->getLocation(), FDiag); 9779 9780 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9781 } 9782 9783 /// Additional arity mismatch diagnosis specific to a function overload 9784 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9785 /// over a candidate in any candidate set. 9786 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9787 unsigned NumArgs) { 9788 FunctionDecl *Fn = Cand->Function; 9789 unsigned MinParams = Fn->getMinRequiredArguments(); 9790 9791 // With invalid overloaded operators, it's possible that we think we 9792 // have an arity mismatch when in fact it looks like we have the 9793 // right number of arguments, because only overloaded operators have 9794 // the weird behavior of overloading member and non-member functions. 9795 // Just don't report anything. 9796 if (Fn->isInvalidDecl() && 9797 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9798 return true; 9799 9800 if (NumArgs < MinParams) { 9801 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9802 (Cand->FailureKind == ovl_fail_bad_deduction && 9803 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9804 } else { 9805 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9806 (Cand->FailureKind == ovl_fail_bad_deduction && 9807 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9808 } 9809 9810 return false; 9811 } 9812 9813 /// General arity mismatch diagnosis over a candidate in a candidate set. 9814 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9815 unsigned NumFormalArgs) { 9816 assert(isa<FunctionDecl>(D) && 9817 "The templated declaration should at least be a function" 9818 " when diagnosing bad template argument deduction due to too many" 9819 " or too few arguments"); 9820 9821 FunctionDecl *Fn = cast<FunctionDecl>(D); 9822 9823 // TODO: treat calls to a missing default constructor as a special case 9824 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9825 unsigned MinParams = Fn->getMinRequiredArguments(); 9826 9827 // at least / at most / exactly 9828 unsigned mode, modeCount; 9829 if (NumFormalArgs < MinParams) { 9830 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9831 FnTy->isTemplateVariadic()) 9832 mode = 0; // "at least" 9833 else 9834 mode = 2; // "exactly" 9835 modeCount = MinParams; 9836 } else { 9837 if (MinParams != FnTy->getNumParams()) 9838 mode = 1; // "at most" 9839 else 9840 mode = 2; // "exactly" 9841 modeCount = FnTy->getNumParams(); 9842 } 9843 9844 std::string Description; 9845 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9846 ClassifyOverloadCandidate(S, Found, Fn, Description); 9847 9848 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9850 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9851 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9852 else 9853 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9854 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9855 << Description << mode << modeCount << NumFormalArgs; 9856 9857 MaybeEmitInheritedConstructorNote(S, Found); 9858 } 9859 9860 /// Arity mismatch diagnosis specific to a function overload candidate. 9861 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9862 unsigned NumFormalArgs) { 9863 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9864 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9865 } 9866 9867 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9868 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9869 return TD; 9870 llvm_unreachable("Unsupported: Getting the described template declaration" 9871 " for bad deduction diagnosis"); 9872 } 9873 9874 /// Diagnose a failed template-argument deduction. 9875 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9876 DeductionFailureInfo &DeductionFailure, 9877 unsigned NumArgs, 9878 bool TakingCandidateAddress) { 9879 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9880 NamedDecl *ParamD; 9881 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9882 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9883 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9884 switch (DeductionFailure.Result) { 9885 case Sema::TDK_Success: 9886 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9887 9888 case Sema::TDK_Incomplete: { 9889 assert(ParamD && "no parameter found for incomplete deduction result"); 9890 S.Diag(Templated->getLocation(), 9891 diag::note_ovl_candidate_incomplete_deduction) 9892 << ParamD->getDeclName(); 9893 MaybeEmitInheritedConstructorNote(S, Found); 9894 return; 9895 } 9896 9897 case Sema::TDK_Underqualified: { 9898 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9899 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9900 9901 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9902 9903 // Param will have been canonicalized, but it should just be a 9904 // qualified version of ParamD, so move the qualifiers to that. 9905 QualifierCollector Qs; 9906 Qs.strip(Param); 9907 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9908 assert(S.Context.hasSameType(Param, NonCanonParam)); 9909 9910 // Arg has also been canonicalized, but there's nothing we can do 9911 // about that. It also doesn't matter as much, because it won't 9912 // have any template parameters in it (because deduction isn't 9913 // done on dependent types). 9914 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9915 9916 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9917 << ParamD->getDeclName() << Arg << NonCanonParam; 9918 MaybeEmitInheritedConstructorNote(S, Found); 9919 return; 9920 } 9921 9922 case Sema::TDK_Inconsistent: { 9923 assert(ParamD && "no parameter found for inconsistent deduction result"); 9924 int which = 0; 9925 if (isa<TemplateTypeParmDecl>(ParamD)) 9926 which = 0; 9927 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9928 // Deduction might have failed because we deduced arguments of two 9929 // different types for a non-type template parameter. 9930 // FIXME: Use a different TDK value for this. 9931 QualType T1 = 9932 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9933 QualType T2 = 9934 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9935 if (!S.Context.hasSameType(T1, T2)) { 9936 S.Diag(Templated->getLocation(), 9937 diag::note_ovl_candidate_inconsistent_deduction_types) 9938 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9939 << *DeductionFailure.getSecondArg() << T2; 9940 MaybeEmitInheritedConstructorNote(S, Found); 9941 return; 9942 } 9943 9944 which = 1; 9945 } else { 9946 which = 2; 9947 } 9948 9949 S.Diag(Templated->getLocation(), 9950 diag::note_ovl_candidate_inconsistent_deduction) 9951 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9952 << *DeductionFailure.getSecondArg(); 9953 MaybeEmitInheritedConstructorNote(S, Found); 9954 return; 9955 } 9956 9957 case Sema::TDK_InvalidExplicitArguments: 9958 assert(ParamD && "no parameter found for invalid explicit arguments"); 9959 if (ParamD->getDeclName()) 9960 S.Diag(Templated->getLocation(), 9961 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9962 << ParamD->getDeclName(); 9963 else { 9964 int index = 0; 9965 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9966 index = TTP->getIndex(); 9967 else if (NonTypeTemplateParmDecl *NTTP 9968 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9969 index = NTTP->getIndex(); 9970 else 9971 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9972 S.Diag(Templated->getLocation(), 9973 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9974 << (index + 1); 9975 } 9976 MaybeEmitInheritedConstructorNote(S, Found); 9977 return; 9978 9979 case Sema::TDK_TooManyArguments: 9980 case Sema::TDK_TooFewArguments: 9981 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9982 return; 9983 9984 case Sema::TDK_InstantiationDepth: 9985 S.Diag(Templated->getLocation(), 9986 diag::note_ovl_candidate_instantiation_depth); 9987 MaybeEmitInheritedConstructorNote(S, Found); 9988 return; 9989 9990 case Sema::TDK_SubstitutionFailure: { 9991 // Format the template argument list into the argument string. 9992 SmallString<128> TemplateArgString; 9993 if (TemplateArgumentList *Args = 9994 DeductionFailure.getTemplateArgumentList()) { 9995 TemplateArgString = " "; 9996 TemplateArgString += S.getTemplateArgumentBindingsText( 9997 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9998 } 9999 10000 // If this candidate was disabled by enable_if, say so. 10001 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10002 if (PDiag && PDiag->second.getDiagID() == 10003 diag::err_typename_nested_not_found_enable_if) { 10004 // FIXME: Use the source range of the condition, and the fully-qualified 10005 // name of the enable_if template. These are both present in PDiag. 10006 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10007 << "'enable_if'" << TemplateArgString; 10008 return; 10009 } 10010 10011 // We found a specific requirement that disabled the enable_if. 10012 if (PDiag && PDiag->second.getDiagID() == 10013 diag::err_typename_nested_not_found_requirement) { 10014 S.Diag(Templated->getLocation(), 10015 diag::note_ovl_candidate_disabled_by_requirement) 10016 << PDiag->second.getStringArg(0) << TemplateArgString; 10017 return; 10018 } 10019 10020 // Format the SFINAE diagnostic into the argument string. 10021 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10022 // formatted message in another diagnostic. 10023 SmallString<128> SFINAEArgString; 10024 SourceRange R; 10025 if (PDiag) { 10026 SFINAEArgString = ": "; 10027 R = SourceRange(PDiag->first, PDiag->first); 10028 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10029 } 10030 10031 S.Diag(Templated->getLocation(), 10032 diag::note_ovl_candidate_substitution_failure) 10033 << TemplateArgString << SFINAEArgString << R; 10034 MaybeEmitInheritedConstructorNote(S, Found); 10035 return; 10036 } 10037 10038 case Sema::TDK_DeducedMismatch: 10039 case Sema::TDK_DeducedMismatchNested: { 10040 // Format the template argument list into the argument string. 10041 SmallString<128> TemplateArgString; 10042 if (TemplateArgumentList *Args = 10043 DeductionFailure.getTemplateArgumentList()) { 10044 TemplateArgString = " "; 10045 TemplateArgString += S.getTemplateArgumentBindingsText( 10046 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10047 } 10048 10049 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10050 << (*DeductionFailure.getCallArgIndex() + 1) 10051 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10052 << TemplateArgString 10053 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10054 break; 10055 } 10056 10057 case Sema::TDK_NonDeducedMismatch: { 10058 // FIXME: Provide a source location to indicate what we couldn't match. 10059 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10060 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10061 if (FirstTA.getKind() == TemplateArgument::Template && 10062 SecondTA.getKind() == TemplateArgument::Template) { 10063 TemplateName FirstTN = FirstTA.getAsTemplate(); 10064 TemplateName SecondTN = SecondTA.getAsTemplate(); 10065 if (FirstTN.getKind() == TemplateName::Template && 10066 SecondTN.getKind() == TemplateName::Template) { 10067 if (FirstTN.getAsTemplateDecl()->getName() == 10068 SecondTN.getAsTemplateDecl()->getName()) { 10069 // FIXME: This fixes a bad diagnostic where both templates are named 10070 // the same. This particular case is a bit difficult since: 10071 // 1) It is passed as a string to the diagnostic printer. 10072 // 2) The diagnostic printer only attempts to find a better 10073 // name for types, not decls. 10074 // Ideally, this should folded into the diagnostic printer. 10075 S.Diag(Templated->getLocation(), 10076 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10077 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10078 return; 10079 } 10080 } 10081 } 10082 10083 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10084 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10085 return; 10086 10087 // FIXME: For generic lambda parameters, check if the function is a lambda 10088 // call operator, and if so, emit a prettier and more informative 10089 // diagnostic that mentions 'auto' and lambda in addition to 10090 // (or instead of?) the canonical template type parameters. 10091 S.Diag(Templated->getLocation(), 10092 diag::note_ovl_candidate_non_deduced_mismatch) 10093 << FirstTA << SecondTA; 10094 return; 10095 } 10096 // TODO: diagnose these individually, then kill off 10097 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10098 case Sema::TDK_MiscellaneousDeductionFailure: 10099 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10100 MaybeEmitInheritedConstructorNote(S, Found); 10101 return; 10102 case Sema::TDK_CUDATargetMismatch: 10103 S.Diag(Templated->getLocation(), 10104 diag::note_cuda_ovl_candidate_target_mismatch); 10105 return; 10106 } 10107 } 10108 10109 /// Diagnose a failed template-argument deduction, for function calls. 10110 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10111 unsigned NumArgs, 10112 bool TakingCandidateAddress) { 10113 unsigned TDK = Cand->DeductionFailure.Result; 10114 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10115 if (CheckArityMismatch(S, Cand, NumArgs)) 10116 return; 10117 } 10118 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10119 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10120 } 10121 10122 /// CUDA: diagnose an invalid call across targets. 10123 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10124 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10125 FunctionDecl *Callee = Cand->Function; 10126 10127 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10128 CalleeTarget = S.IdentifyCUDATarget(Callee); 10129 10130 std::string FnDesc; 10131 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10132 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10133 10134 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10135 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10136 << FnDesc /* Ignored */ 10137 << CalleeTarget << CallerTarget; 10138 10139 // This could be an implicit constructor for which we could not infer the 10140 // target due to a collsion. Diagnose that case. 10141 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10142 if (Meth != nullptr && Meth->isImplicit()) { 10143 CXXRecordDecl *ParentClass = Meth->getParent(); 10144 Sema::CXXSpecialMember CSM; 10145 10146 switch (FnKindPair.first) { 10147 default: 10148 return; 10149 case oc_implicit_default_constructor: 10150 CSM = Sema::CXXDefaultConstructor; 10151 break; 10152 case oc_implicit_copy_constructor: 10153 CSM = Sema::CXXCopyConstructor; 10154 break; 10155 case oc_implicit_move_constructor: 10156 CSM = Sema::CXXMoveConstructor; 10157 break; 10158 case oc_implicit_copy_assignment: 10159 CSM = Sema::CXXCopyAssignment; 10160 break; 10161 case oc_implicit_move_assignment: 10162 CSM = Sema::CXXMoveAssignment; 10163 break; 10164 }; 10165 10166 bool ConstRHS = false; 10167 if (Meth->getNumParams()) { 10168 if (const ReferenceType *RT = 10169 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10170 ConstRHS = RT->getPointeeType().isConstQualified(); 10171 } 10172 } 10173 10174 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10175 /* ConstRHS */ ConstRHS, 10176 /* Diagnose */ true); 10177 } 10178 } 10179 10180 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10181 FunctionDecl *Callee = Cand->Function; 10182 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10183 10184 S.Diag(Callee->getLocation(), 10185 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10186 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10187 } 10188 10189 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10190 FunctionDecl *Callee = Cand->Function; 10191 10192 S.Diag(Callee->getLocation(), 10193 diag::note_ovl_candidate_disabled_by_extension); 10194 } 10195 10196 /// Generates a 'note' diagnostic for an overload candidate. We've 10197 /// already generated a primary error at the call site. 10198 /// 10199 /// It really does need to be a single diagnostic with its caret 10200 /// pointed at the candidate declaration. Yes, this creates some 10201 /// major challenges of technical writing. Yes, this makes pointing 10202 /// out problems with specific arguments quite awkward. It's still 10203 /// better than generating twenty screens of text for every failed 10204 /// overload. 10205 /// 10206 /// It would be great to be able to express per-candidate problems 10207 /// more richly for those diagnostic clients that cared, but we'd 10208 /// still have to be just as careful with the default diagnostics. 10209 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10210 unsigned NumArgs, 10211 bool TakingCandidateAddress) { 10212 FunctionDecl *Fn = Cand->Function; 10213 10214 // Note deleted candidates, but only if they're viable. 10215 if (Cand->Viable) { 10216 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10217 std::string FnDesc; 10218 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10219 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10220 10221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10222 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10223 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10224 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10225 return; 10226 } 10227 10228 // We don't really have anything else to say about viable candidates. 10229 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10230 return; 10231 } 10232 10233 switch (Cand->FailureKind) { 10234 case ovl_fail_too_many_arguments: 10235 case ovl_fail_too_few_arguments: 10236 return DiagnoseArityMismatch(S, Cand, NumArgs); 10237 10238 case ovl_fail_bad_deduction: 10239 return DiagnoseBadDeduction(S, Cand, NumArgs, 10240 TakingCandidateAddress); 10241 10242 case ovl_fail_illegal_constructor: { 10243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10244 << (Fn->getPrimaryTemplate() ? 1 : 0); 10245 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10246 return; 10247 } 10248 10249 case ovl_fail_trivial_conversion: 10250 case ovl_fail_bad_final_conversion: 10251 case ovl_fail_final_conversion_not_exact: 10252 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10253 10254 case ovl_fail_bad_conversion: { 10255 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10256 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10257 if (Cand->Conversions[I].isBad()) 10258 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10259 10260 // FIXME: this currently happens when we're called from SemaInit 10261 // when user-conversion overload fails. Figure out how to handle 10262 // those conditions and diagnose them well. 10263 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10264 } 10265 10266 case ovl_fail_bad_target: 10267 return DiagnoseBadTarget(S, Cand); 10268 10269 case ovl_fail_enable_if: 10270 return DiagnoseFailedEnableIfAttr(S, Cand); 10271 10272 case ovl_fail_ext_disabled: 10273 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10274 10275 case ovl_fail_inhctor_slice: 10276 // It's generally not interesting to note copy/move constructors here. 10277 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10278 return; 10279 S.Diag(Fn->getLocation(), 10280 diag::note_ovl_candidate_inherited_constructor_slice) 10281 << (Fn->getPrimaryTemplate() ? 1 : 0) 10282 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10283 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10284 return; 10285 10286 case ovl_fail_addr_not_available: { 10287 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10288 (void)Available; 10289 assert(!Available); 10290 break; 10291 } 10292 case ovl_non_default_multiversion_function: 10293 // Do nothing, these should simply be ignored. 10294 break; 10295 } 10296 } 10297 10298 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10299 // Desugar the type of the surrogate down to a function type, 10300 // retaining as many typedefs as possible while still showing 10301 // the function type (and, therefore, its parameter types). 10302 QualType FnType = Cand->Surrogate->getConversionType(); 10303 bool isLValueReference = false; 10304 bool isRValueReference = false; 10305 bool isPointer = false; 10306 if (const LValueReferenceType *FnTypeRef = 10307 FnType->getAs<LValueReferenceType>()) { 10308 FnType = FnTypeRef->getPointeeType(); 10309 isLValueReference = true; 10310 } else if (const RValueReferenceType *FnTypeRef = 10311 FnType->getAs<RValueReferenceType>()) { 10312 FnType = FnTypeRef->getPointeeType(); 10313 isRValueReference = true; 10314 } 10315 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10316 FnType = FnTypePtr->getPointeeType(); 10317 isPointer = true; 10318 } 10319 // Desugar down to a function type. 10320 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10321 // Reconstruct the pointer/reference as appropriate. 10322 if (isPointer) FnType = S.Context.getPointerType(FnType); 10323 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10324 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10325 10326 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10327 << FnType; 10328 } 10329 10330 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10331 SourceLocation OpLoc, 10332 OverloadCandidate *Cand) { 10333 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10334 std::string TypeStr("operator"); 10335 TypeStr += Opc; 10336 TypeStr += "("; 10337 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10338 if (Cand->Conversions.size() == 1) { 10339 TypeStr += ")"; 10340 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10341 } else { 10342 TypeStr += ", "; 10343 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10344 TypeStr += ")"; 10345 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10346 } 10347 } 10348 10349 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10350 OverloadCandidate *Cand) { 10351 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10352 if (ICS.isBad()) break; // all meaningless after first invalid 10353 if (!ICS.isAmbiguous()) continue; 10354 10355 ICS.DiagnoseAmbiguousConversion( 10356 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10357 } 10358 } 10359 10360 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10361 if (Cand->Function) 10362 return Cand->Function->getLocation(); 10363 if (Cand->IsSurrogate) 10364 return Cand->Surrogate->getLocation(); 10365 return SourceLocation(); 10366 } 10367 10368 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10369 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10370 case Sema::TDK_Success: 10371 case Sema::TDK_NonDependentConversionFailure: 10372 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10373 10374 case Sema::TDK_Invalid: 10375 case Sema::TDK_Incomplete: 10376 return 1; 10377 10378 case Sema::TDK_Underqualified: 10379 case Sema::TDK_Inconsistent: 10380 return 2; 10381 10382 case Sema::TDK_SubstitutionFailure: 10383 case Sema::TDK_DeducedMismatch: 10384 case Sema::TDK_DeducedMismatchNested: 10385 case Sema::TDK_NonDeducedMismatch: 10386 case Sema::TDK_MiscellaneousDeductionFailure: 10387 case Sema::TDK_CUDATargetMismatch: 10388 return 3; 10389 10390 case Sema::TDK_InstantiationDepth: 10391 return 4; 10392 10393 case Sema::TDK_InvalidExplicitArguments: 10394 return 5; 10395 10396 case Sema::TDK_TooManyArguments: 10397 case Sema::TDK_TooFewArguments: 10398 return 6; 10399 } 10400 llvm_unreachable("Unhandled deduction result"); 10401 } 10402 10403 namespace { 10404 struct CompareOverloadCandidatesForDisplay { 10405 Sema &S; 10406 SourceLocation Loc; 10407 size_t NumArgs; 10408 OverloadCandidateSet::CandidateSetKind CSK; 10409 10410 CompareOverloadCandidatesForDisplay( 10411 Sema &S, SourceLocation Loc, size_t NArgs, 10412 OverloadCandidateSet::CandidateSetKind CSK) 10413 : S(S), NumArgs(NArgs), CSK(CSK) {} 10414 10415 bool operator()(const OverloadCandidate *L, 10416 const OverloadCandidate *R) { 10417 // Fast-path this check. 10418 if (L == R) return false; 10419 10420 // Order first by viability. 10421 if (L->Viable) { 10422 if (!R->Viable) return true; 10423 10424 // TODO: introduce a tri-valued comparison for overload 10425 // candidates. Would be more worthwhile if we had a sort 10426 // that could exploit it. 10427 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10428 return true; 10429 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10430 return false; 10431 } else if (R->Viable) 10432 return false; 10433 10434 assert(L->Viable == R->Viable); 10435 10436 // Criteria by which we can sort non-viable candidates: 10437 if (!L->Viable) { 10438 // 1. Arity mismatches come after other candidates. 10439 if (L->FailureKind == ovl_fail_too_many_arguments || 10440 L->FailureKind == ovl_fail_too_few_arguments) { 10441 if (R->FailureKind == ovl_fail_too_many_arguments || 10442 R->FailureKind == ovl_fail_too_few_arguments) { 10443 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10444 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10445 if (LDist == RDist) { 10446 if (L->FailureKind == R->FailureKind) 10447 // Sort non-surrogates before surrogates. 10448 return !L->IsSurrogate && R->IsSurrogate; 10449 // Sort candidates requiring fewer parameters than there were 10450 // arguments given after candidates requiring more parameters 10451 // than there were arguments given. 10452 return L->FailureKind == ovl_fail_too_many_arguments; 10453 } 10454 return LDist < RDist; 10455 } 10456 return false; 10457 } 10458 if (R->FailureKind == ovl_fail_too_many_arguments || 10459 R->FailureKind == ovl_fail_too_few_arguments) 10460 return true; 10461 10462 // 2. Bad conversions come first and are ordered by the number 10463 // of bad conversions and quality of good conversions. 10464 if (L->FailureKind == ovl_fail_bad_conversion) { 10465 if (R->FailureKind != ovl_fail_bad_conversion) 10466 return true; 10467 10468 // The conversion that can be fixed with a smaller number of changes, 10469 // comes first. 10470 unsigned numLFixes = L->Fix.NumConversionsFixed; 10471 unsigned numRFixes = R->Fix.NumConversionsFixed; 10472 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10473 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10474 if (numLFixes != numRFixes) { 10475 return numLFixes < numRFixes; 10476 } 10477 10478 // If there's any ordering between the defined conversions... 10479 // FIXME: this might not be transitive. 10480 assert(L->Conversions.size() == R->Conversions.size()); 10481 10482 int leftBetter = 0; 10483 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10484 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10485 switch (CompareImplicitConversionSequences(S, Loc, 10486 L->Conversions[I], 10487 R->Conversions[I])) { 10488 case ImplicitConversionSequence::Better: 10489 leftBetter++; 10490 break; 10491 10492 case ImplicitConversionSequence::Worse: 10493 leftBetter--; 10494 break; 10495 10496 case ImplicitConversionSequence::Indistinguishable: 10497 break; 10498 } 10499 } 10500 if (leftBetter > 0) return true; 10501 if (leftBetter < 0) return false; 10502 10503 } else if (R->FailureKind == ovl_fail_bad_conversion) 10504 return false; 10505 10506 if (L->FailureKind == ovl_fail_bad_deduction) { 10507 if (R->FailureKind != ovl_fail_bad_deduction) 10508 return true; 10509 10510 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10511 return RankDeductionFailure(L->DeductionFailure) 10512 < RankDeductionFailure(R->DeductionFailure); 10513 } else if (R->FailureKind == ovl_fail_bad_deduction) 10514 return false; 10515 10516 // TODO: others? 10517 } 10518 10519 // Sort everything else by location. 10520 SourceLocation LLoc = GetLocationForCandidate(L); 10521 SourceLocation RLoc = GetLocationForCandidate(R); 10522 10523 // Put candidates without locations (e.g. builtins) at the end. 10524 if (LLoc.isInvalid()) return false; 10525 if (RLoc.isInvalid()) return true; 10526 10527 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10528 } 10529 }; 10530 } 10531 10532 /// CompleteNonViableCandidate - Normally, overload resolution only 10533 /// computes up to the first bad conversion. Produces the FixIt set if 10534 /// possible. 10535 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10536 ArrayRef<Expr *> Args) { 10537 assert(!Cand->Viable); 10538 10539 // Don't do anything on failures other than bad conversion. 10540 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10541 10542 // We only want the FixIts if all the arguments can be corrected. 10543 bool Unfixable = false; 10544 // Use a implicit copy initialization to check conversion fixes. 10545 Cand->Fix.setConversionChecker(TryCopyInitialization); 10546 10547 // Attempt to fix the bad conversion. 10548 unsigned ConvCount = Cand->Conversions.size(); 10549 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10550 ++ConvIdx) { 10551 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10552 if (Cand->Conversions[ConvIdx].isInitialized() && 10553 Cand->Conversions[ConvIdx].isBad()) { 10554 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10555 break; 10556 } 10557 } 10558 10559 // FIXME: this should probably be preserved from the overload 10560 // operation somehow. 10561 bool SuppressUserConversions = false; 10562 10563 unsigned ConvIdx = 0; 10564 ArrayRef<QualType> ParamTypes; 10565 10566 if (Cand->IsSurrogate) { 10567 QualType ConvType 10568 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10569 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10570 ConvType = ConvPtrType->getPointeeType(); 10571 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10572 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10573 ConvIdx = 1; 10574 } else if (Cand->Function) { 10575 ParamTypes = 10576 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10577 if (isa<CXXMethodDecl>(Cand->Function) && 10578 !isa<CXXConstructorDecl>(Cand->Function)) { 10579 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10580 ConvIdx = 1; 10581 } 10582 } else { 10583 // Builtin operator. 10584 assert(ConvCount <= 3); 10585 ParamTypes = Cand->BuiltinParamTypes; 10586 } 10587 10588 // Fill in the rest of the conversions. 10589 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10590 if (Cand->Conversions[ConvIdx].isInitialized()) { 10591 // We've already checked this conversion. 10592 } else if (ArgIdx < ParamTypes.size()) { 10593 if (ParamTypes[ArgIdx]->isDependentType()) 10594 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10595 Args[ArgIdx]->getType()); 10596 else { 10597 Cand->Conversions[ConvIdx] = 10598 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10599 SuppressUserConversions, 10600 /*InOverloadResolution=*/true, 10601 /*AllowObjCWritebackConversion=*/ 10602 S.getLangOpts().ObjCAutoRefCount); 10603 // Store the FixIt in the candidate if it exists. 10604 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10605 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10606 } 10607 } else 10608 Cand->Conversions[ConvIdx].setEllipsis(); 10609 } 10610 } 10611 10612 /// When overload resolution fails, prints diagnostic messages containing the 10613 /// candidates in the candidate set. 10614 void OverloadCandidateSet::NoteCandidates( 10615 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10616 StringRef Opc, SourceLocation OpLoc, 10617 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10618 // Sort the candidates by viability and position. Sorting directly would 10619 // be prohibitive, so we make a set of pointers and sort those. 10620 SmallVector<OverloadCandidate*, 32> Cands; 10621 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10622 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10623 if (!Filter(*Cand)) 10624 continue; 10625 if (Cand->Viable) 10626 Cands.push_back(Cand); 10627 else if (OCD == OCD_AllCandidates) { 10628 CompleteNonViableCandidate(S, Cand, Args); 10629 if (Cand->Function || Cand->IsSurrogate) 10630 Cands.push_back(Cand); 10631 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10632 // want to list every possible builtin candidate. 10633 } 10634 } 10635 10636 std::stable_sort(Cands.begin(), Cands.end(), 10637 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10638 10639 bool ReportedAmbiguousConversions = false; 10640 10641 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10642 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10643 unsigned CandsShown = 0; 10644 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10645 OverloadCandidate *Cand = *I; 10646 10647 // Set an arbitrary limit on the number of candidate functions we'll spam 10648 // the user with. FIXME: This limit should depend on details of the 10649 // candidate list. 10650 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10651 break; 10652 } 10653 ++CandsShown; 10654 10655 if (Cand->Function) 10656 NoteFunctionCandidate(S, Cand, Args.size(), 10657 /*TakingCandidateAddress=*/false); 10658 else if (Cand->IsSurrogate) 10659 NoteSurrogateCandidate(S, Cand); 10660 else { 10661 assert(Cand->Viable && 10662 "Non-viable built-in candidates are not added to Cands."); 10663 // Generally we only see ambiguities including viable builtin 10664 // operators if overload resolution got screwed up by an 10665 // ambiguous user-defined conversion. 10666 // 10667 // FIXME: It's quite possible for different conversions to see 10668 // different ambiguities, though. 10669 if (!ReportedAmbiguousConversions) { 10670 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10671 ReportedAmbiguousConversions = true; 10672 } 10673 10674 // If this is a viable builtin, print it. 10675 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10676 } 10677 } 10678 10679 if (I != E) 10680 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10681 } 10682 10683 static SourceLocation 10684 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10685 return Cand->Specialization ? Cand->Specialization->getLocation() 10686 : SourceLocation(); 10687 } 10688 10689 namespace { 10690 struct CompareTemplateSpecCandidatesForDisplay { 10691 Sema &S; 10692 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10693 10694 bool operator()(const TemplateSpecCandidate *L, 10695 const TemplateSpecCandidate *R) { 10696 // Fast-path this check. 10697 if (L == R) 10698 return false; 10699 10700 // Assuming that both candidates are not matches... 10701 10702 // Sort by the ranking of deduction failures. 10703 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10704 return RankDeductionFailure(L->DeductionFailure) < 10705 RankDeductionFailure(R->DeductionFailure); 10706 10707 // Sort everything else by location. 10708 SourceLocation LLoc = GetLocationForCandidate(L); 10709 SourceLocation RLoc = GetLocationForCandidate(R); 10710 10711 // Put candidates without locations (e.g. builtins) at the end. 10712 if (LLoc.isInvalid()) 10713 return false; 10714 if (RLoc.isInvalid()) 10715 return true; 10716 10717 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10718 } 10719 }; 10720 } 10721 10722 /// Diagnose a template argument deduction failure. 10723 /// We are treating these failures as overload failures due to bad 10724 /// deductions. 10725 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10726 bool ForTakingAddress) { 10727 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10728 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10729 } 10730 10731 void TemplateSpecCandidateSet::destroyCandidates() { 10732 for (iterator i = begin(), e = end(); i != e; ++i) { 10733 i->DeductionFailure.Destroy(); 10734 } 10735 } 10736 10737 void TemplateSpecCandidateSet::clear() { 10738 destroyCandidates(); 10739 Candidates.clear(); 10740 } 10741 10742 /// NoteCandidates - When no template specialization match is found, prints 10743 /// diagnostic messages containing the non-matching specializations that form 10744 /// the candidate set. 10745 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10746 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10747 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10748 // Sort the candidates by position (assuming no candidate is a match). 10749 // Sorting directly would be prohibitive, so we make a set of pointers 10750 // and sort those. 10751 SmallVector<TemplateSpecCandidate *, 32> Cands; 10752 Cands.reserve(size()); 10753 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10754 if (Cand->Specialization) 10755 Cands.push_back(Cand); 10756 // Otherwise, this is a non-matching builtin candidate. We do not, 10757 // in general, want to list every possible builtin candidate. 10758 } 10759 10760 llvm::sort(Cands.begin(), Cands.end(), 10761 CompareTemplateSpecCandidatesForDisplay(S)); 10762 10763 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10764 // for generalization purposes (?). 10765 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10766 10767 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10768 unsigned CandsShown = 0; 10769 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10770 TemplateSpecCandidate *Cand = *I; 10771 10772 // Set an arbitrary limit on the number of candidates we'll spam 10773 // the user with. FIXME: This limit should depend on details of the 10774 // candidate list. 10775 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10776 break; 10777 ++CandsShown; 10778 10779 assert(Cand->Specialization && 10780 "Non-matching built-in candidates are not added to Cands."); 10781 Cand->NoteDeductionFailure(S, ForTakingAddress); 10782 } 10783 10784 if (I != E) 10785 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10786 } 10787 10788 // [PossiblyAFunctionType] --> [Return] 10789 // NonFunctionType --> NonFunctionType 10790 // R (A) --> R(A) 10791 // R (*)(A) --> R (A) 10792 // R (&)(A) --> R (A) 10793 // R (S::*)(A) --> R (A) 10794 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10795 QualType Ret = PossiblyAFunctionType; 10796 if (const PointerType *ToTypePtr = 10797 PossiblyAFunctionType->getAs<PointerType>()) 10798 Ret = ToTypePtr->getPointeeType(); 10799 else if (const ReferenceType *ToTypeRef = 10800 PossiblyAFunctionType->getAs<ReferenceType>()) 10801 Ret = ToTypeRef->getPointeeType(); 10802 else if (const MemberPointerType *MemTypePtr = 10803 PossiblyAFunctionType->getAs<MemberPointerType>()) 10804 Ret = MemTypePtr->getPointeeType(); 10805 Ret = 10806 Context.getCanonicalType(Ret).getUnqualifiedType(); 10807 return Ret; 10808 } 10809 10810 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10811 bool Complain = true) { 10812 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10813 S.DeduceReturnType(FD, Loc, Complain)) 10814 return true; 10815 10816 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10817 if (S.getLangOpts().CPlusPlus17 && 10818 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10819 !S.ResolveExceptionSpec(Loc, FPT)) 10820 return true; 10821 10822 return false; 10823 } 10824 10825 namespace { 10826 // A helper class to help with address of function resolution 10827 // - allows us to avoid passing around all those ugly parameters 10828 class AddressOfFunctionResolver { 10829 Sema& S; 10830 Expr* SourceExpr; 10831 const QualType& TargetType; 10832 QualType TargetFunctionType; // Extracted function type from target type 10833 10834 bool Complain; 10835 //DeclAccessPair& ResultFunctionAccessPair; 10836 ASTContext& Context; 10837 10838 bool TargetTypeIsNonStaticMemberFunction; 10839 bool FoundNonTemplateFunction; 10840 bool StaticMemberFunctionFromBoundPointer; 10841 bool HasComplained; 10842 10843 OverloadExpr::FindResult OvlExprInfo; 10844 OverloadExpr *OvlExpr; 10845 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10846 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10847 TemplateSpecCandidateSet FailedCandidates; 10848 10849 public: 10850 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10851 const QualType &TargetType, bool Complain) 10852 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10853 Complain(Complain), Context(S.getASTContext()), 10854 TargetTypeIsNonStaticMemberFunction( 10855 !!TargetType->getAs<MemberPointerType>()), 10856 FoundNonTemplateFunction(false), 10857 StaticMemberFunctionFromBoundPointer(false), 10858 HasComplained(false), 10859 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10860 OvlExpr(OvlExprInfo.Expression), 10861 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10862 ExtractUnqualifiedFunctionTypeFromTargetType(); 10863 10864 if (TargetFunctionType->isFunctionType()) { 10865 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10866 if (!UME->isImplicitAccess() && 10867 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10868 StaticMemberFunctionFromBoundPointer = true; 10869 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10870 DeclAccessPair dap; 10871 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10872 OvlExpr, false, &dap)) { 10873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10874 if (!Method->isStatic()) { 10875 // If the target type is a non-function type and the function found 10876 // is a non-static member function, pretend as if that was the 10877 // target, it's the only possible type to end up with. 10878 TargetTypeIsNonStaticMemberFunction = true; 10879 10880 // And skip adding the function if its not in the proper form. 10881 // We'll diagnose this due to an empty set of functions. 10882 if (!OvlExprInfo.HasFormOfMemberPointer) 10883 return; 10884 } 10885 10886 Matches.push_back(std::make_pair(dap, Fn)); 10887 } 10888 return; 10889 } 10890 10891 if (OvlExpr->hasExplicitTemplateArgs()) 10892 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10893 10894 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10895 // C++ [over.over]p4: 10896 // If more than one function is selected, [...] 10897 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10898 if (FoundNonTemplateFunction) 10899 EliminateAllTemplateMatches(); 10900 else 10901 EliminateAllExceptMostSpecializedTemplate(); 10902 } 10903 } 10904 10905 if (S.getLangOpts().CUDA && Matches.size() > 1) 10906 EliminateSuboptimalCudaMatches(); 10907 } 10908 10909 bool hasComplained() const { return HasComplained; } 10910 10911 private: 10912 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10913 QualType Discard; 10914 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10915 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10916 } 10917 10918 /// \return true if A is considered a better overload candidate for the 10919 /// desired type than B. 10920 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10921 // If A doesn't have exactly the correct type, we don't want to classify it 10922 // as "better" than anything else. This way, the user is required to 10923 // disambiguate for us if there are multiple candidates and no exact match. 10924 return candidateHasExactlyCorrectType(A) && 10925 (!candidateHasExactlyCorrectType(B) || 10926 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10927 } 10928 10929 /// \return true if we were able to eliminate all but one overload candidate, 10930 /// false otherwise. 10931 bool eliminiateSuboptimalOverloadCandidates() { 10932 // Same algorithm as overload resolution -- one pass to pick the "best", 10933 // another pass to be sure that nothing is better than the best. 10934 auto Best = Matches.begin(); 10935 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10936 if (isBetterCandidate(I->second, Best->second)) 10937 Best = I; 10938 10939 const FunctionDecl *BestFn = Best->second; 10940 auto IsBestOrInferiorToBest = [this, BestFn]( 10941 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10942 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10943 }; 10944 10945 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10946 // option, so we can potentially give the user a better error 10947 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10948 return false; 10949 Matches[0] = *Best; 10950 Matches.resize(1); 10951 return true; 10952 } 10953 10954 bool isTargetTypeAFunction() const { 10955 return TargetFunctionType->isFunctionType(); 10956 } 10957 10958 // [ToType] [Return] 10959 10960 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10961 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10962 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10963 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10964 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10965 } 10966 10967 // return true if any matching specializations were found 10968 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10969 const DeclAccessPair& CurAccessFunPair) { 10970 if (CXXMethodDecl *Method 10971 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10972 // Skip non-static function templates when converting to pointer, and 10973 // static when converting to member pointer. 10974 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10975 return false; 10976 } 10977 else if (TargetTypeIsNonStaticMemberFunction) 10978 return false; 10979 10980 // C++ [over.over]p2: 10981 // If the name is a function template, template argument deduction is 10982 // done (14.8.2.2), and if the argument deduction succeeds, the 10983 // resulting template argument list is used to generate a single 10984 // function template specialization, which is added to the set of 10985 // overloaded functions considered. 10986 FunctionDecl *Specialization = nullptr; 10987 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10988 if (Sema::TemplateDeductionResult Result 10989 = S.DeduceTemplateArguments(FunctionTemplate, 10990 &OvlExplicitTemplateArgs, 10991 TargetFunctionType, Specialization, 10992 Info, /*IsAddressOfFunction*/true)) { 10993 // Make a note of the failed deduction for diagnostics. 10994 FailedCandidates.addCandidate() 10995 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10996 MakeDeductionFailureInfo(Context, Result, Info)); 10997 return false; 10998 } 10999 11000 // Template argument deduction ensures that we have an exact match or 11001 // compatible pointer-to-function arguments that would be adjusted by ICS. 11002 // This function template specicalization works. 11003 assert(S.isSameOrCompatibleFunctionType( 11004 Context.getCanonicalType(Specialization->getType()), 11005 Context.getCanonicalType(TargetFunctionType))); 11006 11007 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11008 return false; 11009 11010 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11011 return true; 11012 } 11013 11014 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11015 const DeclAccessPair& CurAccessFunPair) { 11016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11017 // Skip non-static functions when converting to pointer, and static 11018 // when converting to member pointer. 11019 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11020 return false; 11021 } 11022 else if (TargetTypeIsNonStaticMemberFunction) 11023 return false; 11024 11025 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11026 if (S.getLangOpts().CUDA) 11027 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11028 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11029 return false; 11030 if (FunDecl->isMultiVersion()) { 11031 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11032 assert(TA && "Multiversioned functions require a target attribute"); 11033 if (!TA->isDefaultVersion()) 11034 return false; 11035 } 11036 11037 // If any candidate has a placeholder return type, trigger its deduction 11038 // now. 11039 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 11040 Complain)) { 11041 HasComplained |= Complain; 11042 return false; 11043 } 11044 11045 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11046 return false; 11047 11048 // If we're in C, we need to support types that aren't exactly identical. 11049 if (!S.getLangOpts().CPlusPlus || 11050 candidateHasExactlyCorrectType(FunDecl)) { 11051 Matches.push_back(std::make_pair( 11052 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11053 FoundNonTemplateFunction = true; 11054 return true; 11055 } 11056 } 11057 11058 return false; 11059 } 11060 11061 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11062 bool Ret = false; 11063 11064 // If the overload expression doesn't have the form of a pointer to 11065 // member, don't try to convert it to a pointer-to-member type. 11066 if (IsInvalidFormOfPointerToMemberFunction()) 11067 return false; 11068 11069 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11070 E = OvlExpr->decls_end(); 11071 I != E; ++I) { 11072 // Look through any using declarations to find the underlying function. 11073 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11074 11075 // C++ [over.over]p3: 11076 // Non-member functions and static member functions match 11077 // targets of type "pointer-to-function" or "reference-to-function." 11078 // Nonstatic member functions match targets of 11079 // type "pointer-to-member-function." 11080 // Note that according to DR 247, the containing class does not matter. 11081 if (FunctionTemplateDecl *FunctionTemplate 11082 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11083 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11084 Ret = true; 11085 } 11086 // If we have explicit template arguments supplied, skip non-templates. 11087 else if (!OvlExpr->hasExplicitTemplateArgs() && 11088 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11089 Ret = true; 11090 } 11091 assert(Ret || Matches.empty()); 11092 return Ret; 11093 } 11094 11095 void EliminateAllExceptMostSpecializedTemplate() { 11096 // [...] and any given function template specialization F1 is 11097 // eliminated if the set contains a second function template 11098 // specialization whose function template is more specialized 11099 // than the function template of F1 according to the partial 11100 // ordering rules of 14.5.5.2. 11101 11102 // The algorithm specified above is quadratic. We instead use a 11103 // two-pass algorithm (similar to the one used to identify the 11104 // best viable function in an overload set) that identifies the 11105 // best function template (if it exists). 11106 11107 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11108 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11109 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11110 11111 // TODO: It looks like FailedCandidates does not serve much purpose 11112 // here, since the no_viable diagnostic has index 0. 11113 UnresolvedSetIterator Result = S.getMostSpecialized( 11114 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11115 SourceExpr->getLocStart(), S.PDiag(), 11116 S.PDiag(diag::err_addr_ovl_ambiguous) 11117 << Matches[0].second->getDeclName(), 11118 S.PDiag(diag::note_ovl_candidate) 11119 << (unsigned)oc_function << (unsigned)ocs_described_template, 11120 Complain, TargetFunctionType); 11121 11122 if (Result != MatchesCopy.end()) { 11123 // Make it the first and only element 11124 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11125 Matches[0].second = cast<FunctionDecl>(*Result); 11126 Matches.resize(1); 11127 } else 11128 HasComplained |= Complain; 11129 } 11130 11131 void EliminateAllTemplateMatches() { 11132 // [...] any function template specializations in the set are 11133 // eliminated if the set also contains a non-template function, [...] 11134 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11135 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11136 ++I; 11137 else { 11138 Matches[I] = Matches[--N]; 11139 Matches.resize(N); 11140 } 11141 } 11142 } 11143 11144 void EliminateSuboptimalCudaMatches() { 11145 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11146 } 11147 11148 public: 11149 void ComplainNoMatchesFound() const { 11150 assert(Matches.empty()); 11151 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 11152 << OvlExpr->getName() << TargetFunctionType 11153 << OvlExpr->getSourceRange(); 11154 if (FailedCandidates.empty()) 11155 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11156 /*TakingAddress=*/true); 11157 else { 11158 // We have some deduction failure messages. Use them to diagnose 11159 // the function templates, and diagnose the non-template candidates 11160 // normally. 11161 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11162 IEnd = OvlExpr->decls_end(); 11163 I != IEnd; ++I) 11164 if (FunctionDecl *Fun = 11165 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11166 if (!functionHasPassObjectSizeParams(Fun)) 11167 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11168 /*TakingAddress=*/true); 11169 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 11170 } 11171 } 11172 11173 bool IsInvalidFormOfPointerToMemberFunction() const { 11174 return TargetTypeIsNonStaticMemberFunction && 11175 !OvlExprInfo.HasFormOfMemberPointer; 11176 } 11177 11178 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11179 // TODO: Should we condition this on whether any functions might 11180 // have matched, or is it more appropriate to do that in callers? 11181 // TODO: a fixit wouldn't hurt. 11182 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11183 << TargetType << OvlExpr->getSourceRange(); 11184 } 11185 11186 bool IsStaticMemberFunctionFromBoundPointer() const { 11187 return StaticMemberFunctionFromBoundPointer; 11188 } 11189 11190 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11191 S.Diag(OvlExpr->getLocStart(), 11192 diag::err_invalid_form_pointer_member_function) 11193 << OvlExpr->getSourceRange(); 11194 } 11195 11196 void ComplainOfInvalidConversion() const { 11197 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 11198 << OvlExpr->getName() << TargetType; 11199 } 11200 11201 void ComplainMultipleMatchesFound() const { 11202 assert(Matches.size() > 1); 11203 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 11204 << OvlExpr->getName() 11205 << OvlExpr->getSourceRange(); 11206 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11207 /*TakingAddress=*/true); 11208 } 11209 11210 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11211 11212 int getNumMatches() const { return Matches.size(); } 11213 11214 FunctionDecl* getMatchingFunctionDecl() const { 11215 if (Matches.size() != 1) return nullptr; 11216 return Matches[0].second; 11217 } 11218 11219 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11220 if (Matches.size() != 1) return nullptr; 11221 return &Matches[0].first; 11222 } 11223 }; 11224 } 11225 11226 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11227 /// an overloaded function (C++ [over.over]), where @p From is an 11228 /// expression with overloaded function type and @p ToType is the type 11229 /// we're trying to resolve to. For example: 11230 /// 11231 /// @code 11232 /// int f(double); 11233 /// int f(int); 11234 /// 11235 /// int (*pfd)(double) = f; // selects f(double) 11236 /// @endcode 11237 /// 11238 /// This routine returns the resulting FunctionDecl if it could be 11239 /// resolved, and NULL otherwise. When @p Complain is true, this 11240 /// routine will emit diagnostics if there is an error. 11241 FunctionDecl * 11242 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11243 QualType TargetType, 11244 bool Complain, 11245 DeclAccessPair &FoundResult, 11246 bool *pHadMultipleCandidates) { 11247 assert(AddressOfExpr->getType() == Context.OverloadTy); 11248 11249 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11250 Complain); 11251 int NumMatches = Resolver.getNumMatches(); 11252 FunctionDecl *Fn = nullptr; 11253 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11254 if (NumMatches == 0 && ShouldComplain) { 11255 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11256 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11257 else 11258 Resolver.ComplainNoMatchesFound(); 11259 } 11260 else if (NumMatches > 1 && ShouldComplain) 11261 Resolver.ComplainMultipleMatchesFound(); 11262 else if (NumMatches == 1) { 11263 Fn = Resolver.getMatchingFunctionDecl(); 11264 assert(Fn); 11265 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11266 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11267 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11268 if (Complain) { 11269 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11270 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11271 else 11272 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11273 } 11274 } 11275 11276 if (pHadMultipleCandidates) 11277 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11278 return Fn; 11279 } 11280 11281 /// Given an expression that refers to an overloaded function, try to 11282 /// resolve that function to a single function that can have its address taken. 11283 /// This will modify `Pair` iff it returns non-null. 11284 /// 11285 /// This routine can only realistically succeed if all but one candidates in the 11286 /// overload set for SrcExpr cannot have their addresses taken. 11287 FunctionDecl * 11288 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11289 DeclAccessPair &Pair) { 11290 OverloadExpr::FindResult R = OverloadExpr::find(E); 11291 OverloadExpr *Ovl = R.Expression; 11292 FunctionDecl *Result = nullptr; 11293 DeclAccessPair DAP; 11294 // Don't use the AddressOfResolver because we're specifically looking for 11295 // cases where we have one overload candidate that lacks 11296 // enable_if/pass_object_size/... 11297 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11298 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11299 if (!FD) 11300 return nullptr; 11301 11302 if (!checkAddressOfFunctionIsAvailable(FD)) 11303 continue; 11304 11305 // We have more than one result; quit. 11306 if (Result) 11307 return nullptr; 11308 DAP = I.getPair(); 11309 Result = FD; 11310 } 11311 11312 if (Result) 11313 Pair = DAP; 11314 return Result; 11315 } 11316 11317 /// Given an overloaded function, tries to turn it into a non-overloaded 11318 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11319 /// will perform access checks, diagnose the use of the resultant decl, and, if 11320 /// requested, potentially perform a function-to-pointer decay. 11321 /// 11322 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11323 /// Otherwise, returns true. This may emit diagnostics and return true. 11324 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11325 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11326 Expr *E = SrcExpr.get(); 11327 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11328 11329 DeclAccessPair DAP; 11330 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11331 if (!Found) 11332 return false; 11333 11334 // Emitting multiple diagnostics for a function that is both inaccessible and 11335 // unavailable is consistent with our behavior elsewhere. So, always check 11336 // for both. 11337 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11338 CheckAddressOfMemberAccess(E, DAP); 11339 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11340 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11341 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11342 else 11343 SrcExpr = Fixed; 11344 return true; 11345 } 11346 11347 /// Given an expression that refers to an overloaded function, try to 11348 /// resolve that overloaded function expression down to a single function. 11349 /// 11350 /// This routine can only resolve template-ids that refer to a single function 11351 /// template, where that template-id refers to a single template whose template 11352 /// arguments are either provided by the template-id or have defaults, 11353 /// as described in C++0x [temp.arg.explicit]p3. 11354 /// 11355 /// If no template-ids are found, no diagnostics are emitted and NULL is 11356 /// returned. 11357 FunctionDecl * 11358 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11359 bool Complain, 11360 DeclAccessPair *FoundResult) { 11361 // C++ [over.over]p1: 11362 // [...] [Note: any redundant set of parentheses surrounding the 11363 // overloaded function name is ignored (5.1). ] 11364 // C++ [over.over]p1: 11365 // [...] The overloaded function name can be preceded by the & 11366 // operator. 11367 11368 // If we didn't actually find any template-ids, we're done. 11369 if (!ovl->hasExplicitTemplateArgs()) 11370 return nullptr; 11371 11372 TemplateArgumentListInfo ExplicitTemplateArgs; 11373 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11374 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11375 11376 // Look through all of the overloaded functions, searching for one 11377 // whose type matches exactly. 11378 FunctionDecl *Matched = nullptr; 11379 for (UnresolvedSetIterator I = ovl->decls_begin(), 11380 E = ovl->decls_end(); I != E; ++I) { 11381 // C++0x [temp.arg.explicit]p3: 11382 // [...] In contexts where deduction is done and fails, or in contexts 11383 // where deduction is not done, if a template argument list is 11384 // specified and it, along with any default template arguments, 11385 // identifies a single function template specialization, then the 11386 // template-id is an lvalue for the function template specialization. 11387 FunctionTemplateDecl *FunctionTemplate 11388 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11389 11390 // C++ [over.over]p2: 11391 // If the name is a function template, template argument deduction is 11392 // done (14.8.2.2), and if the argument deduction succeeds, the 11393 // resulting template argument list is used to generate a single 11394 // function template specialization, which is added to the set of 11395 // overloaded functions considered. 11396 FunctionDecl *Specialization = nullptr; 11397 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11398 if (TemplateDeductionResult Result 11399 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11400 Specialization, Info, 11401 /*IsAddressOfFunction*/true)) { 11402 // Make a note of the failed deduction for diagnostics. 11403 // TODO: Actually use the failed-deduction info? 11404 FailedCandidates.addCandidate() 11405 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11406 MakeDeductionFailureInfo(Context, Result, Info)); 11407 continue; 11408 } 11409 11410 assert(Specialization && "no specialization and no error?"); 11411 11412 // Multiple matches; we can't resolve to a single declaration. 11413 if (Matched) { 11414 if (Complain) { 11415 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11416 << ovl->getName(); 11417 NoteAllOverloadCandidates(ovl); 11418 } 11419 return nullptr; 11420 } 11421 11422 Matched = Specialization; 11423 if (FoundResult) *FoundResult = I.getPair(); 11424 } 11425 11426 if (Matched && 11427 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11428 return nullptr; 11429 11430 return Matched; 11431 } 11432 11433 // Resolve and fix an overloaded expression that can be resolved 11434 // because it identifies a single function template specialization. 11435 // 11436 // Last three arguments should only be supplied if Complain = true 11437 // 11438 // Return true if it was logically possible to so resolve the 11439 // expression, regardless of whether or not it succeeded. Always 11440 // returns true if 'complain' is set. 11441 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11442 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11443 bool complain, SourceRange OpRangeForComplaining, 11444 QualType DestTypeForComplaining, 11445 unsigned DiagIDForComplaining) { 11446 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11447 11448 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11449 11450 DeclAccessPair found; 11451 ExprResult SingleFunctionExpression; 11452 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11453 ovl.Expression, /*complain*/ false, &found)) { 11454 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11455 SrcExpr = ExprError(); 11456 return true; 11457 } 11458 11459 // It is only correct to resolve to an instance method if we're 11460 // resolving a form that's permitted to be a pointer to member. 11461 // Otherwise we'll end up making a bound member expression, which 11462 // is illegal in all the contexts we resolve like this. 11463 if (!ovl.HasFormOfMemberPointer && 11464 isa<CXXMethodDecl>(fn) && 11465 cast<CXXMethodDecl>(fn)->isInstance()) { 11466 if (!complain) return false; 11467 11468 Diag(ovl.Expression->getExprLoc(), 11469 diag::err_bound_member_function) 11470 << 0 << ovl.Expression->getSourceRange(); 11471 11472 // TODO: I believe we only end up here if there's a mix of 11473 // static and non-static candidates (otherwise the expression 11474 // would have 'bound member' type, not 'overload' type). 11475 // Ideally we would note which candidate was chosen and why 11476 // the static candidates were rejected. 11477 SrcExpr = ExprError(); 11478 return true; 11479 } 11480 11481 // Fix the expression to refer to 'fn'. 11482 SingleFunctionExpression = 11483 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11484 11485 // If desired, do function-to-pointer decay. 11486 if (doFunctionPointerConverion) { 11487 SingleFunctionExpression = 11488 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11489 if (SingleFunctionExpression.isInvalid()) { 11490 SrcExpr = ExprError(); 11491 return true; 11492 } 11493 } 11494 } 11495 11496 if (!SingleFunctionExpression.isUsable()) { 11497 if (complain) { 11498 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11499 << ovl.Expression->getName() 11500 << DestTypeForComplaining 11501 << OpRangeForComplaining 11502 << ovl.Expression->getQualifierLoc().getSourceRange(); 11503 NoteAllOverloadCandidates(SrcExpr.get()); 11504 11505 SrcExpr = ExprError(); 11506 return true; 11507 } 11508 11509 return false; 11510 } 11511 11512 SrcExpr = SingleFunctionExpression; 11513 return true; 11514 } 11515 11516 /// Add a single candidate to the overload set. 11517 static void AddOverloadedCallCandidate(Sema &S, 11518 DeclAccessPair FoundDecl, 11519 TemplateArgumentListInfo *ExplicitTemplateArgs, 11520 ArrayRef<Expr *> Args, 11521 OverloadCandidateSet &CandidateSet, 11522 bool PartialOverloading, 11523 bool KnownValid) { 11524 NamedDecl *Callee = FoundDecl.getDecl(); 11525 if (isa<UsingShadowDecl>(Callee)) 11526 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11527 11528 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11529 if (ExplicitTemplateArgs) { 11530 assert(!KnownValid && "Explicit template arguments?"); 11531 return; 11532 } 11533 // Prevent ill-formed function decls to be added as overload candidates. 11534 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11535 return; 11536 11537 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11538 /*SuppressUsedConversions=*/false, 11539 PartialOverloading); 11540 return; 11541 } 11542 11543 if (FunctionTemplateDecl *FuncTemplate 11544 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11545 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11546 ExplicitTemplateArgs, Args, CandidateSet, 11547 /*SuppressUsedConversions=*/false, 11548 PartialOverloading); 11549 return; 11550 } 11551 11552 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11553 } 11554 11555 /// Add the overload candidates named by callee and/or found by argument 11556 /// dependent lookup to the given overload set. 11557 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11558 ArrayRef<Expr *> Args, 11559 OverloadCandidateSet &CandidateSet, 11560 bool PartialOverloading) { 11561 11562 #ifndef NDEBUG 11563 // Verify that ArgumentDependentLookup is consistent with the rules 11564 // in C++0x [basic.lookup.argdep]p3: 11565 // 11566 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11567 // and let Y be the lookup set produced by argument dependent 11568 // lookup (defined as follows). If X contains 11569 // 11570 // -- a declaration of a class member, or 11571 // 11572 // -- a block-scope function declaration that is not a 11573 // using-declaration, or 11574 // 11575 // -- a declaration that is neither a function or a function 11576 // template 11577 // 11578 // then Y is empty. 11579 11580 if (ULE->requiresADL()) { 11581 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11582 E = ULE->decls_end(); I != E; ++I) { 11583 assert(!(*I)->getDeclContext()->isRecord()); 11584 assert(isa<UsingShadowDecl>(*I) || 11585 !(*I)->getDeclContext()->isFunctionOrMethod()); 11586 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11587 } 11588 } 11589 #endif 11590 11591 // It would be nice to avoid this copy. 11592 TemplateArgumentListInfo TABuffer; 11593 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11594 if (ULE->hasExplicitTemplateArgs()) { 11595 ULE->copyTemplateArgumentsInto(TABuffer); 11596 ExplicitTemplateArgs = &TABuffer; 11597 } 11598 11599 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11600 E = ULE->decls_end(); I != E; ++I) 11601 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11602 CandidateSet, PartialOverloading, 11603 /*KnownValid*/ true); 11604 11605 if (ULE->requiresADL()) 11606 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11607 Args, ExplicitTemplateArgs, 11608 CandidateSet, PartialOverloading); 11609 } 11610 11611 /// Determine whether a declaration with the specified name could be moved into 11612 /// a different namespace. 11613 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11614 switch (Name.getCXXOverloadedOperator()) { 11615 case OO_New: case OO_Array_New: 11616 case OO_Delete: case OO_Array_Delete: 11617 return false; 11618 11619 default: 11620 return true; 11621 } 11622 } 11623 11624 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11625 /// template, where the non-dependent name was declared after the template 11626 /// was defined. This is common in code written for a compilers which do not 11627 /// correctly implement two-stage name lookup. 11628 /// 11629 /// Returns true if a viable candidate was found and a diagnostic was issued. 11630 static bool 11631 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11632 const CXXScopeSpec &SS, LookupResult &R, 11633 OverloadCandidateSet::CandidateSetKind CSK, 11634 TemplateArgumentListInfo *ExplicitTemplateArgs, 11635 ArrayRef<Expr *> Args, 11636 bool *DoDiagnoseEmptyLookup = nullptr) { 11637 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11638 return false; 11639 11640 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11641 if (DC->isTransparentContext()) 11642 continue; 11643 11644 SemaRef.LookupQualifiedName(R, DC); 11645 11646 if (!R.empty()) { 11647 R.suppressDiagnostics(); 11648 11649 if (isa<CXXRecordDecl>(DC)) { 11650 // Don't diagnose names we find in classes; we get much better 11651 // diagnostics for these from DiagnoseEmptyLookup. 11652 R.clear(); 11653 if (DoDiagnoseEmptyLookup) 11654 *DoDiagnoseEmptyLookup = true; 11655 return false; 11656 } 11657 11658 OverloadCandidateSet Candidates(FnLoc, CSK); 11659 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11660 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11661 ExplicitTemplateArgs, Args, 11662 Candidates, false, /*KnownValid*/ false); 11663 11664 OverloadCandidateSet::iterator Best; 11665 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11666 // No viable functions. Don't bother the user with notes for functions 11667 // which don't work and shouldn't be found anyway. 11668 R.clear(); 11669 return false; 11670 } 11671 11672 // Find the namespaces where ADL would have looked, and suggest 11673 // declaring the function there instead. 11674 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11675 Sema::AssociatedClassSet AssociatedClasses; 11676 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11677 AssociatedNamespaces, 11678 AssociatedClasses); 11679 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11680 if (canBeDeclaredInNamespace(R.getLookupName())) { 11681 DeclContext *Std = SemaRef.getStdNamespace(); 11682 for (Sema::AssociatedNamespaceSet::iterator 11683 it = AssociatedNamespaces.begin(), 11684 end = AssociatedNamespaces.end(); it != end; ++it) { 11685 // Never suggest declaring a function within namespace 'std'. 11686 if (Std && Std->Encloses(*it)) 11687 continue; 11688 11689 // Never suggest declaring a function within a namespace with a 11690 // reserved name, like __gnu_cxx. 11691 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11692 if (NS && 11693 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11694 continue; 11695 11696 SuggestedNamespaces.insert(*it); 11697 } 11698 } 11699 11700 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11701 << R.getLookupName(); 11702 if (SuggestedNamespaces.empty()) { 11703 SemaRef.Diag(Best->Function->getLocation(), 11704 diag::note_not_found_by_two_phase_lookup) 11705 << R.getLookupName() << 0; 11706 } else if (SuggestedNamespaces.size() == 1) { 11707 SemaRef.Diag(Best->Function->getLocation(), 11708 diag::note_not_found_by_two_phase_lookup) 11709 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11710 } else { 11711 // FIXME: It would be useful to list the associated namespaces here, 11712 // but the diagnostics infrastructure doesn't provide a way to produce 11713 // a localized representation of a list of items. 11714 SemaRef.Diag(Best->Function->getLocation(), 11715 diag::note_not_found_by_two_phase_lookup) 11716 << R.getLookupName() << 2; 11717 } 11718 11719 // Try to recover by calling this function. 11720 return true; 11721 } 11722 11723 R.clear(); 11724 } 11725 11726 return false; 11727 } 11728 11729 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11730 /// template, where the non-dependent operator was declared after the template 11731 /// was defined. 11732 /// 11733 /// Returns true if a viable candidate was found and a diagnostic was issued. 11734 static bool 11735 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11736 SourceLocation OpLoc, 11737 ArrayRef<Expr *> Args) { 11738 DeclarationName OpName = 11739 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11740 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11741 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11742 OverloadCandidateSet::CSK_Operator, 11743 /*ExplicitTemplateArgs=*/nullptr, Args); 11744 } 11745 11746 namespace { 11747 class BuildRecoveryCallExprRAII { 11748 Sema &SemaRef; 11749 public: 11750 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11751 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11752 SemaRef.IsBuildingRecoveryCallExpr = true; 11753 } 11754 11755 ~BuildRecoveryCallExprRAII() { 11756 SemaRef.IsBuildingRecoveryCallExpr = false; 11757 } 11758 }; 11759 11760 } 11761 11762 static std::unique_ptr<CorrectionCandidateCallback> 11763 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11764 bool HasTemplateArgs, bool AllowTypoCorrection) { 11765 if (!AllowTypoCorrection) 11766 return llvm::make_unique<NoTypoCorrectionCCC>(); 11767 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11768 HasTemplateArgs, ME); 11769 } 11770 11771 /// Attempts to recover from a call where no functions were found. 11772 /// 11773 /// Returns true if new candidates were found. 11774 static ExprResult 11775 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11776 UnresolvedLookupExpr *ULE, 11777 SourceLocation LParenLoc, 11778 MutableArrayRef<Expr *> Args, 11779 SourceLocation RParenLoc, 11780 bool EmptyLookup, bool AllowTypoCorrection) { 11781 // Do not try to recover if it is already building a recovery call. 11782 // This stops infinite loops for template instantiations like 11783 // 11784 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11785 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11786 // 11787 if (SemaRef.IsBuildingRecoveryCallExpr) 11788 return ExprError(); 11789 BuildRecoveryCallExprRAII RCE(SemaRef); 11790 11791 CXXScopeSpec SS; 11792 SS.Adopt(ULE->getQualifierLoc()); 11793 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11794 11795 TemplateArgumentListInfo TABuffer; 11796 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11797 if (ULE->hasExplicitTemplateArgs()) { 11798 ULE->copyTemplateArgumentsInto(TABuffer); 11799 ExplicitTemplateArgs = &TABuffer; 11800 } 11801 11802 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11803 Sema::LookupOrdinaryName); 11804 bool DoDiagnoseEmptyLookup = EmptyLookup; 11805 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11806 OverloadCandidateSet::CSK_Normal, 11807 ExplicitTemplateArgs, Args, 11808 &DoDiagnoseEmptyLookup) && 11809 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11810 S, SS, R, 11811 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11812 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11813 ExplicitTemplateArgs, Args))) 11814 return ExprError(); 11815 11816 assert(!R.empty() && "lookup results empty despite recovery"); 11817 11818 // If recovery created an ambiguity, just bail out. 11819 if (R.isAmbiguous()) { 11820 R.suppressDiagnostics(); 11821 return ExprError(); 11822 } 11823 11824 // Build an implicit member call if appropriate. Just drop the 11825 // casts and such from the call, we don't really care. 11826 ExprResult NewFn = ExprError(); 11827 if ((*R.begin())->isCXXClassMember()) 11828 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11829 ExplicitTemplateArgs, S); 11830 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11831 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11832 ExplicitTemplateArgs); 11833 else 11834 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11835 11836 if (NewFn.isInvalid()) 11837 return ExprError(); 11838 11839 // This shouldn't cause an infinite loop because we're giving it 11840 // an expression with viable lookup results, which should never 11841 // end up here. 11842 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11843 MultiExprArg(Args.data(), Args.size()), 11844 RParenLoc); 11845 } 11846 11847 /// Constructs and populates an OverloadedCandidateSet from 11848 /// the given function. 11849 /// \returns true when an the ExprResult output parameter has been set. 11850 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11851 UnresolvedLookupExpr *ULE, 11852 MultiExprArg Args, 11853 SourceLocation RParenLoc, 11854 OverloadCandidateSet *CandidateSet, 11855 ExprResult *Result) { 11856 #ifndef NDEBUG 11857 if (ULE->requiresADL()) { 11858 // To do ADL, we must have found an unqualified name. 11859 assert(!ULE->getQualifier() && "qualified name with ADL"); 11860 11861 // We don't perform ADL for implicit declarations of builtins. 11862 // Verify that this was correctly set up. 11863 FunctionDecl *F; 11864 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11865 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11866 F->getBuiltinID() && F->isImplicit()) 11867 llvm_unreachable("performing ADL for builtin"); 11868 11869 // We don't perform ADL in C. 11870 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11871 } 11872 #endif 11873 11874 UnbridgedCastsSet UnbridgedCasts; 11875 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11876 *Result = ExprError(); 11877 return true; 11878 } 11879 11880 // Add the functions denoted by the callee to the set of candidate 11881 // functions, including those from argument-dependent lookup. 11882 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11883 11884 if (getLangOpts().MSVCCompat && 11885 CurContext->isDependentContext() && !isSFINAEContext() && 11886 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11887 11888 OverloadCandidateSet::iterator Best; 11889 if (CandidateSet->empty() || 11890 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11891 OR_No_Viable_Function) { 11892 // In Microsoft mode, if we are inside a template class member function then 11893 // create a type dependent CallExpr. The goal is to postpone name lookup 11894 // to instantiation time to be able to search into type dependent base 11895 // classes. 11896 CallExpr *CE = new (Context) CallExpr( 11897 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11898 CE->setTypeDependent(true); 11899 CE->setValueDependent(true); 11900 CE->setInstantiationDependent(true); 11901 *Result = CE; 11902 return true; 11903 } 11904 } 11905 11906 if (CandidateSet->empty()) 11907 return false; 11908 11909 UnbridgedCasts.restore(); 11910 return false; 11911 } 11912 11913 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11914 /// the completed call expression. If overload resolution fails, emits 11915 /// diagnostics and returns ExprError() 11916 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11917 UnresolvedLookupExpr *ULE, 11918 SourceLocation LParenLoc, 11919 MultiExprArg Args, 11920 SourceLocation RParenLoc, 11921 Expr *ExecConfig, 11922 OverloadCandidateSet *CandidateSet, 11923 OverloadCandidateSet::iterator *Best, 11924 OverloadingResult OverloadResult, 11925 bool AllowTypoCorrection) { 11926 if (CandidateSet->empty()) 11927 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11928 RParenLoc, /*EmptyLookup=*/true, 11929 AllowTypoCorrection); 11930 11931 switch (OverloadResult) { 11932 case OR_Success: { 11933 FunctionDecl *FDecl = (*Best)->Function; 11934 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11935 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11936 return ExprError(); 11937 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11938 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11939 ExecConfig); 11940 } 11941 11942 case OR_No_Viable_Function: { 11943 // Try to recover by looking for viable functions which the user might 11944 // have meant to call. 11945 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11946 Args, RParenLoc, 11947 /*EmptyLookup=*/false, 11948 AllowTypoCorrection); 11949 if (!Recovery.isInvalid()) 11950 return Recovery; 11951 11952 // If the user passes in a function that we can't take the address of, we 11953 // generally end up emitting really bad error messages. Here, we attempt to 11954 // emit better ones. 11955 for (const Expr *Arg : Args) { 11956 if (!Arg->getType()->isFunctionType()) 11957 continue; 11958 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11959 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11960 if (FD && 11961 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11962 Arg->getExprLoc())) 11963 return ExprError(); 11964 } 11965 } 11966 11967 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11968 << ULE->getName() << Fn->getSourceRange(); 11969 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11970 break; 11971 } 11972 11973 case OR_Ambiguous: 11974 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11975 << ULE->getName() << Fn->getSourceRange(); 11976 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11977 break; 11978 11979 case OR_Deleted: { 11980 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11981 << (*Best)->Function->isDeleted() 11982 << ULE->getName() 11983 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11984 << Fn->getSourceRange(); 11985 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11986 11987 // We emitted an error for the unavailable/deleted function call but keep 11988 // the call in the AST. 11989 FunctionDecl *FDecl = (*Best)->Function; 11990 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11991 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11992 ExecConfig); 11993 } 11994 } 11995 11996 // Overload resolution failed. 11997 return ExprError(); 11998 } 11999 12000 static void markUnaddressableCandidatesUnviable(Sema &S, 12001 OverloadCandidateSet &CS) { 12002 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12003 if (I->Viable && 12004 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12005 I->Viable = false; 12006 I->FailureKind = ovl_fail_addr_not_available; 12007 } 12008 } 12009 } 12010 12011 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12012 /// (which eventually refers to the declaration Func) and the call 12013 /// arguments Args/NumArgs, attempt to resolve the function call down 12014 /// to a specific function. If overload resolution succeeds, returns 12015 /// the call expression produced by overload resolution. 12016 /// Otherwise, emits diagnostics and returns ExprError. 12017 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12018 UnresolvedLookupExpr *ULE, 12019 SourceLocation LParenLoc, 12020 MultiExprArg Args, 12021 SourceLocation RParenLoc, 12022 Expr *ExecConfig, 12023 bool AllowTypoCorrection, 12024 bool CalleesAddressIsTaken) { 12025 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12026 OverloadCandidateSet::CSK_Normal); 12027 ExprResult result; 12028 12029 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12030 &result)) 12031 return result; 12032 12033 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12034 // functions that aren't addressible are considered unviable. 12035 if (CalleesAddressIsTaken) 12036 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12037 12038 OverloadCandidateSet::iterator Best; 12039 OverloadingResult OverloadResult = 12040 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 12041 12042 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12043 RParenLoc, ExecConfig, &CandidateSet, 12044 &Best, OverloadResult, 12045 AllowTypoCorrection); 12046 } 12047 12048 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12049 return Functions.size() > 1 || 12050 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12051 } 12052 12053 /// Create a unary operation that may resolve to an overloaded 12054 /// operator. 12055 /// 12056 /// \param OpLoc The location of the operator itself (e.g., '*'). 12057 /// 12058 /// \param Opc The UnaryOperatorKind that describes this operator. 12059 /// 12060 /// \param Fns The set of non-member functions that will be 12061 /// considered by overload resolution. The caller needs to build this 12062 /// set based on the context using, e.g., 12063 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12064 /// set should not contain any member functions; those will be added 12065 /// by CreateOverloadedUnaryOp(). 12066 /// 12067 /// \param Input The input argument. 12068 ExprResult 12069 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12070 const UnresolvedSetImpl &Fns, 12071 Expr *Input, bool PerformADL) { 12072 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12073 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12074 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12075 // TODO: provide better source location info. 12076 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12077 12078 if (checkPlaceholderForOverload(*this, Input)) 12079 return ExprError(); 12080 12081 Expr *Args[2] = { Input, nullptr }; 12082 unsigned NumArgs = 1; 12083 12084 // For post-increment and post-decrement, add the implicit '0' as 12085 // the second argument, so that we know this is a post-increment or 12086 // post-decrement. 12087 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12088 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12089 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12090 SourceLocation()); 12091 NumArgs = 2; 12092 } 12093 12094 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12095 12096 if (Input->isTypeDependent()) { 12097 if (Fns.empty()) 12098 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12099 VK_RValue, OK_Ordinary, OpLoc, false); 12100 12101 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12102 UnresolvedLookupExpr *Fn 12103 = UnresolvedLookupExpr::Create(Context, NamingClass, 12104 NestedNameSpecifierLoc(), OpNameInfo, 12105 /*ADL*/ true, IsOverloaded(Fns), 12106 Fns.begin(), Fns.end()); 12107 return new (Context) 12108 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 12109 VK_RValue, OpLoc, FPOptions()); 12110 } 12111 12112 // Build an empty overload set. 12113 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12114 12115 // Add the candidates from the given function set. 12116 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12117 12118 // Add operator candidates that are member functions. 12119 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12120 12121 // Add candidates from ADL. 12122 if (PerformADL) { 12123 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12124 /*ExplicitTemplateArgs*/nullptr, 12125 CandidateSet); 12126 } 12127 12128 // Add builtin operator candidates. 12129 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12130 12131 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12132 12133 // Perform overload resolution. 12134 OverloadCandidateSet::iterator Best; 12135 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12136 case OR_Success: { 12137 // We found a built-in operator or an overloaded operator. 12138 FunctionDecl *FnDecl = Best->Function; 12139 12140 if (FnDecl) { 12141 Expr *Base = nullptr; 12142 // We matched an overloaded operator. Build a call to that 12143 // operator. 12144 12145 // Convert the arguments. 12146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12147 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12148 12149 ExprResult InputRes = 12150 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12151 Best->FoundDecl, Method); 12152 if (InputRes.isInvalid()) 12153 return ExprError(); 12154 Base = Input = InputRes.get(); 12155 } else { 12156 // Convert the arguments. 12157 ExprResult InputInit 12158 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12159 Context, 12160 FnDecl->getParamDecl(0)), 12161 SourceLocation(), 12162 Input); 12163 if (InputInit.isInvalid()) 12164 return ExprError(); 12165 Input = InputInit.get(); 12166 } 12167 12168 // Build the actual expression node. 12169 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12170 Base, HadMultipleCandidates, 12171 OpLoc); 12172 if (FnExpr.isInvalid()) 12173 return ExprError(); 12174 12175 // Determine the result type. 12176 QualType ResultTy = FnDecl->getReturnType(); 12177 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12178 ResultTy = ResultTy.getNonLValueExprType(Context); 12179 12180 Args[0] = Input; 12181 CallExpr *TheCall = 12182 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12183 ResultTy, VK, OpLoc, FPOptions()); 12184 12185 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12186 return ExprError(); 12187 12188 if (CheckFunctionCall(FnDecl, TheCall, 12189 FnDecl->getType()->castAs<FunctionProtoType>())) 12190 return ExprError(); 12191 12192 return MaybeBindToTemporary(TheCall); 12193 } else { 12194 // We matched a built-in operator. Convert the arguments, then 12195 // break out so that we will build the appropriate built-in 12196 // operator node. 12197 ExprResult InputRes = PerformImplicitConversion( 12198 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing); 12199 if (InputRes.isInvalid()) 12200 return ExprError(); 12201 Input = InputRes.get(); 12202 break; 12203 } 12204 } 12205 12206 case OR_No_Viable_Function: 12207 // This is an erroneous use of an operator which can be overloaded by 12208 // a non-member function. Check for non-member operators which were 12209 // defined too late to be candidates. 12210 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12211 // FIXME: Recover by calling the found function. 12212 return ExprError(); 12213 12214 // No viable function; fall through to handling this as a 12215 // built-in operator, which will produce an error message for us. 12216 break; 12217 12218 case OR_Ambiguous: 12219 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12220 << UnaryOperator::getOpcodeStr(Opc) 12221 << Input->getType() 12222 << Input->getSourceRange(); 12223 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12224 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12225 return ExprError(); 12226 12227 case OR_Deleted: 12228 Diag(OpLoc, diag::err_ovl_deleted_oper) 12229 << Best->Function->isDeleted() 12230 << UnaryOperator::getOpcodeStr(Opc) 12231 << getDeletedOrUnavailableSuffix(Best->Function) 12232 << Input->getSourceRange(); 12233 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12234 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12235 return ExprError(); 12236 } 12237 12238 // Either we found no viable overloaded operator or we matched a 12239 // built-in operator. In either case, fall through to trying to 12240 // build a built-in operation. 12241 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12242 } 12243 12244 /// Create a binary operation that may resolve to an overloaded 12245 /// operator. 12246 /// 12247 /// \param OpLoc The location of the operator itself (e.g., '+'). 12248 /// 12249 /// \param Opc The BinaryOperatorKind that describes this operator. 12250 /// 12251 /// \param Fns The set of non-member functions that will be 12252 /// considered by overload resolution. The caller needs to build this 12253 /// set based on the context using, e.g., 12254 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12255 /// set should not contain any member functions; those will be added 12256 /// by CreateOverloadedBinOp(). 12257 /// 12258 /// \param LHS Left-hand argument. 12259 /// \param RHS Right-hand argument. 12260 ExprResult 12261 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12262 BinaryOperatorKind Opc, 12263 const UnresolvedSetImpl &Fns, 12264 Expr *LHS, Expr *RHS, bool PerformADL) { 12265 Expr *Args[2] = { LHS, RHS }; 12266 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12267 12268 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12269 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12270 12271 // If either side is type-dependent, create an appropriate dependent 12272 // expression. 12273 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12274 if (Fns.empty()) { 12275 // If there are no functions to store, just build a dependent 12276 // BinaryOperator or CompoundAssignment. 12277 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12278 return new (Context) BinaryOperator( 12279 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12280 OpLoc, FPFeatures); 12281 12282 return new (Context) CompoundAssignOperator( 12283 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12284 Context.DependentTy, Context.DependentTy, OpLoc, 12285 FPFeatures); 12286 } 12287 12288 // FIXME: save results of ADL from here? 12289 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12290 // TODO: provide better source location info in DNLoc component. 12291 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12292 UnresolvedLookupExpr *Fn 12293 = UnresolvedLookupExpr::Create(Context, NamingClass, 12294 NestedNameSpecifierLoc(), OpNameInfo, 12295 /*ADL*/PerformADL, IsOverloaded(Fns), 12296 Fns.begin(), Fns.end()); 12297 return new (Context) 12298 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12299 VK_RValue, OpLoc, FPFeatures); 12300 } 12301 12302 // Always do placeholder-like conversions on the RHS. 12303 if (checkPlaceholderForOverload(*this, Args[1])) 12304 return ExprError(); 12305 12306 // Do placeholder-like conversion on the LHS; note that we should 12307 // not get here with a PseudoObject LHS. 12308 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12309 if (checkPlaceholderForOverload(*this, Args[0])) 12310 return ExprError(); 12311 12312 // If this is the assignment operator, we only perform overload resolution 12313 // if the left-hand side is a class or enumeration type. This is actually 12314 // a hack. The standard requires that we do overload resolution between the 12315 // various built-in candidates, but as DR507 points out, this can lead to 12316 // problems. So we do it this way, which pretty much follows what GCC does. 12317 // Note that we go the traditional code path for compound assignment forms. 12318 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12319 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12320 12321 // If this is the .* operator, which is not overloadable, just 12322 // create a built-in binary operator. 12323 if (Opc == BO_PtrMemD) 12324 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12325 12326 // Build an empty overload set. 12327 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12328 12329 // Add the candidates from the given function set. 12330 AddFunctionCandidates(Fns, Args, CandidateSet); 12331 12332 // Add operator candidates that are member functions. 12333 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12334 12335 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12336 // performed for an assignment operator (nor for operator[] nor operator->, 12337 // which don't get here). 12338 if (Opc != BO_Assign && PerformADL) 12339 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12340 /*ExplicitTemplateArgs*/ nullptr, 12341 CandidateSet); 12342 12343 // Add builtin operator candidates. 12344 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12345 12346 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12347 12348 // Perform overload resolution. 12349 OverloadCandidateSet::iterator Best; 12350 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12351 case OR_Success: { 12352 // We found a built-in operator or an overloaded operator. 12353 FunctionDecl *FnDecl = Best->Function; 12354 12355 if (FnDecl) { 12356 Expr *Base = nullptr; 12357 // We matched an overloaded operator. Build a call to that 12358 // operator. 12359 12360 // Convert the arguments. 12361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12362 // Best->Access is only meaningful for class members. 12363 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12364 12365 ExprResult Arg1 = 12366 PerformCopyInitialization( 12367 InitializedEntity::InitializeParameter(Context, 12368 FnDecl->getParamDecl(0)), 12369 SourceLocation(), Args[1]); 12370 if (Arg1.isInvalid()) 12371 return ExprError(); 12372 12373 ExprResult Arg0 = 12374 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12375 Best->FoundDecl, Method); 12376 if (Arg0.isInvalid()) 12377 return ExprError(); 12378 Base = Args[0] = Arg0.getAs<Expr>(); 12379 Args[1] = RHS = Arg1.getAs<Expr>(); 12380 } else { 12381 // Convert the arguments. 12382 ExprResult Arg0 = PerformCopyInitialization( 12383 InitializedEntity::InitializeParameter(Context, 12384 FnDecl->getParamDecl(0)), 12385 SourceLocation(), Args[0]); 12386 if (Arg0.isInvalid()) 12387 return ExprError(); 12388 12389 ExprResult Arg1 = 12390 PerformCopyInitialization( 12391 InitializedEntity::InitializeParameter(Context, 12392 FnDecl->getParamDecl(1)), 12393 SourceLocation(), Args[1]); 12394 if (Arg1.isInvalid()) 12395 return ExprError(); 12396 Args[0] = LHS = Arg0.getAs<Expr>(); 12397 Args[1] = RHS = Arg1.getAs<Expr>(); 12398 } 12399 12400 // Build the actual expression node. 12401 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12402 Best->FoundDecl, Base, 12403 HadMultipleCandidates, OpLoc); 12404 if (FnExpr.isInvalid()) 12405 return ExprError(); 12406 12407 // Determine the result type. 12408 QualType ResultTy = FnDecl->getReturnType(); 12409 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12410 ResultTy = ResultTy.getNonLValueExprType(Context); 12411 12412 CXXOperatorCallExpr *TheCall = 12413 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12414 Args, ResultTy, VK, OpLoc, 12415 FPFeatures); 12416 12417 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12418 FnDecl)) 12419 return ExprError(); 12420 12421 ArrayRef<const Expr *> ArgsArray(Args, 2); 12422 const Expr *ImplicitThis = nullptr; 12423 // Cut off the implicit 'this'. 12424 if (isa<CXXMethodDecl>(FnDecl)) { 12425 ImplicitThis = ArgsArray[0]; 12426 ArgsArray = ArgsArray.slice(1); 12427 } 12428 12429 // Check for a self move. 12430 if (Op == OO_Equal) 12431 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12432 12433 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12434 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12435 VariadicDoesNotApply); 12436 12437 return MaybeBindToTemporary(TheCall); 12438 } else { 12439 // We matched a built-in operator. Convert the arguments, then 12440 // break out so that we will build the appropriate built-in 12441 // operator node. 12442 ExprResult ArgsRes0 = 12443 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0], 12444 Best->Conversions[0], AA_Passing); 12445 if (ArgsRes0.isInvalid()) 12446 return ExprError(); 12447 Args[0] = ArgsRes0.get(); 12448 12449 ExprResult ArgsRes1 = 12450 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1], 12451 Best->Conversions[1], AA_Passing); 12452 if (ArgsRes1.isInvalid()) 12453 return ExprError(); 12454 Args[1] = ArgsRes1.get(); 12455 break; 12456 } 12457 } 12458 12459 case OR_No_Viable_Function: { 12460 // C++ [over.match.oper]p9: 12461 // If the operator is the operator , [...] and there are no 12462 // viable functions, then the operator is assumed to be the 12463 // built-in operator and interpreted according to clause 5. 12464 if (Opc == BO_Comma) 12465 break; 12466 12467 // For class as left operand for assignment or compound assignment 12468 // operator do not fall through to handling in built-in, but report that 12469 // no overloaded assignment operator found 12470 ExprResult Result = ExprError(); 12471 if (Args[0]->getType()->isRecordType() && 12472 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12473 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12474 << BinaryOperator::getOpcodeStr(Opc) 12475 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12476 if (Args[0]->getType()->isIncompleteType()) { 12477 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12478 << Args[0]->getType() 12479 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12480 } 12481 } else { 12482 // This is an erroneous use of an operator which can be overloaded by 12483 // a non-member function. Check for non-member operators which were 12484 // defined too late to be candidates. 12485 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12486 // FIXME: Recover by calling the found function. 12487 return ExprError(); 12488 12489 // No viable function; try to create a built-in operation, which will 12490 // produce an error. Then, show the non-viable candidates. 12491 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12492 } 12493 assert(Result.isInvalid() && 12494 "C++ binary operator overloading is missing candidates!"); 12495 if (Result.isInvalid()) 12496 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12497 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12498 return Result; 12499 } 12500 12501 case OR_Ambiguous: 12502 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12503 << BinaryOperator::getOpcodeStr(Opc) 12504 << Args[0]->getType() << Args[1]->getType() 12505 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12506 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12507 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12508 return ExprError(); 12509 12510 case OR_Deleted: 12511 if (isImplicitlyDeleted(Best->Function)) { 12512 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12513 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12514 << Context.getRecordType(Method->getParent()) 12515 << getSpecialMember(Method); 12516 12517 // The user probably meant to call this special member. Just 12518 // explain why it's deleted. 12519 NoteDeletedFunction(Method); 12520 return ExprError(); 12521 } else { 12522 Diag(OpLoc, diag::err_ovl_deleted_oper) 12523 << Best->Function->isDeleted() 12524 << BinaryOperator::getOpcodeStr(Opc) 12525 << getDeletedOrUnavailableSuffix(Best->Function) 12526 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12527 } 12528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12529 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12530 return ExprError(); 12531 } 12532 12533 // We matched a built-in operator; build it. 12534 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12535 } 12536 12537 ExprResult 12538 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12539 SourceLocation RLoc, 12540 Expr *Base, Expr *Idx) { 12541 Expr *Args[2] = { Base, Idx }; 12542 DeclarationName OpName = 12543 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12544 12545 // If either side is type-dependent, create an appropriate dependent 12546 // expression. 12547 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12548 12549 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12550 // CHECKME: no 'operator' keyword? 12551 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12552 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12553 UnresolvedLookupExpr *Fn 12554 = UnresolvedLookupExpr::Create(Context, NamingClass, 12555 NestedNameSpecifierLoc(), OpNameInfo, 12556 /*ADL*/ true, /*Overloaded*/ false, 12557 UnresolvedSetIterator(), 12558 UnresolvedSetIterator()); 12559 // Can't add any actual overloads yet 12560 12561 return new (Context) 12562 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12563 Context.DependentTy, VK_RValue, RLoc, FPOptions()); 12564 } 12565 12566 // Handle placeholders on both operands. 12567 if (checkPlaceholderForOverload(*this, Args[0])) 12568 return ExprError(); 12569 if (checkPlaceholderForOverload(*this, Args[1])) 12570 return ExprError(); 12571 12572 // Build an empty overload set. 12573 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12574 12575 // Subscript can only be overloaded as a member function. 12576 12577 // Add operator candidates that are member functions. 12578 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12579 12580 // Add builtin operator candidates. 12581 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12582 12583 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12584 12585 // Perform overload resolution. 12586 OverloadCandidateSet::iterator Best; 12587 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12588 case OR_Success: { 12589 // We found a built-in operator or an overloaded operator. 12590 FunctionDecl *FnDecl = Best->Function; 12591 12592 if (FnDecl) { 12593 // We matched an overloaded operator. Build a call to that 12594 // operator. 12595 12596 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12597 12598 // Convert the arguments. 12599 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12600 ExprResult Arg0 = 12601 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12602 Best->FoundDecl, Method); 12603 if (Arg0.isInvalid()) 12604 return ExprError(); 12605 Args[0] = Arg0.get(); 12606 12607 // Convert the arguments. 12608 ExprResult InputInit 12609 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12610 Context, 12611 FnDecl->getParamDecl(0)), 12612 SourceLocation(), 12613 Args[1]); 12614 if (InputInit.isInvalid()) 12615 return ExprError(); 12616 12617 Args[1] = InputInit.getAs<Expr>(); 12618 12619 // Build the actual expression node. 12620 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12621 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12622 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12623 Best->FoundDecl, 12624 Base, 12625 HadMultipleCandidates, 12626 OpLocInfo.getLoc(), 12627 OpLocInfo.getInfo()); 12628 if (FnExpr.isInvalid()) 12629 return ExprError(); 12630 12631 // Determine the result type 12632 QualType ResultTy = FnDecl->getReturnType(); 12633 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12634 ResultTy = ResultTy.getNonLValueExprType(Context); 12635 12636 CXXOperatorCallExpr *TheCall = 12637 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12638 FnExpr.get(), Args, 12639 ResultTy, VK, RLoc, 12640 FPOptions()); 12641 12642 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12643 return ExprError(); 12644 12645 if (CheckFunctionCall(Method, TheCall, 12646 Method->getType()->castAs<FunctionProtoType>())) 12647 return ExprError(); 12648 12649 return MaybeBindToTemporary(TheCall); 12650 } else { 12651 // We matched a built-in operator. Convert the arguments, then 12652 // break out so that we will build the appropriate built-in 12653 // operator node. 12654 ExprResult ArgsRes0 = 12655 PerformImplicitConversion(Args[0], Best->BuiltinParamTypes[0], 12656 Best->Conversions[0], AA_Passing); 12657 if (ArgsRes0.isInvalid()) 12658 return ExprError(); 12659 Args[0] = ArgsRes0.get(); 12660 12661 ExprResult ArgsRes1 = 12662 PerformImplicitConversion(Args[1], Best->BuiltinParamTypes[1], 12663 Best->Conversions[1], AA_Passing); 12664 if (ArgsRes1.isInvalid()) 12665 return ExprError(); 12666 Args[1] = ArgsRes1.get(); 12667 12668 break; 12669 } 12670 } 12671 12672 case OR_No_Viable_Function: { 12673 if (CandidateSet.empty()) 12674 Diag(LLoc, diag::err_ovl_no_oper) 12675 << Args[0]->getType() << /*subscript*/ 0 12676 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12677 else 12678 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12679 << Args[0]->getType() 12680 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12681 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12682 "[]", LLoc); 12683 return ExprError(); 12684 } 12685 12686 case OR_Ambiguous: 12687 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12688 << "[]" 12689 << Args[0]->getType() << Args[1]->getType() 12690 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12691 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12692 "[]", LLoc); 12693 return ExprError(); 12694 12695 case OR_Deleted: 12696 Diag(LLoc, diag::err_ovl_deleted_oper) 12697 << Best->Function->isDeleted() << "[]" 12698 << getDeletedOrUnavailableSuffix(Best->Function) 12699 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12700 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12701 "[]", LLoc); 12702 return ExprError(); 12703 } 12704 12705 // We matched a built-in operator; build it. 12706 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12707 } 12708 12709 /// BuildCallToMemberFunction - Build a call to a member 12710 /// function. MemExpr is the expression that refers to the member 12711 /// function (and includes the object parameter), Args/NumArgs are the 12712 /// arguments to the function call (not including the object 12713 /// parameter). The caller needs to validate that the member 12714 /// expression refers to a non-static member function or an overloaded 12715 /// member function. 12716 ExprResult 12717 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12718 SourceLocation LParenLoc, 12719 MultiExprArg Args, 12720 SourceLocation RParenLoc) { 12721 assert(MemExprE->getType() == Context.BoundMemberTy || 12722 MemExprE->getType() == Context.OverloadTy); 12723 12724 // Dig out the member expression. This holds both the object 12725 // argument and the member function we're referring to. 12726 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12727 12728 // Determine whether this is a call to a pointer-to-member function. 12729 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12730 assert(op->getType() == Context.BoundMemberTy); 12731 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12732 12733 QualType fnType = 12734 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12735 12736 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12737 QualType resultType = proto->getCallResultType(Context); 12738 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12739 12740 // Check that the object type isn't more qualified than the 12741 // member function we're calling. 12742 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12743 12744 QualType objectType = op->getLHS()->getType(); 12745 if (op->getOpcode() == BO_PtrMemI) 12746 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12747 Qualifiers objectQuals = objectType.getQualifiers(); 12748 12749 Qualifiers difference = objectQuals - funcQuals; 12750 difference.removeObjCGCAttr(); 12751 difference.removeAddressSpace(); 12752 if (difference) { 12753 std::string qualsString = difference.getAsString(); 12754 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12755 << fnType.getUnqualifiedType() 12756 << qualsString 12757 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12758 } 12759 12760 CXXMemberCallExpr *call 12761 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12762 resultType, valueKind, RParenLoc); 12763 12764 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12765 call, nullptr)) 12766 return ExprError(); 12767 12768 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12769 return ExprError(); 12770 12771 if (CheckOtherCall(call, proto)) 12772 return ExprError(); 12773 12774 return MaybeBindToTemporary(call); 12775 } 12776 12777 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12778 return new (Context) 12779 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12780 12781 UnbridgedCastsSet UnbridgedCasts; 12782 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12783 return ExprError(); 12784 12785 MemberExpr *MemExpr; 12786 CXXMethodDecl *Method = nullptr; 12787 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12788 NestedNameSpecifier *Qualifier = nullptr; 12789 if (isa<MemberExpr>(NakedMemExpr)) { 12790 MemExpr = cast<MemberExpr>(NakedMemExpr); 12791 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12792 FoundDecl = MemExpr->getFoundDecl(); 12793 Qualifier = MemExpr->getQualifier(); 12794 UnbridgedCasts.restore(); 12795 } else { 12796 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12797 Qualifier = UnresExpr->getQualifier(); 12798 12799 QualType ObjectType = UnresExpr->getBaseType(); 12800 Expr::Classification ObjectClassification 12801 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12802 : UnresExpr->getBase()->Classify(Context); 12803 12804 // Add overload candidates 12805 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12806 OverloadCandidateSet::CSK_Normal); 12807 12808 // FIXME: avoid copy. 12809 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12810 if (UnresExpr->hasExplicitTemplateArgs()) { 12811 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12812 TemplateArgs = &TemplateArgsBuffer; 12813 } 12814 12815 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12816 E = UnresExpr->decls_end(); I != E; ++I) { 12817 12818 NamedDecl *Func = *I; 12819 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12820 if (isa<UsingShadowDecl>(Func)) 12821 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12822 12823 12824 // Microsoft supports direct constructor calls. 12825 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12826 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12827 Args, CandidateSet); 12828 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12829 // If explicit template arguments were provided, we can't call a 12830 // non-template member function. 12831 if (TemplateArgs) 12832 continue; 12833 12834 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12835 ObjectClassification, Args, CandidateSet, 12836 /*SuppressUserConversions=*/false); 12837 } else { 12838 AddMethodTemplateCandidate( 12839 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12840 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12841 /*SuppressUsedConversions=*/false); 12842 } 12843 } 12844 12845 DeclarationName DeclName = UnresExpr->getMemberName(); 12846 12847 UnbridgedCasts.restore(); 12848 12849 OverloadCandidateSet::iterator Best; 12850 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12851 Best)) { 12852 case OR_Success: 12853 Method = cast<CXXMethodDecl>(Best->Function); 12854 FoundDecl = Best->FoundDecl; 12855 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12856 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12857 return ExprError(); 12858 // If FoundDecl is different from Method (such as if one is a template 12859 // and the other a specialization), make sure DiagnoseUseOfDecl is 12860 // called on both. 12861 // FIXME: This would be more comprehensively addressed by modifying 12862 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12863 // being used. 12864 if (Method != FoundDecl.getDecl() && 12865 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12866 return ExprError(); 12867 break; 12868 12869 case OR_No_Viable_Function: 12870 Diag(UnresExpr->getMemberLoc(), 12871 diag::err_ovl_no_viable_member_function_in_call) 12872 << DeclName << MemExprE->getSourceRange(); 12873 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12874 // FIXME: Leaking incoming expressions! 12875 return ExprError(); 12876 12877 case OR_Ambiguous: 12878 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12879 << DeclName << MemExprE->getSourceRange(); 12880 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12881 // FIXME: Leaking incoming expressions! 12882 return ExprError(); 12883 12884 case OR_Deleted: 12885 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12886 << Best->Function->isDeleted() 12887 << DeclName 12888 << getDeletedOrUnavailableSuffix(Best->Function) 12889 << MemExprE->getSourceRange(); 12890 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12891 // FIXME: Leaking incoming expressions! 12892 return ExprError(); 12893 } 12894 12895 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12896 12897 // If overload resolution picked a static member, build a 12898 // non-member call based on that function. 12899 if (Method->isStatic()) { 12900 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12901 RParenLoc); 12902 } 12903 12904 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12905 } 12906 12907 QualType ResultType = Method->getReturnType(); 12908 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12909 ResultType = ResultType.getNonLValueExprType(Context); 12910 12911 assert(Method && "Member call to something that isn't a method?"); 12912 CXXMemberCallExpr *TheCall = 12913 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12914 ResultType, VK, RParenLoc); 12915 12916 // Check for a valid return type. 12917 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12918 TheCall, Method)) 12919 return ExprError(); 12920 12921 // Convert the object argument (for a non-static member function call). 12922 // We only need to do this if there was actually an overload; otherwise 12923 // it was done at lookup. 12924 if (!Method->isStatic()) { 12925 ExprResult ObjectArg = 12926 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12927 FoundDecl, Method); 12928 if (ObjectArg.isInvalid()) 12929 return ExprError(); 12930 MemExpr->setBase(ObjectArg.get()); 12931 } 12932 12933 // Convert the rest of the arguments 12934 const FunctionProtoType *Proto = 12935 Method->getType()->getAs<FunctionProtoType>(); 12936 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12937 RParenLoc)) 12938 return ExprError(); 12939 12940 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12941 12942 if (CheckFunctionCall(Method, TheCall, Proto)) 12943 return ExprError(); 12944 12945 // In the case the method to call was not selected by the overloading 12946 // resolution process, we still need to handle the enable_if attribute. Do 12947 // that here, so it will not hide previous -- and more relevant -- errors. 12948 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12949 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12950 Diag(MemE->getMemberLoc(), 12951 diag::err_ovl_no_viable_member_function_in_call) 12952 << Method << Method->getSourceRange(); 12953 Diag(Method->getLocation(), 12954 diag::note_ovl_candidate_disabled_by_function_cond_attr) 12955 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12956 return ExprError(); 12957 } 12958 } 12959 12960 if ((isa<CXXConstructorDecl>(CurContext) || 12961 isa<CXXDestructorDecl>(CurContext)) && 12962 TheCall->getMethodDecl()->isPure()) { 12963 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12964 12965 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12966 MemExpr->performsVirtualDispatch(getLangOpts())) { 12967 Diag(MemExpr->getLocStart(), 12968 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12969 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12970 << MD->getParent()->getDeclName(); 12971 12972 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12973 if (getLangOpts().AppleKext) 12974 Diag(MemExpr->getLocStart(), 12975 diag::note_pure_qualified_call_kext) 12976 << MD->getParent()->getDeclName() 12977 << MD->getDeclName(); 12978 } 12979 } 12980 12981 if (CXXDestructorDecl *DD = 12982 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12983 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12984 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12985 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12986 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12987 MemExpr->getMemberLoc()); 12988 } 12989 12990 return MaybeBindToTemporary(TheCall); 12991 } 12992 12993 /// BuildCallToObjectOfClassType - Build a call to an object of class 12994 /// type (C++ [over.call.object]), which can end up invoking an 12995 /// overloaded function call operator (@c operator()) or performing a 12996 /// user-defined conversion on the object argument. 12997 ExprResult 12998 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12999 SourceLocation LParenLoc, 13000 MultiExprArg Args, 13001 SourceLocation RParenLoc) { 13002 if (checkPlaceholderForOverload(*this, Obj)) 13003 return ExprError(); 13004 ExprResult Object = Obj; 13005 13006 UnbridgedCastsSet UnbridgedCasts; 13007 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13008 return ExprError(); 13009 13010 assert(Object.get()->getType()->isRecordType() && 13011 "Requires object type argument"); 13012 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13013 13014 // C++ [over.call.object]p1: 13015 // If the primary-expression E in the function call syntax 13016 // evaluates to a class object of type "cv T", then the set of 13017 // candidate functions includes at least the function call 13018 // operators of T. The function call operators of T are obtained by 13019 // ordinary lookup of the name operator() in the context of 13020 // (E).operator(). 13021 OverloadCandidateSet CandidateSet(LParenLoc, 13022 OverloadCandidateSet::CSK_Operator); 13023 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13024 13025 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13026 diag::err_incomplete_object_call, Object.get())) 13027 return true; 13028 13029 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13030 LookupQualifiedName(R, Record->getDecl()); 13031 R.suppressDiagnostics(); 13032 13033 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13034 Oper != OperEnd; ++Oper) { 13035 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13036 Object.get()->Classify(Context), Args, CandidateSet, 13037 /*SuppressUserConversions=*/false); 13038 } 13039 13040 // C++ [over.call.object]p2: 13041 // In addition, for each (non-explicit in C++0x) conversion function 13042 // declared in T of the form 13043 // 13044 // operator conversion-type-id () cv-qualifier; 13045 // 13046 // where cv-qualifier is the same cv-qualification as, or a 13047 // greater cv-qualification than, cv, and where conversion-type-id 13048 // denotes the type "pointer to function of (P1,...,Pn) returning 13049 // R", or the type "reference to pointer to function of 13050 // (P1,...,Pn) returning R", or the type "reference to function 13051 // of (P1,...,Pn) returning R", a surrogate call function [...] 13052 // is also considered as a candidate function. Similarly, 13053 // surrogate call functions are added to the set of candidate 13054 // functions for each conversion function declared in an 13055 // accessible base class provided the function is not hidden 13056 // within T by another intervening declaration. 13057 const auto &Conversions = 13058 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13059 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13060 NamedDecl *D = *I; 13061 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13062 if (isa<UsingShadowDecl>(D)) 13063 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13064 13065 // Skip over templated conversion functions; they aren't 13066 // surrogates. 13067 if (isa<FunctionTemplateDecl>(D)) 13068 continue; 13069 13070 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13071 if (!Conv->isExplicit()) { 13072 // Strip the reference type (if any) and then the pointer type (if 13073 // any) to get down to what might be a function type. 13074 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13075 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13076 ConvType = ConvPtrType->getPointeeType(); 13077 13078 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13079 { 13080 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13081 Object.get(), Args, CandidateSet); 13082 } 13083 } 13084 } 13085 13086 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13087 13088 // Perform overload resolution. 13089 OverloadCandidateSet::iterator Best; 13090 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 13091 Best)) { 13092 case OR_Success: 13093 // Overload resolution succeeded; we'll build the appropriate call 13094 // below. 13095 break; 13096 13097 case OR_No_Viable_Function: 13098 if (CandidateSet.empty()) 13099 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 13100 << Object.get()->getType() << /*call*/ 1 13101 << Object.get()->getSourceRange(); 13102 else 13103 Diag(Object.get()->getLocStart(), 13104 diag::err_ovl_no_viable_object_call) 13105 << Object.get()->getType() << Object.get()->getSourceRange(); 13106 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13107 break; 13108 13109 case OR_Ambiguous: 13110 Diag(Object.get()->getLocStart(), 13111 diag::err_ovl_ambiguous_object_call) 13112 << Object.get()->getType() << Object.get()->getSourceRange(); 13113 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13114 break; 13115 13116 case OR_Deleted: 13117 Diag(Object.get()->getLocStart(), 13118 diag::err_ovl_deleted_object_call) 13119 << Best->Function->isDeleted() 13120 << Object.get()->getType() 13121 << getDeletedOrUnavailableSuffix(Best->Function) 13122 << Object.get()->getSourceRange(); 13123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13124 break; 13125 } 13126 13127 if (Best == CandidateSet.end()) 13128 return true; 13129 13130 UnbridgedCasts.restore(); 13131 13132 if (Best->Function == nullptr) { 13133 // Since there is no function declaration, this is one of the 13134 // surrogate candidates. Dig out the conversion function. 13135 CXXConversionDecl *Conv 13136 = cast<CXXConversionDecl>( 13137 Best->Conversions[0].UserDefined.ConversionFunction); 13138 13139 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13140 Best->FoundDecl); 13141 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13142 return ExprError(); 13143 assert(Conv == Best->FoundDecl.getDecl() && 13144 "Found Decl & conversion-to-functionptr should be same, right?!"); 13145 // We selected one of the surrogate functions that converts the 13146 // object parameter to a function pointer. Perform the conversion 13147 // on the object argument, then let ActOnCallExpr finish the job. 13148 13149 // Create an implicit member expr to refer to the conversion operator. 13150 // and then call it. 13151 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13152 Conv, HadMultipleCandidates); 13153 if (Call.isInvalid()) 13154 return ExprError(); 13155 // Record usage of conversion in an implicit cast. 13156 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13157 CK_UserDefinedConversion, Call.get(), 13158 nullptr, VK_RValue); 13159 13160 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13161 } 13162 13163 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13164 13165 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13166 // that calls this method, using Object for the implicit object 13167 // parameter and passing along the remaining arguments. 13168 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13169 13170 // An error diagnostic has already been printed when parsing the declaration. 13171 if (Method->isInvalidDecl()) 13172 return ExprError(); 13173 13174 const FunctionProtoType *Proto = 13175 Method->getType()->getAs<FunctionProtoType>(); 13176 13177 unsigned NumParams = Proto->getNumParams(); 13178 13179 DeclarationNameInfo OpLocInfo( 13180 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13181 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13182 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13183 Obj, HadMultipleCandidates, 13184 OpLocInfo.getLoc(), 13185 OpLocInfo.getInfo()); 13186 if (NewFn.isInvalid()) 13187 return true; 13188 13189 // Build the full argument list for the method call (the implicit object 13190 // parameter is placed at the beginning of the list). 13191 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13192 MethodArgs[0] = Object.get(); 13193 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13194 13195 // Once we've built TheCall, all of the expressions are properly 13196 // owned. 13197 QualType ResultTy = Method->getReturnType(); 13198 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13199 ResultTy = ResultTy.getNonLValueExprType(Context); 13200 13201 CXXOperatorCallExpr *TheCall = new (Context) 13202 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13203 VK, RParenLoc, FPOptions()); 13204 13205 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13206 return true; 13207 13208 // We may have default arguments. If so, we need to allocate more 13209 // slots in the call for them. 13210 if (Args.size() < NumParams) 13211 TheCall->setNumArgs(Context, NumParams + 1); 13212 13213 bool IsError = false; 13214 13215 // Initialize the implicit object parameter. 13216 ExprResult ObjRes = 13217 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13218 Best->FoundDecl, Method); 13219 if (ObjRes.isInvalid()) 13220 IsError = true; 13221 else 13222 Object = ObjRes; 13223 TheCall->setArg(0, Object.get()); 13224 13225 // Check the argument types. 13226 for (unsigned i = 0; i != NumParams; i++) { 13227 Expr *Arg; 13228 if (i < Args.size()) { 13229 Arg = Args[i]; 13230 13231 // Pass the argument. 13232 13233 ExprResult InputInit 13234 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13235 Context, 13236 Method->getParamDecl(i)), 13237 SourceLocation(), Arg); 13238 13239 IsError |= InputInit.isInvalid(); 13240 Arg = InputInit.getAs<Expr>(); 13241 } else { 13242 ExprResult DefArg 13243 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13244 if (DefArg.isInvalid()) { 13245 IsError = true; 13246 break; 13247 } 13248 13249 Arg = DefArg.getAs<Expr>(); 13250 } 13251 13252 TheCall->setArg(i + 1, Arg); 13253 } 13254 13255 // If this is a variadic call, handle args passed through "...". 13256 if (Proto->isVariadic()) { 13257 // Promote the arguments (C99 6.5.2.2p7). 13258 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13259 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13260 nullptr); 13261 IsError |= Arg.isInvalid(); 13262 TheCall->setArg(i + 1, Arg.get()); 13263 } 13264 } 13265 13266 if (IsError) return true; 13267 13268 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13269 13270 if (CheckFunctionCall(Method, TheCall, Proto)) 13271 return true; 13272 13273 return MaybeBindToTemporary(TheCall); 13274 } 13275 13276 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13277 /// (if one exists), where @c Base is an expression of class type and 13278 /// @c Member is the name of the member we're trying to find. 13279 ExprResult 13280 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13281 bool *NoArrowOperatorFound) { 13282 assert(Base->getType()->isRecordType() && 13283 "left-hand side must have class type"); 13284 13285 if (checkPlaceholderForOverload(*this, Base)) 13286 return ExprError(); 13287 13288 SourceLocation Loc = Base->getExprLoc(); 13289 13290 // C++ [over.ref]p1: 13291 // 13292 // [...] An expression x->m is interpreted as (x.operator->())->m 13293 // for a class object x of type T if T::operator->() exists and if 13294 // the operator is selected as the best match function by the 13295 // overload resolution mechanism (13.3). 13296 DeclarationName OpName = 13297 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13298 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13299 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13300 13301 if (RequireCompleteType(Loc, Base->getType(), 13302 diag::err_typecheck_incomplete_tag, Base)) 13303 return ExprError(); 13304 13305 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13306 LookupQualifiedName(R, BaseRecord->getDecl()); 13307 R.suppressDiagnostics(); 13308 13309 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13310 Oper != OperEnd; ++Oper) { 13311 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13312 None, CandidateSet, /*SuppressUserConversions=*/false); 13313 } 13314 13315 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13316 13317 // Perform overload resolution. 13318 OverloadCandidateSet::iterator Best; 13319 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13320 case OR_Success: 13321 // Overload resolution succeeded; we'll build the call below. 13322 break; 13323 13324 case OR_No_Viable_Function: 13325 if (CandidateSet.empty()) { 13326 QualType BaseType = Base->getType(); 13327 if (NoArrowOperatorFound) { 13328 // Report this specific error to the caller instead of emitting a 13329 // diagnostic, as requested. 13330 *NoArrowOperatorFound = true; 13331 return ExprError(); 13332 } 13333 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13334 << BaseType << Base->getSourceRange(); 13335 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13336 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13337 << FixItHint::CreateReplacement(OpLoc, "."); 13338 } 13339 } else 13340 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13341 << "operator->" << Base->getSourceRange(); 13342 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13343 return ExprError(); 13344 13345 case OR_Ambiguous: 13346 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13347 << "->" << Base->getType() << Base->getSourceRange(); 13348 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13349 return ExprError(); 13350 13351 case OR_Deleted: 13352 Diag(OpLoc, diag::err_ovl_deleted_oper) 13353 << Best->Function->isDeleted() 13354 << "->" 13355 << getDeletedOrUnavailableSuffix(Best->Function) 13356 << Base->getSourceRange(); 13357 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13358 return ExprError(); 13359 } 13360 13361 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13362 13363 // Convert the object parameter. 13364 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13365 ExprResult BaseResult = 13366 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13367 Best->FoundDecl, Method); 13368 if (BaseResult.isInvalid()) 13369 return ExprError(); 13370 Base = BaseResult.get(); 13371 13372 // Build the operator call. 13373 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13374 Base, HadMultipleCandidates, OpLoc); 13375 if (FnExpr.isInvalid()) 13376 return ExprError(); 13377 13378 QualType ResultTy = Method->getReturnType(); 13379 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13380 ResultTy = ResultTy.getNonLValueExprType(Context); 13381 CXXOperatorCallExpr *TheCall = 13382 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13383 Base, ResultTy, VK, OpLoc, FPOptions()); 13384 13385 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13386 return ExprError(); 13387 13388 if (CheckFunctionCall(Method, TheCall, 13389 Method->getType()->castAs<FunctionProtoType>())) 13390 return ExprError(); 13391 13392 return MaybeBindToTemporary(TheCall); 13393 } 13394 13395 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13396 /// a literal operator described by the provided lookup results. 13397 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13398 DeclarationNameInfo &SuffixInfo, 13399 ArrayRef<Expr*> Args, 13400 SourceLocation LitEndLoc, 13401 TemplateArgumentListInfo *TemplateArgs) { 13402 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13403 13404 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13405 OverloadCandidateSet::CSK_Normal); 13406 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13407 /*SuppressUserConversions=*/true); 13408 13409 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13410 13411 // Perform overload resolution. This will usually be trivial, but might need 13412 // to perform substitutions for a literal operator template. 13413 OverloadCandidateSet::iterator Best; 13414 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13415 case OR_Success: 13416 case OR_Deleted: 13417 break; 13418 13419 case OR_No_Viable_Function: 13420 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13421 << R.getLookupName(); 13422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13423 return ExprError(); 13424 13425 case OR_Ambiguous: 13426 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13427 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13428 return ExprError(); 13429 } 13430 13431 FunctionDecl *FD = Best->Function; 13432 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13433 nullptr, HadMultipleCandidates, 13434 SuffixInfo.getLoc(), 13435 SuffixInfo.getInfo()); 13436 if (Fn.isInvalid()) 13437 return true; 13438 13439 // Check the argument types. This should almost always be a no-op, except 13440 // that array-to-pointer decay is applied to string literals. 13441 Expr *ConvArgs[2]; 13442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13443 ExprResult InputInit = PerformCopyInitialization( 13444 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13445 SourceLocation(), Args[ArgIdx]); 13446 if (InputInit.isInvalid()) 13447 return true; 13448 ConvArgs[ArgIdx] = InputInit.get(); 13449 } 13450 13451 QualType ResultTy = FD->getReturnType(); 13452 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13453 ResultTy = ResultTy.getNonLValueExprType(Context); 13454 13455 UserDefinedLiteral *UDL = 13456 new (Context) UserDefinedLiteral(Context, Fn.get(), 13457 llvm::makeArrayRef(ConvArgs, Args.size()), 13458 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13459 13460 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13461 return ExprError(); 13462 13463 if (CheckFunctionCall(FD, UDL, nullptr)) 13464 return ExprError(); 13465 13466 return MaybeBindToTemporary(UDL); 13467 } 13468 13469 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13470 /// given LookupResult is non-empty, it is assumed to describe a member which 13471 /// will be invoked. Otherwise, the function will be found via argument 13472 /// dependent lookup. 13473 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13474 /// otherwise CallExpr is set to ExprError() and some non-success value 13475 /// is returned. 13476 Sema::ForRangeStatus 13477 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13478 SourceLocation RangeLoc, 13479 const DeclarationNameInfo &NameInfo, 13480 LookupResult &MemberLookup, 13481 OverloadCandidateSet *CandidateSet, 13482 Expr *Range, ExprResult *CallExpr) { 13483 Scope *S = nullptr; 13484 13485 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13486 if (!MemberLookup.empty()) { 13487 ExprResult MemberRef = 13488 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13489 /*IsPtr=*/false, CXXScopeSpec(), 13490 /*TemplateKWLoc=*/SourceLocation(), 13491 /*FirstQualifierInScope=*/nullptr, 13492 MemberLookup, 13493 /*TemplateArgs=*/nullptr, S); 13494 if (MemberRef.isInvalid()) { 13495 *CallExpr = ExprError(); 13496 return FRS_DiagnosticIssued; 13497 } 13498 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13499 if (CallExpr->isInvalid()) { 13500 *CallExpr = ExprError(); 13501 return FRS_DiagnosticIssued; 13502 } 13503 } else { 13504 UnresolvedSet<0> FoundNames; 13505 UnresolvedLookupExpr *Fn = 13506 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13507 NestedNameSpecifierLoc(), NameInfo, 13508 /*NeedsADL=*/true, /*Overloaded=*/false, 13509 FoundNames.begin(), FoundNames.end()); 13510 13511 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13512 CandidateSet, CallExpr); 13513 if (CandidateSet->empty() || CandidateSetError) { 13514 *CallExpr = ExprError(); 13515 return FRS_NoViableFunction; 13516 } 13517 OverloadCandidateSet::iterator Best; 13518 OverloadingResult OverloadResult = 13519 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13520 13521 if (OverloadResult == OR_No_Viable_Function) { 13522 *CallExpr = ExprError(); 13523 return FRS_NoViableFunction; 13524 } 13525 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13526 Loc, nullptr, CandidateSet, &Best, 13527 OverloadResult, 13528 /*AllowTypoCorrection=*/false); 13529 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13530 *CallExpr = ExprError(); 13531 return FRS_DiagnosticIssued; 13532 } 13533 } 13534 return FRS_Success; 13535 } 13536 13537 13538 /// FixOverloadedFunctionReference - E is an expression that refers to 13539 /// a C++ overloaded function (possibly with some parentheses and 13540 /// perhaps a '&' around it). We have resolved the overloaded function 13541 /// to the function declaration Fn, so patch up the expression E to 13542 /// refer (possibly indirectly) to Fn. Returns the new expr. 13543 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13544 FunctionDecl *Fn) { 13545 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13546 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13547 Found, Fn); 13548 if (SubExpr == PE->getSubExpr()) 13549 return PE; 13550 13551 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13552 } 13553 13554 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13555 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13556 Found, Fn); 13557 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13558 SubExpr->getType()) && 13559 "Implicit cast type cannot be determined from overload"); 13560 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13561 if (SubExpr == ICE->getSubExpr()) 13562 return ICE; 13563 13564 return ImplicitCastExpr::Create(Context, ICE->getType(), 13565 ICE->getCastKind(), 13566 SubExpr, nullptr, 13567 ICE->getValueKind()); 13568 } 13569 13570 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13571 if (!GSE->isResultDependent()) { 13572 Expr *SubExpr = 13573 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13574 if (SubExpr == GSE->getResultExpr()) 13575 return GSE; 13576 13577 // Replace the resulting type information before rebuilding the generic 13578 // selection expression. 13579 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13580 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13581 unsigned ResultIdx = GSE->getResultIndex(); 13582 AssocExprs[ResultIdx] = SubExpr; 13583 13584 return new (Context) GenericSelectionExpr( 13585 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13586 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13587 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13588 ResultIdx); 13589 } 13590 // Rather than fall through to the unreachable, return the original generic 13591 // selection expression. 13592 return GSE; 13593 } 13594 13595 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13596 assert(UnOp->getOpcode() == UO_AddrOf && 13597 "Can only take the address of an overloaded function"); 13598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13599 if (Method->isStatic()) { 13600 // Do nothing: static member functions aren't any different 13601 // from non-member functions. 13602 } else { 13603 // Fix the subexpression, which really has to be an 13604 // UnresolvedLookupExpr holding an overloaded member function 13605 // or template. 13606 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13607 Found, Fn); 13608 if (SubExpr == UnOp->getSubExpr()) 13609 return UnOp; 13610 13611 assert(isa<DeclRefExpr>(SubExpr) 13612 && "fixed to something other than a decl ref"); 13613 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13614 && "fixed to a member ref with no nested name qualifier"); 13615 13616 // We have taken the address of a pointer to member 13617 // function. Perform the computation here so that we get the 13618 // appropriate pointer to member type. 13619 QualType ClassType 13620 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13621 QualType MemPtrType 13622 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13623 // Under the MS ABI, lock down the inheritance model now. 13624 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13625 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13626 13627 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13628 VK_RValue, OK_Ordinary, 13629 UnOp->getOperatorLoc(), false); 13630 } 13631 } 13632 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13633 Found, Fn); 13634 if (SubExpr == UnOp->getSubExpr()) 13635 return UnOp; 13636 13637 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13638 Context.getPointerType(SubExpr->getType()), 13639 VK_RValue, OK_Ordinary, 13640 UnOp->getOperatorLoc(), false); 13641 } 13642 13643 // C++ [except.spec]p17: 13644 // An exception-specification is considered to be needed when: 13645 // - in an expression the function is the unique lookup result or the 13646 // selected member of a set of overloaded functions 13647 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13648 ResolveExceptionSpec(E->getExprLoc(), FPT); 13649 13650 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13651 // FIXME: avoid copy. 13652 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13653 if (ULE->hasExplicitTemplateArgs()) { 13654 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13655 TemplateArgs = &TemplateArgsBuffer; 13656 } 13657 13658 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13659 ULE->getQualifierLoc(), 13660 ULE->getTemplateKeywordLoc(), 13661 Fn, 13662 /*enclosing*/ false, // FIXME? 13663 ULE->getNameLoc(), 13664 Fn->getType(), 13665 VK_LValue, 13666 Found.getDecl(), 13667 TemplateArgs); 13668 MarkDeclRefReferenced(DRE); 13669 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13670 return DRE; 13671 } 13672 13673 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13674 // FIXME: avoid copy. 13675 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13676 if (MemExpr->hasExplicitTemplateArgs()) { 13677 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13678 TemplateArgs = &TemplateArgsBuffer; 13679 } 13680 13681 Expr *Base; 13682 13683 // If we're filling in a static method where we used to have an 13684 // implicit member access, rewrite to a simple decl ref. 13685 if (MemExpr->isImplicitAccess()) { 13686 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13687 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13688 MemExpr->getQualifierLoc(), 13689 MemExpr->getTemplateKeywordLoc(), 13690 Fn, 13691 /*enclosing*/ false, 13692 MemExpr->getMemberLoc(), 13693 Fn->getType(), 13694 VK_LValue, 13695 Found.getDecl(), 13696 TemplateArgs); 13697 MarkDeclRefReferenced(DRE); 13698 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13699 return DRE; 13700 } else { 13701 SourceLocation Loc = MemExpr->getMemberLoc(); 13702 if (MemExpr->getQualifier()) 13703 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13704 CheckCXXThisCapture(Loc); 13705 Base = new (Context) CXXThisExpr(Loc, 13706 MemExpr->getBaseType(), 13707 /*isImplicit=*/true); 13708 } 13709 } else 13710 Base = MemExpr->getBase(); 13711 13712 ExprValueKind valueKind; 13713 QualType type; 13714 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13715 valueKind = VK_LValue; 13716 type = Fn->getType(); 13717 } else { 13718 valueKind = VK_RValue; 13719 type = Context.BoundMemberTy; 13720 } 13721 13722 MemberExpr *ME = MemberExpr::Create( 13723 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13724 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13725 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13726 OK_Ordinary); 13727 ME->setHadMultipleCandidates(true); 13728 MarkMemberReferenced(ME); 13729 return ME; 13730 } 13731 13732 llvm_unreachable("Invalid reference to overloaded function"); 13733 } 13734 13735 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13736 DeclAccessPair Found, 13737 FunctionDecl *Fn) { 13738 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13739 } 13740