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_IncompletePack: 633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 634 case Sema::TDK_Inconsistent: 635 case Sema::TDK_Underqualified: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 638 Saved->Param = Info.Param; 639 Saved->FirstArg = Info.FirstArg; 640 Saved->SecondArg = Info.SecondArg; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_SubstitutionFailure: 646 Result.Data = Info.take(); 647 if (Info.hasSFINAEDiagnostic()) { 648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 649 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 650 Info.takeSFINAEDiagnostic(*Diag); 651 Result.HasDiagnostic = true; 652 } 653 break; 654 655 case Sema::TDK_Success: 656 case Sema::TDK_NonDependentConversionFailure: 657 llvm_unreachable("not a deduction failure"); 658 } 659 660 return Result; 661 } 662 663 void DeductionFailureInfo::Destroy() { 664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 665 case Sema::TDK_Success: 666 case Sema::TDK_Invalid: 667 case Sema::TDK_InstantiationDepth: 668 case Sema::TDK_Incomplete: 669 case Sema::TDK_TooManyArguments: 670 case Sema::TDK_TooFewArguments: 671 case Sema::TDK_InvalidExplicitArguments: 672 case Sema::TDK_CUDATargetMismatch: 673 case Sema::TDK_NonDependentConversionFailure: 674 break; 675 676 case Sema::TDK_IncompletePack: 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 case Sema::TDK_DeducedMismatch: 680 case Sema::TDK_DeducedMismatchNested: 681 case Sema::TDK_NonDeducedMismatch: 682 // FIXME: Destroy the data? 683 Data = nullptr; 684 break; 685 686 case Sema::TDK_SubstitutionFailure: 687 // FIXME: Destroy the template argument list? 688 Data = nullptr; 689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 690 Diag->~PartialDiagnosticAt(); 691 HasDiagnostic = false; 692 } 693 break; 694 695 // Unhandled 696 case Sema::TDK_MiscellaneousDeductionFailure: 697 break; 698 } 699 } 700 701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 702 if (HasDiagnostic) 703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 704 return nullptr; 705 } 706 707 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 709 case Sema::TDK_Success: 710 case Sema::TDK_Invalid: 711 case Sema::TDK_InstantiationDepth: 712 case Sema::TDK_TooManyArguments: 713 case Sema::TDK_TooFewArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_DeducedMismatch: 716 case Sema::TDK_DeducedMismatchNested: 717 case Sema::TDK_NonDeducedMismatch: 718 case Sema::TDK_CUDATargetMismatch: 719 case Sema::TDK_NonDependentConversionFailure: 720 return TemplateParameter(); 721 722 case Sema::TDK_Incomplete: 723 case Sema::TDK_InvalidExplicitArguments: 724 return TemplateParameter::getFromOpaqueValue(Data); 725 726 case Sema::TDK_IncompletePack: 727 case Sema::TDK_Inconsistent: 728 case Sema::TDK_Underqualified: 729 return static_cast<DFIParamWithArguments*>(Data)->Param; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 736 return TemplateParameter(); 737 } 738 739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 741 case Sema::TDK_Success: 742 case Sema::TDK_Invalid: 743 case Sema::TDK_InstantiationDepth: 744 case Sema::TDK_TooManyArguments: 745 case Sema::TDK_TooFewArguments: 746 case Sema::TDK_Incomplete: 747 case Sema::TDK_IncompletePack: 748 case Sema::TDK_InvalidExplicitArguments: 749 case Sema::TDK_Inconsistent: 750 case Sema::TDK_Underqualified: 751 case Sema::TDK_NonDeducedMismatch: 752 case Sema::TDK_CUDATargetMismatch: 753 case Sema::TDK_NonDependentConversionFailure: 754 return nullptr; 755 756 case Sema::TDK_DeducedMismatch: 757 case Sema::TDK_DeducedMismatchNested: 758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 759 760 case Sema::TDK_SubstitutionFailure: 761 return static_cast<TemplateArgumentList*>(Data); 762 763 // Unhandled 764 case Sema::TDK_MiscellaneousDeductionFailure: 765 break; 766 } 767 768 return nullptr; 769 } 770 771 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 773 case Sema::TDK_Success: 774 case Sema::TDK_Invalid: 775 case Sema::TDK_InstantiationDepth: 776 case Sema::TDK_Incomplete: 777 case Sema::TDK_TooManyArguments: 778 case Sema::TDK_TooFewArguments: 779 case Sema::TDK_InvalidExplicitArguments: 780 case Sema::TDK_SubstitutionFailure: 781 case Sema::TDK_CUDATargetMismatch: 782 case Sema::TDK_NonDependentConversionFailure: 783 return nullptr; 784 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_DeducedMismatch: 789 case Sema::TDK_DeducedMismatchNested: 790 case Sema::TDK_NonDeducedMismatch: 791 return &static_cast<DFIArguments*>(Data)->FirstArg; 792 793 // Unhandled 794 case Sema::TDK_MiscellaneousDeductionFailure: 795 break; 796 } 797 798 return nullptr; 799 } 800 801 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 803 case Sema::TDK_Success: 804 case Sema::TDK_Invalid: 805 case Sema::TDK_InstantiationDepth: 806 case Sema::TDK_Incomplete: 807 case Sema::TDK_IncompletePack: 808 case Sema::TDK_TooManyArguments: 809 case Sema::TDK_TooFewArguments: 810 case Sema::TDK_InvalidExplicitArguments: 811 case Sema::TDK_SubstitutionFailure: 812 case Sema::TDK_CUDATargetMismatch: 813 case Sema::TDK_NonDependentConversionFailure: 814 return nullptr; 815 816 case Sema::TDK_Inconsistent: 817 case Sema::TDK_Underqualified: 818 case Sema::TDK_DeducedMismatch: 819 case Sema::TDK_DeducedMismatchNested: 820 case Sema::TDK_NonDeducedMismatch: 821 return &static_cast<DFIArguments*>(Data)->SecondArg; 822 823 // Unhandled 824 case Sema::TDK_MiscellaneousDeductionFailure: 825 break; 826 } 827 828 return nullptr; 829 } 830 831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 836 837 default: 838 return llvm::None; 839 } 840 } 841 842 void OverloadCandidateSet::destroyCandidates() { 843 for (iterator i = begin(), e = end(); i != e; ++i) { 844 for (auto &C : i->Conversions) 845 C.~ImplicitConversionSequence(); 846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 847 i->DeductionFailure.Destroy(); 848 } 849 } 850 851 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 852 destroyCandidates(); 853 SlabAllocator.Reset(); 854 NumInlineBytesUsed = 0; 855 Candidates.clear(); 856 Functions.clear(); 857 Kind = CSK; 858 } 859 860 namespace { 861 class UnbridgedCastsSet { 862 struct Entry { 863 Expr **Addr; 864 Expr *Saved; 865 }; 866 SmallVector<Entry, 2> Entries; 867 868 public: 869 void save(Sema &S, Expr *&E) { 870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 871 Entry entry = { &E, E }; 872 Entries.push_back(entry); 873 E = S.stripARCUnbridgedCast(E); 874 } 875 876 void restore() { 877 for (SmallVectorImpl<Entry>::iterator 878 i = Entries.begin(), e = Entries.end(); i != e; ++i) 879 *i->Addr = i->Saved; 880 } 881 }; 882 } 883 884 /// checkPlaceholderForOverload - Do any interesting placeholder-like 885 /// preprocessing on the given expression. 886 /// 887 /// \param unbridgedCasts a collection to which to add unbridged casts; 888 /// without this, they will be immediately diagnosed as errors 889 /// 890 /// Return true on unrecoverable error. 891 static bool 892 checkPlaceholderForOverload(Sema &S, Expr *&E, 893 UnbridgedCastsSet *unbridgedCasts = nullptr) { 894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 895 // We can't handle overloaded expressions here because overload 896 // resolution might reasonably tweak them. 897 if (placeholder->getKind() == BuiltinType::Overload) return false; 898 899 // If the context potentially accepts unbridged ARC casts, strip 900 // the unbridged cast and add it to the collection for later restoration. 901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 902 unbridgedCasts) { 903 unbridgedCasts->save(S, E); 904 return false; 905 } 906 907 // Go ahead and check everything else. 908 ExprResult result = S.CheckPlaceholderExpr(E); 909 if (result.isInvalid()) 910 return true; 911 912 E = result.get(); 913 return false; 914 } 915 916 // Nothing to do. 917 return false; 918 } 919 920 /// checkArgPlaceholdersForOverload - Check a set of call operands for 921 /// placeholders. 922 static bool checkArgPlaceholdersForOverload(Sema &S, 923 MultiExprArg Args, 924 UnbridgedCastsSet &unbridged) { 925 for (unsigned i = 0, e = Args.size(); i != e; ++i) 926 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 927 return true; 928 929 return false; 930 } 931 932 /// Determine whether the given New declaration is an overload of the 933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 934 /// New and Old cannot be overloaded, e.g., if New has the same signature as 935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 936 /// functions (or function templates) at all. When it does return Ovl_Match or 937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 939 /// declaration. 940 /// 941 /// Example: Given the following input: 942 /// 943 /// void f(int, float); // #1 944 /// void f(int, int); // #2 945 /// int f(int, int); // #3 946 /// 947 /// When we process #1, there is no previous declaration of "f", so IsOverload 948 /// will not be used. 949 /// 950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 951 /// the parameter types, we see that #1 and #2 are overloaded (since they have 952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 953 /// unchanged. 954 /// 955 /// When we process #3, Old is an overload set containing #1 and #2. We compare 956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 958 /// functions are not part of the signature), IsOverload returns Ovl_Match and 959 /// MatchedDecl will be set to point to the FunctionDecl for #2. 960 /// 961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 962 /// by a using declaration. The rules for whether to hide shadow declarations 963 /// ignore some properties which otherwise figure into a function template's 964 /// signature. 965 Sema::OverloadKind 966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 967 NamedDecl *&Match, bool NewIsUsingDecl) { 968 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 969 I != E; ++I) { 970 NamedDecl *OldD = *I; 971 972 bool OldIsUsingDecl = false; 973 if (isa<UsingShadowDecl>(OldD)) { 974 OldIsUsingDecl = true; 975 976 // We can always introduce two using declarations into the same 977 // context, even if they have identical signatures. 978 if (NewIsUsingDecl) continue; 979 980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 981 } 982 983 // A using-declaration does not conflict with another declaration 984 // if one of them is hidden. 985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 986 continue; 987 988 // If either declaration was introduced by a using declaration, 989 // we'll need to use slightly different rules for matching. 990 // Essentially, these rules are the normal rules, except that 991 // function templates hide function templates with different 992 // return types or template parameter lists. 993 bool UseMemberUsingDeclRules = 994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 995 !New->getFriendObjectKind(); 996 997 if (FunctionDecl *OldF = OldD->getAsFunction()) { 998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 999 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1001 continue; 1002 } 1003 1004 if (!isa<FunctionTemplateDecl>(OldD) && 1005 !shouldLinkPossiblyHiddenDecl(*I, New)) 1006 continue; 1007 1008 Match = *I; 1009 return Ovl_Match; 1010 } 1011 1012 // Builtins that have custom typechecking or have a reference should 1013 // not be overloadable or redeclarable. 1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1015 Match = *I; 1016 return Ovl_NonFunction; 1017 } 1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1019 // We can overload with these, which can show up when doing 1020 // redeclaration checks for UsingDecls. 1021 assert(Old.getLookupKind() == LookupUsingDeclName); 1022 } else if (isa<TagDecl>(OldD)) { 1023 // We can always overload with tags by hiding them. 1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1025 // Optimistically assume that an unresolved using decl will 1026 // overload; if it doesn't, we'll have to diagnose during 1027 // template instantiation. 1028 // 1029 // Exception: if the scope is dependent and this is not a class 1030 // member, the using declaration can only introduce an enumerator. 1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1032 Match = *I; 1033 return Ovl_NonFunction; 1034 } 1035 } else { 1036 // (C++ 13p1): 1037 // Only function declarations can be overloaded; object and type 1038 // declarations cannot be overloaded. 1039 Match = *I; 1040 return Ovl_NonFunction; 1041 } 1042 } 1043 1044 return Ovl_Overload; 1045 } 1046 1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1049 // C++ [basic.start.main]p2: This function shall not be overloaded. 1050 if (New->isMain()) 1051 return false; 1052 1053 // MSVCRT user defined entry points cannot be overloaded. 1054 if (New->isMSVCRTEntryPoint()) 1055 return false; 1056 1057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1059 1060 // C++ [temp.fct]p2: 1061 // A function template can be overloaded with other function templates 1062 // and with normal (non-template) functions. 1063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1064 return true; 1065 1066 // Is the function New an overload of the function Old? 1067 QualType OldQType = Context.getCanonicalType(Old->getType()); 1068 QualType NewQType = Context.getCanonicalType(New->getType()); 1069 1070 // Compare the signatures (C++ 1.3.10) of the two functions to 1071 // determine whether they are overloads. If we find any mismatch 1072 // in the signature, they are overloads. 1073 1074 // If either of these functions is a K&R-style function (no 1075 // prototype), then we consider them to have matching signatures. 1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1077 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1078 return false; 1079 1080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1082 1083 // The signature of a function includes the types of its 1084 // parameters (C++ 1.3.10), which includes the presence or absence 1085 // of the ellipsis; see C++ DR 357). 1086 if (OldQType != NewQType && 1087 (OldType->getNumParams() != NewType->getNumParams() || 1088 OldType->isVariadic() != NewType->isVariadic() || 1089 !FunctionParamTypesAreEqual(OldType, NewType))) 1090 return true; 1091 1092 // C++ [temp.over.link]p4: 1093 // The signature of a function template consists of its function 1094 // signature, its return type and its template parameter list. The names 1095 // of the template parameters are significant only for establishing the 1096 // relationship between the template parameters and the rest of the 1097 // signature. 1098 // 1099 // We check the return type and template parameter lists for function 1100 // templates first; the remaining checks follow. 1101 // 1102 // However, we don't consider either of these when deciding whether 1103 // a member introduced by a shadow declaration is hidden. 1104 if (!UseMemberUsingDeclRules && NewTemplate && 1105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1106 OldTemplate->getTemplateParameters(), 1107 false, TPL_TemplateMatch) || 1108 OldType->getReturnType() != NewType->getReturnType())) 1109 return true; 1110 1111 // If the function is a class member, its signature includes the 1112 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1113 // 1114 // As part of this, also check whether one of the member functions 1115 // is static, in which case they are not overloads (C++ 1116 // 13.1p2). While not part of the definition of the signature, 1117 // this check is important to determine whether these functions 1118 // can be overloaded. 1119 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1120 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1121 if (OldMethod && NewMethod && 1122 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1123 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1124 if (!UseMemberUsingDeclRules && 1125 (OldMethod->getRefQualifier() == RQ_None || 1126 NewMethod->getRefQualifier() == RQ_None)) { 1127 // C++0x [over.load]p2: 1128 // - Member function declarations with the same name and the same 1129 // parameter-type-list as well as member function template 1130 // declarations with the same name, the same parameter-type-list, and 1131 // the same template parameter lists cannot be overloaded if any of 1132 // them, but not all, have a ref-qualifier (8.3.5). 1133 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1134 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1135 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1136 } 1137 return true; 1138 } 1139 1140 // We may not have applied the implicit const for a constexpr member 1141 // function yet (because we haven't yet resolved whether this is a static 1142 // or non-static member function). Add it now, on the assumption that this 1143 // is a redeclaration of OldMethod. 1144 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1145 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1146 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1147 !isa<CXXConstructorDecl>(NewMethod)) 1148 NewQuals |= Qualifiers::Const; 1149 1150 // We do not allow overloading based off of '__restrict'. 1151 OldQuals &= ~Qualifiers::Restrict; 1152 NewQuals &= ~Qualifiers::Restrict; 1153 if (OldQuals != NewQuals) 1154 return true; 1155 } 1156 1157 // Though pass_object_size is placed on parameters and takes an argument, we 1158 // consider it to be a function-level modifier for the sake of function 1159 // identity. Either the function has one or more parameters with 1160 // pass_object_size or it doesn't. 1161 if (functionHasPassObjectSizeParams(New) != 1162 functionHasPassObjectSizeParams(Old)) 1163 return true; 1164 1165 // enable_if attributes are an order-sensitive part of the signature. 1166 for (specific_attr_iterator<EnableIfAttr> 1167 NewI = New->specific_attr_begin<EnableIfAttr>(), 1168 NewE = New->specific_attr_end<EnableIfAttr>(), 1169 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1170 OldE = Old->specific_attr_end<EnableIfAttr>(); 1171 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1172 if (NewI == NewE || OldI == OldE) 1173 return true; 1174 llvm::FoldingSetNodeID NewID, OldID; 1175 NewI->getCond()->Profile(NewID, Context, true); 1176 OldI->getCond()->Profile(OldID, Context, true); 1177 if (NewID != OldID) 1178 return true; 1179 } 1180 1181 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1182 // Don't allow overloading of destructors. (In theory we could, but it 1183 // would be a giant change to clang.) 1184 if (isa<CXXDestructorDecl>(New)) 1185 return false; 1186 1187 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1188 OldTarget = IdentifyCUDATarget(Old); 1189 if (NewTarget == CFT_InvalidTarget) 1190 return false; 1191 1192 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1193 1194 // Allow overloading of functions with same signature and different CUDA 1195 // target attributes. 1196 return NewTarget != OldTarget; 1197 } 1198 1199 // The signatures match; this is not an overload. 1200 return false; 1201 } 1202 1203 /// Checks availability of the function depending on the current 1204 /// function context. Inside an unavailable function, unavailability is ignored. 1205 /// 1206 /// \returns true if \arg FD is unavailable and current context is inside 1207 /// an available function, false otherwise. 1208 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1209 if (!FD->isUnavailable()) 1210 return false; 1211 1212 // Walk up the context of the caller. 1213 Decl *C = cast<Decl>(CurContext); 1214 do { 1215 if (C->isUnavailable()) 1216 return false; 1217 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1218 return true; 1219 } 1220 1221 /// Tries a user-defined conversion from From to ToType. 1222 /// 1223 /// Produces an implicit conversion sequence for when a standard conversion 1224 /// is not an option. See TryImplicitConversion for more information. 1225 static ImplicitConversionSequence 1226 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1227 bool SuppressUserConversions, 1228 bool AllowExplicit, 1229 bool InOverloadResolution, 1230 bool CStyle, 1231 bool AllowObjCWritebackConversion, 1232 bool AllowObjCConversionOnExplicit) { 1233 ImplicitConversionSequence ICS; 1234 1235 if (SuppressUserConversions) { 1236 // We're not in the case above, so there is no conversion that 1237 // we can perform. 1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1239 return ICS; 1240 } 1241 1242 // Attempt user-defined conversion. 1243 OverloadCandidateSet Conversions(From->getExprLoc(), 1244 OverloadCandidateSet::CSK_Normal); 1245 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1246 Conversions, AllowExplicit, 1247 AllowObjCConversionOnExplicit)) { 1248 case OR_Success: 1249 case OR_Deleted: 1250 ICS.setUserDefined(); 1251 // C++ [over.ics.user]p4: 1252 // A conversion of an expression of class type to the same class 1253 // type is given Exact Match rank, and a conversion of an 1254 // expression of class type to a base class of that type is 1255 // given Conversion rank, in spite of the fact that a copy 1256 // constructor (i.e., a user-defined conversion function) is 1257 // called for those cases. 1258 if (CXXConstructorDecl *Constructor 1259 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1260 QualType FromCanon 1261 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1262 QualType ToCanon 1263 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1264 if (Constructor->isCopyConstructor() && 1265 (FromCanon == ToCanon || 1266 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1267 // Turn this into a "standard" conversion sequence, so that it 1268 // gets ranked with standard conversion sequences. 1269 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1270 ICS.setStandard(); 1271 ICS.Standard.setAsIdentityConversion(); 1272 ICS.Standard.setFromType(From->getType()); 1273 ICS.Standard.setAllToTypes(ToType); 1274 ICS.Standard.CopyConstructor = Constructor; 1275 ICS.Standard.FoundCopyConstructor = Found; 1276 if (ToCanon != FromCanon) 1277 ICS.Standard.Second = ICK_Derived_To_Base; 1278 } 1279 } 1280 break; 1281 1282 case OR_Ambiguous: 1283 ICS.setAmbiguous(); 1284 ICS.Ambiguous.setFromType(From->getType()); 1285 ICS.Ambiguous.setToType(ToType); 1286 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1287 Cand != Conversions.end(); ++Cand) 1288 if (Cand->Viable) 1289 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1290 break; 1291 1292 // Fall through. 1293 case OR_No_Viable_Function: 1294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1295 break; 1296 } 1297 1298 return ICS; 1299 } 1300 1301 /// TryImplicitConversion - Attempt to perform an implicit conversion 1302 /// from the given expression (Expr) to the given type (ToType). This 1303 /// function returns an implicit conversion sequence that can be used 1304 /// to perform the initialization. Given 1305 /// 1306 /// void f(float f); 1307 /// void g(int i) { f(i); } 1308 /// 1309 /// this routine would produce an implicit conversion sequence to 1310 /// describe the initialization of f from i, which will be a standard 1311 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1312 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1313 // 1314 /// Note that this routine only determines how the conversion can be 1315 /// performed; it does not actually perform the conversion. As such, 1316 /// it will not produce any diagnostics if no conversion is available, 1317 /// but will instead return an implicit conversion sequence of kind 1318 /// "BadConversion". 1319 /// 1320 /// If @p SuppressUserConversions, then user-defined conversions are 1321 /// not permitted. 1322 /// If @p AllowExplicit, then explicit user-defined conversions are 1323 /// permitted. 1324 /// 1325 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1326 /// writeback conversion, which allows __autoreleasing id* parameters to 1327 /// be initialized with __strong id* or __weak id* arguments. 1328 static ImplicitConversionSequence 1329 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1330 bool SuppressUserConversions, 1331 bool AllowExplicit, 1332 bool InOverloadResolution, 1333 bool CStyle, 1334 bool AllowObjCWritebackConversion, 1335 bool AllowObjCConversionOnExplicit) { 1336 ImplicitConversionSequence ICS; 1337 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1338 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1339 ICS.setStandard(); 1340 return ICS; 1341 } 1342 1343 if (!S.getLangOpts().CPlusPlus) { 1344 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1345 return ICS; 1346 } 1347 1348 // C++ [over.ics.user]p4: 1349 // A conversion of an expression of class type to the same class 1350 // type is given Exact Match rank, and a conversion of an 1351 // expression of class type to a base class of that type is 1352 // given Conversion rank, in spite of the fact that a copy/move 1353 // constructor (i.e., a user-defined conversion function) is 1354 // called for those cases. 1355 QualType FromType = From->getType(); 1356 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1357 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1358 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1359 ICS.setStandard(); 1360 ICS.Standard.setAsIdentityConversion(); 1361 ICS.Standard.setFromType(FromType); 1362 ICS.Standard.setAllToTypes(ToType); 1363 1364 // We don't actually check at this point whether there is a valid 1365 // copy/move constructor, since overloading just assumes that it 1366 // exists. When we actually perform initialization, we'll find the 1367 // appropriate constructor to copy the returned object, if needed. 1368 ICS.Standard.CopyConstructor = nullptr; 1369 1370 // Determine whether this is considered a derived-to-base conversion. 1371 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1372 ICS.Standard.Second = ICK_Derived_To_Base; 1373 1374 return ICS; 1375 } 1376 1377 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1378 AllowExplicit, InOverloadResolution, CStyle, 1379 AllowObjCWritebackConversion, 1380 AllowObjCConversionOnExplicit); 1381 } 1382 1383 ImplicitConversionSequence 1384 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1385 bool SuppressUserConversions, 1386 bool AllowExplicit, 1387 bool InOverloadResolution, 1388 bool CStyle, 1389 bool AllowObjCWritebackConversion) { 1390 return ::TryImplicitConversion(*this, From, ToType, 1391 SuppressUserConversions, AllowExplicit, 1392 InOverloadResolution, CStyle, 1393 AllowObjCWritebackConversion, 1394 /*AllowObjCConversionOnExplicit=*/false); 1395 } 1396 1397 /// PerformImplicitConversion - Perform an implicit conversion of the 1398 /// expression From to the type ToType. Returns the 1399 /// converted expression. Flavor is the kind of conversion we're 1400 /// performing, used in the error message. If @p AllowExplicit, 1401 /// explicit user-defined conversions are permitted. 1402 ExprResult 1403 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1404 AssignmentAction Action, bool AllowExplicit) { 1405 ImplicitConversionSequence ICS; 1406 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1407 } 1408 1409 ExprResult 1410 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1411 AssignmentAction Action, bool AllowExplicit, 1412 ImplicitConversionSequence& ICS) { 1413 if (checkPlaceholderForOverload(*this, From)) 1414 return ExprError(); 1415 1416 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1417 bool AllowObjCWritebackConversion 1418 = getLangOpts().ObjCAutoRefCount && 1419 (Action == AA_Passing || Action == AA_Sending); 1420 if (getLangOpts().ObjC1) 1421 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1422 From->getType(), From); 1423 ICS = ::TryImplicitConversion(*this, From, ToType, 1424 /*SuppressUserConversions=*/false, 1425 AllowExplicit, 1426 /*InOverloadResolution=*/false, 1427 /*CStyle=*/false, 1428 AllowObjCWritebackConversion, 1429 /*AllowObjCConversionOnExplicit=*/false); 1430 return PerformImplicitConversion(From, ToType, ICS, Action); 1431 } 1432 1433 /// Determine whether the conversion from FromType to ToType is a valid 1434 /// conversion that strips "noexcept" or "noreturn" off the nested function 1435 /// type. 1436 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1437 QualType &ResultTy) { 1438 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1439 return false; 1440 1441 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1442 // or F(t noexcept) -> F(t) 1443 // where F adds one of the following at most once: 1444 // - a pointer 1445 // - a member pointer 1446 // - a block pointer 1447 // Changes here need matching changes in FindCompositePointerType. 1448 CanQualType CanTo = Context.getCanonicalType(ToType); 1449 CanQualType CanFrom = Context.getCanonicalType(FromType); 1450 Type::TypeClass TyClass = CanTo->getTypeClass(); 1451 if (TyClass != CanFrom->getTypeClass()) return false; 1452 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1453 if (TyClass == Type::Pointer) { 1454 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1455 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1456 } else if (TyClass == Type::BlockPointer) { 1457 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1458 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1459 } else if (TyClass == Type::MemberPointer) { 1460 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1461 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1462 // A function pointer conversion cannot change the class of the function. 1463 if (ToMPT->getClass() != FromMPT->getClass()) 1464 return false; 1465 CanTo = ToMPT->getPointeeType(); 1466 CanFrom = FromMPT->getPointeeType(); 1467 } else { 1468 return false; 1469 } 1470 1471 TyClass = CanTo->getTypeClass(); 1472 if (TyClass != CanFrom->getTypeClass()) return false; 1473 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1474 return false; 1475 } 1476 1477 const auto *FromFn = cast<FunctionType>(CanFrom); 1478 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1479 1480 const auto *ToFn = cast<FunctionType>(CanTo); 1481 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1482 1483 bool Changed = false; 1484 1485 // Drop 'noreturn' if not present in target type. 1486 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1487 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1488 Changed = true; 1489 } 1490 1491 // Drop 'noexcept' if not present in target type. 1492 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1493 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1494 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1495 FromFn = cast<FunctionType>( 1496 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1497 EST_None) 1498 .getTypePtr()); 1499 Changed = true; 1500 } 1501 1502 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1503 // only if the ExtParameterInfo lists of the two function prototypes can be 1504 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1505 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1506 bool CanUseToFPT, CanUseFromFPT; 1507 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1508 CanUseFromFPT, NewParamInfos) && 1509 CanUseToFPT && !CanUseFromFPT) { 1510 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1511 ExtInfo.ExtParameterInfos = 1512 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1513 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1514 FromFPT->getParamTypes(), ExtInfo); 1515 FromFn = QT->getAs<FunctionType>(); 1516 Changed = true; 1517 } 1518 } 1519 1520 if (!Changed) 1521 return false; 1522 1523 assert(QualType(FromFn, 0).isCanonical()); 1524 if (QualType(FromFn, 0) != CanTo) return false; 1525 1526 ResultTy = ToType; 1527 return true; 1528 } 1529 1530 /// Determine whether the conversion from FromType to ToType is a valid 1531 /// vector conversion. 1532 /// 1533 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1534 /// conversion. 1535 static bool IsVectorConversion(Sema &S, QualType FromType, 1536 QualType ToType, ImplicitConversionKind &ICK) { 1537 // We need at least one of these types to be a vector type to have a vector 1538 // conversion. 1539 if (!ToType->isVectorType() && !FromType->isVectorType()) 1540 return false; 1541 1542 // Identical types require no conversions. 1543 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1544 return false; 1545 1546 // There are no conversions between extended vector types, only identity. 1547 if (ToType->isExtVectorType()) { 1548 // There are no conversions between extended vector types other than the 1549 // identity conversion. 1550 if (FromType->isExtVectorType()) 1551 return false; 1552 1553 // Vector splat from any arithmetic type to a vector. 1554 if (FromType->isArithmeticType()) { 1555 ICK = ICK_Vector_Splat; 1556 return true; 1557 } 1558 } 1559 1560 // We can perform the conversion between vector types in the following cases: 1561 // 1)vector types are equivalent AltiVec and GCC vector types 1562 // 2)lax vector conversions are permitted and the vector types are of the 1563 // same size 1564 if (ToType->isVectorType() && FromType->isVectorType()) { 1565 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1566 S.isLaxVectorConversion(FromType, ToType)) { 1567 ICK = ICK_Vector_Conversion; 1568 return true; 1569 } 1570 } 1571 1572 return false; 1573 } 1574 1575 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1576 bool InOverloadResolution, 1577 StandardConversionSequence &SCS, 1578 bool CStyle); 1579 1580 /// IsStandardConversion - Determines whether there is a standard 1581 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1582 /// expression From to the type ToType. Standard conversion sequences 1583 /// only consider non-class types; for conversions that involve class 1584 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1585 /// contain the standard conversion sequence required to perform this 1586 /// conversion and this routine will return true. Otherwise, this 1587 /// routine will return false and the value of SCS is unspecified. 1588 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1589 bool InOverloadResolution, 1590 StandardConversionSequence &SCS, 1591 bool CStyle, 1592 bool AllowObjCWritebackConversion) { 1593 QualType FromType = From->getType(); 1594 1595 // Standard conversions (C++ [conv]) 1596 SCS.setAsIdentityConversion(); 1597 SCS.IncompatibleObjC = false; 1598 SCS.setFromType(FromType); 1599 SCS.CopyConstructor = nullptr; 1600 1601 // There are no standard conversions for class types in C++, so 1602 // abort early. When overloading in C, however, we do permit them. 1603 if (S.getLangOpts().CPlusPlus && 1604 (FromType->isRecordType() || ToType->isRecordType())) 1605 return false; 1606 1607 // The first conversion can be an lvalue-to-rvalue conversion, 1608 // array-to-pointer conversion, or function-to-pointer conversion 1609 // (C++ 4p1). 1610 1611 if (FromType == S.Context.OverloadTy) { 1612 DeclAccessPair AccessPair; 1613 if (FunctionDecl *Fn 1614 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1615 AccessPair)) { 1616 // We were able to resolve the address of the overloaded function, 1617 // so we can convert to the type of that function. 1618 FromType = Fn->getType(); 1619 SCS.setFromType(FromType); 1620 1621 // we can sometimes resolve &foo<int> regardless of ToType, so check 1622 // if the type matches (identity) or we are converting to bool 1623 if (!S.Context.hasSameUnqualifiedType( 1624 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1625 QualType resultTy; 1626 // if the function type matches except for [[noreturn]], it's ok 1627 if (!S.IsFunctionConversion(FromType, 1628 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1629 // otherwise, only a boolean conversion is standard 1630 if (!ToType->isBooleanType()) 1631 return false; 1632 } 1633 1634 // Check if the "from" expression is taking the address of an overloaded 1635 // function and recompute the FromType accordingly. Take advantage of the 1636 // fact that non-static member functions *must* have such an address-of 1637 // expression. 1638 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1639 if (Method && !Method->isStatic()) { 1640 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1641 "Non-unary operator on non-static member address"); 1642 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1643 == UO_AddrOf && 1644 "Non-address-of operator on non-static member address"); 1645 const Type *ClassType 1646 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1647 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1648 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1649 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1650 UO_AddrOf && 1651 "Non-address-of operator for overloaded function expression"); 1652 FromType = S.Context.getPointerType(FromType); 1653 } 1654 1655 // Check that we've computed the proper type after overload resolution. 1656 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1657 // be calling it from within an NDEBUG block. 1658 assert(S.Context.hasSameType( 1659 FromType, 1660 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1661 } else { 1662 return false; 1663 } 1664 } 1665 // Lvalue-to-rvalue conversion (C++11 4.1): 1666 // A glvalue (3.10) of a non-function, non-array type T can 1667 // be converted to a prvalue. 1668 bool argIsLValue = From->isGLValue(); 1669 if (argIsLValue && 1670 !FromType->isFunctionType() && !FromType->isArrayType() && 1671 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1672 SCS.First = ICK_Lvalue_To_Rvalue; 1673 1674 // C11 6.3.2.1p2: 1675 // ... if the lvalue has atomic type, the value has the non-atomic version 1676 // of the type of the lvalue ... 1677 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1678 FromType = Atomic->getValueType(); 1679 1680 // If T is a non-class type, the type of the rvalue is the 1681 // cv-unqualified version of T. Otherwise, the type of the rvalue 1682 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1683 // just strip the qualifiers because they don't matter. 1684 FromType = FromType.getUnqualifiedType(); 1685 } else if (FromType->isArrayType()) { 1686 // Array-to-pointer conversion (C++ 4.2) 1687 SCS.First = ICK_Array_To_Pointer; 1688 1689 // An lvalue or rvalue of type "array of N T" or "array of unknown 1690 // bound of T" can be converted to an rvalue of type "pointer to 1691 // T" (C++ 4.2p1). 1692 FromType = S.Context.getArrayDecayedType(FromType); 1693 1694 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1695 // This conversion is deprecated in C++03 (D.4) 1696 SCS.DeprecatedStringLiteralToCharPtr = true; 1697 1698 // For the purpose of ranking in overload resolution 1699 // (13.3.3.1.1), this conversion is considered an 1700 // array-to-pointer conversion followed by a qualification 1701 // conversion (4.4). (C++ 4.2p2) 1702 SCS.Second = ICK_Identity; 1703 SCS.Third = ICK_Qualification; 1704 SCS.QualificationIncludesObjCLifetime = false; 1705 SCS.setAllToTypes(FromType); 1706 return true; 1707 } 1708 } else if (FromType->isFunctionType() && argIsLValue) { 1709 // Function-to-pointer conversion (C++ 4.3). 1710 SCS.First = ICK_Function_To_Pointer; 1711 1712 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1713 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1714 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1715 return false; 1716 1717 // An lvalue of function type T can be converted to an rvalue of 1718 // type "pointer to T." The result is a pointer to the 1719 // function. (C++ 4.3p1). 1720 FromType = S.Context.getPointerType(FromType); 1721 } else { 1722 // We don't require any conversions for the first step. 1723 SCS.First = ICK_Identity; 1724 } 1725 SCS.setToType(0, FromType); 1726 1727 // The second conversion can be an integral promotion, floating 1728 // point promotion, integral conversion, floating point conversion, 1729 // floating-integral conversion, pointer conversion, 1730 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1731 // For overloading in C, this can also be a "compatible-type" 1732 // conversion. 1733 bool IncompatibleObjC = false; 1734 ImplicitConversionKind SecondICK = ICK_Identity; 1735 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1736 // The unqualified versions of the types are the same: there's no 1737 // conversion to do. 1738 SCS.Second = ICK_Identity; 1739 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1740 // Integral promotion (C++ 4.5). 1741 SCS.Second = ICK_Integral_Promotion; 1742 FromType = ToType.getUnqualifiedType(); 1743 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1744 // Floating point promotion (C++ 4.6). 1745 SCS.Second = ICK_Floating_Promotion; 1746 FromType = ToType.getUnqualifiedType(); 1747 } else if (S.IsComplexPromotion(FromType, ToType)) { 1748 // Complex promotion (Clang extension) 1749 SCS.Second = ICK_Complex_Promotion; 1750 FromType = ToType.getUnqualifiedType(); 1751 } else if (ToType->isBooleanType() && 1752 (FromType->isArithmeticType() || 1753 FromType->isAnyPointerType() || 1754 FromType->isBlockPointerType() || 1755 FromType->isMemberPointerType() || 1756 FromType->isNullPtrType())) { 1757 // Boolean conversions (C++ 4.12). 1758 SCS.Second = ICK_Boolean_Conversion; 1759 FromType = S.Context.BoolTy; 1760 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1761 ToType->isIntegralType(S.Context)) { 1762 // Integral conversions (C++ 4.7). 1763 SCS.Second = ICK_Integral_Conversion; 1764 FromType = ToType.getUnqualifiedType(); 1765 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1766 // Complex conversions (C99 6.3.1.6) 1767 SCS.Second = ICK_Complex_Conversion; 1768 FromType = ToType.getUnqualifiedType(); 1769 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1770 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1771 // Complex-real conversions (C99 6.3.1.7) 1772 SCS.Second = ICK_Complex_Real; 1773 FromType = ToType.getUnqualifiedType(); 1774 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1775 // FIXME: disable conversions between long double and __float128 if 1776 // their representation is different until there is back end support 1777 // We of course allow this conversion if long double is really double. 1778 if (&S.Context.getFloatTypeSemantics(FromType) != 1779 &S.Context.getFloatTypeSemantics(ToType)) { 1780 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1781 ToType == S.Context.LongDoubleTy) || 1782 (FromType == S.Context.LongDoubleTy && 1783 ToType == S.Context.Float128Ty)); 1784 if (Float128AndLongDouble && 1785 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1786 &llvm::APFloat::PPCDoubleDouble())) 1787 return false; 1788 } 1789 // Floating point conversions (C++ 4.8). 1790 SCS.Second = ICK_Floating_Conversion; 1791 FromType = ToType.getUnqualifiedType(); 1792 } else if ((FromType->isRealFloatingType() && 1793 ToType->isIntegralType(S.Context)) || 1794 (FromType->isIntegralOrUnscopedEnumerationType() && 1795 ToType->isRealFloatingType())) { 1796 // Floating-integral conversions (C++ 4.9). 1797 SCS.Second = ICK_Floating_Integral; 1798 FromType = ToType.getUnqualifiedType(); 1799 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1800 SCS.Second = ICK_Block_Pointer_Conversion; 1801 } else if (AllowObjCWritebackConversion && 1802 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1803 SCS.Second = ICK_Writeback_Conversion; 1804 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1805 FromType, IncompatibleObjC)) { 1806 // Pointer conversions (C++ 4.10). 1807 SCS.Second = ICK_Pointer_Conversion; 1808 SCS.IncompatibleObjC = IncompatibleObjC; 1809 FromType = FromType.getUnqualifiedType(); 1810 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1811 InOverloadResolution, FromType)) { 1812 // Pointer to member conversions (4.11). 1813 SCS.Second = ICK_Pointer_Member; 1814 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1815 SCS.Second = SecondICK; 1816 FromType = ToType.getUnqualifiedType(); 1817 } else if (!S.getLangOpts().CPlusPlus && 1818 S.Context.typesAreCompatible(ToType, FromType)) { 1819 // Compatible conversions (Clang extension for C function overloading) 1820 SCS.Second = ICK_Compatible_Conversion; 1821 FromType = ToType.getUnqualifiedType(); 1822 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1823 InOverloadResolution, 1824 SCS, CStyle)) { 1825 SCS.Second = ICK_TransparentUnionConversion; 1826 FromType = ToType; 1827 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1828 CStyle)) { 1829 // tryAtomicConversion has updated the standard conversion sequence 1830 // appropriately. 1831 return true; 1832 } else if (ToType->isEventT() && 1833 From->isIntegerConstantExpr(S.getASTContext()) && 1834 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1835 SCS.Second = ICK_Zero_Event_Conversion; 1836 FromType = ToType; 1837 } else if (ToType->isQueueT() && 1838 From->isIntegerConstantExpr(S.getASTContext()) && 1839 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1840 SCS.Second = ICK_Zero_Queue_Conversion; 1841 FromType = ToType; 1842 } else { 1843 // No second conversion required. 1844 SCS.Second = ICK_Identity; 1845 } 1846 SCS.setToType(1, FromType); 1847 1848 // The third conversion can be a function pointer conversion or a 1849 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1850 bool ObjCLifetimeConversion; 1851 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1852 // Function pointer conversions (removing 'noexcept') including removal of 1853 // 'noreturn' (Clang extension). 1854 SCS.Third = ICK_Function_Conversion; 1855 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1856 ObjCLifetimeConversion)) { 1857 SCS.Third = ICK_Qualification; 1858 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1859 FromType = ToType; 1860 } else { 1861 // No conversion required 1862 SCS.Third = ICK_Identity; 1863 } 1864 1865 // C++ [over.best.ics]p6: 1866 // [...] Any difference in top-level cv-qualification is 1867 // subsumed by the initialization itself and does not constitute 1868 // a conversion. [...] 1869 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1870 QualType CanonTo = S.Context.getCanonicalType(ToType); 1871 if (CanonFrom.getLocalUnqualifiedType() 1872 == CanonTo.getLocalUnqualifiedType() && 1873 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1874 FromType = ToType; 1875 CanonFrom = CanonTo; 1876 } 1877 1878 SCS.setToType(2, FromType); 1879 1880 if (CanonFrom == CanonTo) 1881 return true; 1882 1883 // If we have not converted the argument type to the parameter type, 1884 // this is a bad conversion sequence, unless we're resolving an overload in C. 1885 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1886 return false; 1887 1888 ExprResult ER = ExprResult{From}; 1889 Sema::AssignConvertType Conv = 1890 S.CheckSingleAssignmentConstraints(ToType, ER, 1891 /*Diagnose=*/false, 1892 /*DiagnoseCFAudited=*/false, 1893 /*ConvertRHS=*/false); 1894 ImplicitConversionKind SecondConv; 1895 switch (Conv) { 1896 case Sema::Compatible: 1897 SecondConv = ICK_C_Only_Conversion; 1898 break; 1899 // For our purposes, discarding qualifiers is just as bad as using an 1900 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1901 // qualifiers, as well. 1902 case Sema::CompatiblePointerDiscardsQualifiers: 1903 case Sema::IncompatiblePointer: 1904 case Sema::IncompatiblePointerSign: 1905 SecondConv = ICK_Incompatible_Pointer_Conversion; 1906 break; 1907 default: 1908 return false; 1909 } 1910 1911 // First can only be an lvalue conversion, so we pretend that this was the 1912 // second conversion. First should already be valid from earlier in the 1913 // function. 1914 SCS.Second = SecondConv; 1915 SCS.setToType(1, ToType); 1916 1917 // Third is Identity, because Second should rank us worse than any other 1918 // conversion. This could also be ICK_Qualification, but it's simpler to just 1919 // lump everything in with the second conversion, and we don't gain anything 1920 // from making this ICK_Qualification. 1921 SCS.Third = ICK_Identity; 1922 SCS.setToType(2, ToType); 1923 return true; 1924 } 1925 1926 static bool 1927 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1928 QualType &ToType, 1929 bool InOverloadResolution, 1930 StandardConversionSequence &SCS, 1931 bool CStyle) { 1932 1933 const RecordType *UT = ToType->getAsUnionType(); 1934 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1935 return false; 1936 // The field to initialize within the transparent union. 1937 RecordDecl *UD = UT->getDecl(); 1938 // It's compatible if the expression matches any of the fields. 1939 for (const auto *it : UD->fields()) { 1940 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1941 CStyle, /*ObjCWritebackConversion=*/false)) { 1942 ToType = it->getType(); 1943 return true; 1944 } 1945 } 1946 return false; 1947 } 1948 1949 /// IsIntegralPromotion - Determines whether the conversion from the 1950 /// expression From (whose potentially-adjusted type is FromType) to 1951 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1952 /// sets PromotedType to the promoted type. 1953 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1954 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1955 // All integers are built-in. 1956 if (!To) { 1957 return false; 1958 } 1959 1960 // An rvalue of type char, signed char, unsigned char, short int, or 1961 // unsigned short int can be converted to an rvalue of type int if 1962 // int can represent all the values of the source type; otherwise, 1963 // the source rvalue can be converted to an rvalue of type unsigned 1964 // int (C++ 4.5p1). 1965 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1966 !FromType->isEnumeralType()) { 1967 if (// We can promote any signed, promotable integer type to an int 1968 (FromType->isSignedIntegerType() || 1969 // We can promote any unsigned integer type whose size is 1970 // less than int to an int. 1971 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1972 return To->getKind() == BuiltinType::Int; 1973 } 1974 1975 return To->getKind() == BuiltinType::UInt; 1976 } 1977 1978 // C++11 [conv.prom]p3: 1979 // A prvalue of an unscoped enumeration type whose underlying type is not 1980 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1981 // following types that can represent all the values of the enumeration 1982 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1983 // unsigned int, long int, unsigned long int, long long int, or unsigned 1984 // long long int. If none of the types in that list can represent all the 1985 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1986 // type can be converted to an rvalue a prvalue of the extended integer type 1987 // with lowest integer conversion rank (4.13) greater than the rank of long 1988 // long in which all the values of the enumeration can be represented. If 1989 // there are two such extended types, the signed one is chosen. 1990 // C++11 [conv.prom]p4: 1991 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1992 // can be converted to a prvalue of its underlying type. Moreover, if 1993 // integral promotion can be applied to its underlying type, a prvalue of an 1994 // unscoped enumeration type whose underlying type is fixed can also be 1995 // converted to a prvalue of the promoted underlying type. 1996 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1997 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1998 // provided for a scoped enumeration. 1999 if (FromEnumType->getDecl()->isScoped()) 2000 return false; 2001 2002 // We can perform an integral promotion to the underlying type of the enum, 2003 // even if that's not the promoted type. Note that the check for promoting 2004 // the underlying type is based on the type alone, and does not consider 2005 // the bitfield-ness of the actual source expression. 2006 if (FromEnumType->getDecl()->isFixed()) { 2007 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2008 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2009 IsIntegralPromotion(nullptr, Underlying, ToType); 2010 } 2011 2012 // We have already pre-calculated the promotion type, so this is trivial. 2013 if (ToType->isIntegerType() && 2014 isCompleteType(From->getBeginLoc(), FromType)) 2015 return Context.hasSameUnqualifiedType( 2016 ToType, FromEnumType->getDecl()->getPromotionType()); 2017 2018 // C++ [conv.prom]p5: 2019 // If the bit-field has an enumerated type, it is treated as any other 2020 // value of that type for promotion purposes. 2021 // 2022 // ... so do not fall through into the bit-field checks below in C++. 2023 if (getLangOpts().CPlusPlus) 2024 return false; 2025 } 2026 2027 // C++0x [conv.prom]p2: 2028 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2029 // to an rvalue a prvalue of the first of the following types that can 2030 // represent all the values of its underlying type: int, unsigned int, 2031 // long int, unsigned long int, long long int, or unsigned long long int. 2032 // If none of the types in that list can represent all the values of its 2033 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2034 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2035 // type. 2036 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2037 ToType->isIntegerType()) { 2038 // Determine whether the type we're converting from is signed or 2039 // unsigned. 2040 bool FromIsSigned = FromType->isSignedIntegerType(); 2041 uint64_t FromSize = Context.getTypeSize(FromType); 2042 2043 // The types we'll try to promote to, in the appropriate 2044 // order. Try each of these types. 2045 QualType PromoteTypes[6] = { 2046 Context.IntTy, Context.UnsignedIntTy, 2047 Context.LongTy, Context.UnsignedLongTy , 2048 Context.LongLongTy, Context.UnsignedLongLongTy 2049 }; 2050 for (int Idx = 0; Idx < 6; ++Idx) { 2051 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2052 if (FromSize < ToSize || 2053 (FromSize == ToSize && 2054 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2055 // We found the type that we can promote to. If this is the 2056 // type we wanted, we have a promotion. Otherwise, no 2057 // promotion. 2058 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2059 } 2060 } 2061 } 2062 2063 // An rvalue for an integral bit-field (9.6) can be converted to an 2064 // rvalue of type int if int can represent all the values of the 2065 // bit-field; otherwise, it can be converted to unsigned int if 2066 // unsigned int can represent all the values of the bit-field. If 2067 // the bit-field is larger yet, no integral promotion applies to 2068 // it. If the bit-field has an enumerated type, it is treated as any 2069 // other value of that type for promotion purposes (C++ 4.5p3). 2070 // FIXME: We should delay checking of bit-fields until we actually perform the 2071 // conversion. 2072 // 2073 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2074 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2075 // bit-fields and those whose underlying type is larger than int) for GCC 2076 // compatibility. 2077 if (From) { 2078 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2079 llvm::APSInt BitWidth; 2080 if (FromType->isIntegralType(Context) && 2081 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2082 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2083 ToSize = Context.getTypeSize(ToType); 2084 2085 // Are we promoting to an int from a bitfield that fits in an int? 2086 if (BitWidth < ToSize || 2087 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2088 return To->getKind() == BuiltinType::Int; 2089 } 2090 2091 // Are we promoting to an unsigned int from an unsigned bitfield 2092 // that fits into an unsigned int? 2093 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2094 return To->getKind() == BuiltinType::UInt; 2095 } 2096 2097 return false; 2098 } 2099 } 2100 } 2101 2102 // An rvalue of type bool can be converted to an rvalue of type int, 2103 // with false becoming zero and true becoming one (C++ 4.5p4). 2104 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2105 return true; 2106 } 2107 2108 return false; 2109 } 2110 2111 /// IsFloatingPointPromotion - Determines whether the conversion from 2112 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2113 /// returns true and sets PromotedType to the promoted type. 2114 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2115 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2116 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2117 /// An rvalue of type float can be converted to an rvalue of type 2118 /// double. (C++ 4.6p1). 2119 if (FromBuiltin->getKind() == BuiltinType::Float && 2120 ToBuiltin->getKind() == BuiltinType::Double) 2121 return true; 2122 2123 // C99 6.3.1.5p1: 2124 // When a float is promoted to double or long double, or a 2125 // double is promoted to long double [...]. 2126 if (!getLangOpts().CPlusPlus && 2127 (FromBuiltin->getKind() == BuiltinType::Float || 2128 FromBuiltin->getKind() == BuiltinType::Double) && 2129 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2130 ToBuiltin->getKind() == BuiltinType::Float128)) 2131 return true; 2132 2133 // Half can be promoted to float. 2134 if (!getLangOpts().NativeHalfType && 2135 FromBuiltin->getKind() == BuiltinType::Half && 2136 ToBuiltin->getKind() == BuiltinType::Float) 2137 return true; 2138 } 2139 2140 return false; 2141 } 2142 2143 /// Determine if a conversion is a complex promotion. 2144 /// 2145 /// A complex promotion is defined as a complex -> complex conversion 2146 /// where the conversion between the underlying real types is a 2147 /// floating-point or integral promotion. 2148 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2149 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2150 if (!FromComplex) 2151 return false; 2152 2153 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2154 if (!ToComplex) 2155 return false; 2156 2157 return IsFloatingPointPromotion(FromComplex->getElementType(), 2158 ToComplex->getElementType()) || 2159 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2160 ToComplex->getElementType()); 2161 } 2162 2163 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2164 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2165 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2166 /// if non-empty, will be a pointer to ToType that may or may not have 2167 /// the right set of qualifiers on its pointee. 2168 /// 2169 static QualType 2170 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2171 QualType ToPointee, QualType ToType, 2172 ASTContext &Context, 2173 bool StripObjCLifetime = false) { 2174 assert((FromPtr->getTypeClass() == Type::Pointer || 2175 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2176 "Invalid similarly-qualified pointer type"); 2177 2178 /// Conversions to 'id' subsume cv-qualifier conversions. 2179 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2180 return ToType.getUnqualifiedType(); 2181 2182 QualType CanonFromPointee 2183 = Context.getCanonicalType(FromPtr->getPointeeType()); 2184 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2185 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2186 2187 if (StripObjCLifetime) 2188 Quals.removeObjCLifetime(); 2189 2190 // Exact qualifier match -> return the pointer type we're converting to. 2191 if (CanonToPointee.getLocalQualifiers() == Quals) { 2192 // ToType is exactly what we need. Return it. 2193 if (!ToType.isNull()) 2194 return ToType.getUnqualifiedType(); 2195 2196 // Build a pointer to ToPointee. It has the right qualifiers 2197 // already. 2198 if (isa<ObjCObjectPointerType>(ToType)) 2199 return Context.getObjCObjectPointerType(ToPointee); 2200 return Context.getPointerType(ToPointee); 2201 } 2202 2203 // Just build a canonical type that has the right qualifiers. 2204 QualType QualifiedCanonToPointee 2205 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2206 2207 if (isa<ObjCObjectPointerType>(ToType)) 2208 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2209 return Context.getPointerType(QualifiedCanonToPointee); 2210 } 2211 2212 static bool isNullPointerConstantForConversion(Expr *Expr, 2213 bool InOverloadResolution, 2214 ASTContext &Context) { 2215 // Handle value-dependent integral null pointer constants correctly. 2216 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2217 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2218 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2219 return !InOverloadResolution; 2220 2221 return Expr->isNullPointerConstant(Context, 2222 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2223 : Expr::NPC_ValueDependentIsNull); 2224 } 2225 2226 /// IsPointerConversion - Determines whether the conversion of the 2227 /// expression From, which has the (possibly adjusted) type FromType, 2228 /// can be converted to the type ToType via a pointer conversion (C++ 2229 /// 4.10). If so, returns true and places the converted type (that 2230 /// might differ from ToType in its cv-qualifiers at some level) into 2231 /// ConvertedType. 2232 /// 2233 /// This routine also supports conversions to and from block pointers 2234 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2235 /// pointers to interfaces. FIXME: Once we've determined the 2236 /// appropriate overloading rules for Objective-C, we may want to 2237 /// split the Objective-C checks into a different routine; however, 2238 /// GCC seems to consider all of these conversions to be pointer 2239 /// conversions, so for now they live here. IncompatibleObjC will be 2240 /// set if the conversion is an allowed Objective-C conversion that 2241 /// should result in a warning. 2242 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2243 bool InOverloadResolution, 2244 QualType& ConvertedType, 2245 bool &IncompatibleObjC) { 2246 IncompatibleObjC = false; 2247 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2248 IncompatibleObjC)) 2249 return true; 2250 2251 // Conversion from a null pointer constant to any Objective-C pointer type. 2252 if (ToType->isObjCObjectPointerType() && 2253 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2254 ConvertedType = ToType; 2255 return true; 2256 } 2257 2258 // Blocks: Block pointers can be converted to void*. 2259 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2260 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2261 ConvertedType = ToType; 2262 return true; 2263 } 2264 // Blocks: A null pointer constant can be converted to a block 2265 // pointer type. 2266 if (ToType->isBlockPointerType() && 2267 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2268 ConvertedType = ToType; 2269 return true; 2270 } 2271 2272 // If the left-hand-side is nullptr_t, the right side can be a null 2273 // pointer constant. 2274 if (ToType->isNullPtrType() && 2275 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2276 ConvertedType = ToType; 2277 return true; 2278 } 2279 2280 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2281 if (!ToTypePtr) 2282 return false; 2283 2284 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2285 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2286 ConvertedType = ToType; 2287 return true; 2288 } 2289 2290 // Beyond this point, both types need to be pointers 2291 // , including objective-c pointers. 2292 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2293 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2294 !getLangOpts().ObjCAutoRefCount) { 2295 ConvertedType = BuildSimilarlyQualifiedPointerType( 2296 FromType->getAs<ObjCObjectPointerType>(), 2297 ToPointeeType, 2298 ToType, Context); 2299 return true; 2300 } 2301 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2302 if (!FromTypePtr) 2303 return false; 2304 2305 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2306 2307 // If the unqualified pointee types are the same, this can't be a 2308 // pointer conversion, so don't do all of the work below. 2309 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2310 return false; 2311 2312 // An rvalue of type "pointer to cv T," where T is an object type, 2313 // can be converted to an rvalue of type "pointer to cv void" (C++ 2314 // 4.10p2). 2315 if (FromPointeeType->isIncompleteOrObjectType() && 2316 ToPointeeType->isVoidType()) { 2317 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2318 ToPointeeType, 2319 ToType, Context, 2320 /*StripObjCLifetime=*/true); 2321 return true; 2322 } 2323 2324 // MSVC allows implicit function to void* type conversion. 2325 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2326 ToPointeeType->isVoidType()) { 2327 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2328 ToPointeeType, 2329 ToType, Context); 2330 return true; 2331 } 2332 2333 // When we're overloading in C, we allow a special kind of pointer 2334 // conversion for compatible-but-not-identical pointee types. 2335 if (!getLangOpts().CPlusPlus && 2336 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2337 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2338 ToPointeeType, 2339 ToType, Context); 2340 return true; 2341 } 2342 2343 // C++ [conv.ptr]p3: 2344 // 2345 // An rvalue of type "pointer to cv D," where D is a class type, 2346 // can be converted to an rvalue of type "pointer to cv B," where 2347 // B is a base class (clause 10) of D. If B is an inaccessible 2348 // (clause 11) or ambiguous (10.2) base class of D, a program that 2349 // necessitates this conversion is ill-formed. The result of the 2350 // conversion is a pointer to the base class sub-object of the 2351 // derived class object. The null pointer value is converted to 2352 // the null pointer value of the destination type. 2353 // 2354 // Note that we do not check for ambiguity or inaccessibility 2355 // here. That is handled by CheckPointerConversion. 2356 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2357 ToPointeeType->isRecordType() && 2358 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2359 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2360 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2361 ToPointeeType, 2362 ToType, Context); 2363 return true; 2364 } 2365 2366 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2367 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2368 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2369 ToPointeeType, 2370 ToType, Context); 2371 return true; 2372 } 2373 2374 return false; 2375 } 2376 2377 /// Adopt the given qualifiers for the given type. 2378 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2379 Qualifiers TQs = T.getQualifiers(); 2380 2381 // Check whether qualifiers already match. 2382 if (TQs == Qs) 2383 return T; 2384 2385 if (Qs.compatiblyIncludes(TQs)) 2386 return Context.getQualifiedType(T, Qs); 2387 2388 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2389 } 2390 2391 /// isObjCPointerConversion - Determines whether this is an 2392 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2393 /// with the same arguments and return values. 2394 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2395 QualType& ConvertedType, 2396 bool &IncompatibleObjC) { 2397 if (!getLangOpts().ObjC1) 2398 return false; 2399 2400 // The set of qualifiers on the type we're converting from. 2401 Qualifiers FromQualifiers = FromType.getQualifiers(); 2402 2403 // First, we handle all conversions on ObjC object pointer types. 2404 const ObjCObjectPointerType* ToObjCPtr = 2405 ToType->getAs<ObjCObjectPointerType>(); 2406 const ObjCObjectPointerType *FromObjCPtr = 2407 FromType->getAs<ObjCObjectPointerType>(); 2408 2409 if (ToObjCPtr && FromObjCPtr) { 2410 // If the pointee types are the same (ignoring qualifications), 2411 // then this is not a pointer conversion. 2412 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2413 FromObjCPtr->getPointeeType())) 2414 return false; 2415 2416 // Conversion between Objective-C pointers. 2417 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2418 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2419 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2420 if (getLangOpts().CPlusPlus && LHS && RHS && 2421 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2422 FromObjCPtr->getPointeeType())) 2423 return false; 2424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2425 ToObjCPtr->getPointeeType(), 2426 ToType, Context); 2427 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2428 return true; 2429 } 2430 2431 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2432 // Okay: this is some kind of implicit downcast of Objective-C 2433 // interfaces, which is permitted. However, we're going to 2434 // complain about it. 2435 IncompatibleObjC = true; 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2437 ToObjCPtr->getPointeeType(), 2438 ToType, Context); 2439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2440 return true; 2441 } 2442 } 2443 // Beyond this point, both types need to be C pointers or block pointers. 2444 QualType ToPointeeType; 2445 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2446 ToPointeeType = ToCPtr->getPointeeType(); 2447 else if (const BlockPointerType *ToBlockPtr = 2448 ToType->getAs<BlockPointerType>()) { 2449 // Objective C++: We're able to convert from a pointer to any object 2450 // to a block pointer type. 2451 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2452 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2453 return true; 2454 } 2455 ToPointeeType = ToBlockPtr->getPointeeType(); 2456 } 2457 else if (FromType->getAs<BlockPointerType>() && 2458 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2459 // Objective C++: We're able to convert from a block pointer type to a 2460 // pointer to any object. 2461 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2462 return true; 2463 } 2464 else 2465 return false; 2466 2467 QualType FromPointeeType; 2468 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2469 FromPointeeType = FromCPtr->getPointeeType(); 2470 else if (const BlockPointerType *FromBlockPtr = 2471 FromType->getAs<BlockPointerType>()) 2472 FromPointeeType = FromBlockPtr->getPointeeType(); 2473 else 2474 return false; 2475 2476 // If we have pointers to pointers, recursively check whether this 2477 // is an Objective-C conversion. 2478 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2479 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2480 IncompatibleObjC)) { 2481 // We always complain about this conversion. 2482 IncompatibleObjC = true; 2483 ConvertedType = Context.getPointerType(ConvertedType); 2484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2485 return true; 2486 } 2487 // Allow conversion of pointee being objective-c pointer to another one; 2488 // as in I* to id. 2489 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2490 ToPointeeType->getAs<ObjCObjectPointerType>() && 2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2492 IncompatibleObjC)) { 2493 2494 ConvertedType = Context.getPointerType(ConvertedType); 2495 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2496 return true; 2497 } 2498 2499 // If we have pointers to functions or blocks, check whether the only 2500 // differences in the argument and result types are in Objective-C 2501 // pointer conversions. If so, we permit the conversion (but 2502 // complain about it). 2503 const FunctionProtoType *FromFunctionType 2504 = FromPointeeType->getAs<FunctionProtoType>(); 2505 const FunctionProtoType *ToFunctionType 2506 = ToPointeeType->getAs<FunctionProtoType>(); 2507 if (FromFunctionType && ToFunctionType) { 2508 // If the function types are exactly the same, this isn't an 2509 // Objective-C pointer conversion. 2510 if (Context.getCanonicalType(FromPointeeType) 2511 == Context.getCanonicalType(ToPointeeType)) 2512 return false; 2513 2514 // Perform the quick checks that will tell us whether these 2515 // function types are obviously different. 2516 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2517 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2518 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2519 return false; 2520 2521 bool HasObjCConversion = false; 2522 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2523 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2524 // Okay, the types match exactly. Nothing to do. 2525 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2526 ToFunctionType->getReturnType(), 2527 ConvertedType, IncompatibleObjC)) { 2528 // Okay, we have an Objective-C pointer conversion. 2529 HasObjCConversion = true; 2530 } else { 2531 // Function types are too different. Abort. 2532 return false; 2533 } 2534 2535 // Check argument types. 2536 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2537 ArgIdx != NumArgs; ++ArgIdx) { 2538 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2539 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2540 if (Context.getCanonicalType(FromArgType) 2541 == Context.getCanonicalType(ToArgType)) { 2542 // Okay, the types match exactly. Nothing to do. 2543 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2544 ConvertedType, IncompatibleObjC)) { 2545 // Okay, we have an Objective-C pointer conversion. 2546 HasObjCConversion = true; 2547 } else { 2548 // Argument types are too different. Abort. 2549 return false; 2550 } 2551 } 2552 2553 if (HasObjCConversion) { 2554 // We had an Objective-C conversion. Allow this pointer 2555 // conversion, but complain about it. 2556 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2557 IncompatibleObjC = true; 2558 return true; 2559 } 2560 } 2561 2562 return false; 2563 } 2564 2565 /// Determine whether this is an Objective-C writeback conversion, 2566 /// used for parameter passing when performing automatic reference counting. 2567 /// 2568 /// \param FromType The type we're converting form. 2569 /// 2570 /// \param ToType The type we're converting to. 2571 /// 2572 /// \param ConvertedType The type that will be produced after applying 2573 /// this conversion. 2574 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2575 QualType &ConvertedType) { 2576 if (!getLangOpts().ObjCAutoRefCount || 2577 Context.hasSameUnqualifiedType(FromType, ToType)) 2578 return false; 2579 2580 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2581 QualType ToPointee; 2582 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2583 ToPointee = ToPointer->getPointeeType(); 2584 else 2585 return false; 2586 2587 Qualifiers ToQuals = ToPointee.getQualifiers(); 2588 if (!ToPointee->isObjCLifetimeType() || 2589 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2590 !ToQuals.withoutObjCLifetime().empty()) 2591 return false; 2592 2593 // Argument must be a pointer to __strong to __weak. 2594 QualType FromPointee; 2595 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2596 FromPointee = FromPointer->getPointeeType(); 2597 else 2598 return false; 2599 2600 Qualifiers FromQuals = FromPointee.getQualifiers(); 2601 if (!FromPointee->isObjCLifetimeType() || 2602 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2603 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2604 return false; 2605 2606 // Make sure that we have compatible qualifiers. 2607 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2608 if (!ToQuals.compatiblyIncludes(FromQuals)) 2609 return false; 2610 2611 // Remove qualifiers from the pointee type we're converting from; they 2612 // aren't used in the compatibility check belong, and we'll be adding back 2613 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2614 FromPointee = FromPointee.getUnqualifiedType(); 2615 2616 // The unqualified form of the pointee types must be compatible. 2617 ToPointee = ToPointee.getUnqualifiedType(); 2618 bool IncompatibleObjC; 2619 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2620 FromPointee = ToPointee; 2621 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2622 IncompatibleObjC)) 2623 return false; 2624 2625 /// Construct the type we're converting to, which is a pointer to 2626 /// __autoreleasing pointee. 2627 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2628 ConvertedType = Context.getPointerType(FromPointee); 2629 return true; 2630 } 2631 2632 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2633 QualType& ConvertedType) { 2634 QualType ToPointeeType; 2635 if (const BlockPointerType *ToBlockPtr = 2636 ToType->getAs<BlockPointerType>()) 2637 ToPointeeType = ToBlockPtr->getPointeeType(); 2638 else 2639 return false; 2640 2641 QualType FromPointeeType; 2642 if (const BlockPointerType *FromBlockPtr = 2643 FromType->getAs<BlockPointerType>()) 2644 FromPointeeType = FromBlockPtr->getPointeeType(); 2645 else 2646 return false; 2647 // We have pointer to blocks, check whether the only 2648 // differences in the argument and result types are in Objective-C 2649 // pointer conversions. If so, we permit the conversion. 2650 2651 const FunctionProtoType *FromFunctionType 2652 = FromPointeeType->getAs<FunctionProtoType>(); 2653 const FunctionProtoType *ToFunctionType 2654 = ToPointeeType->getAs<FunctionProtoType>(); 2655 2656 if (!FromFunctionType || !ToFunctionType) 2657 return false; 2658 2659 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2660 return true; 2661 2662 // Perform the quick checks that will tell us whether these 2663 // function types are obviously different. 2664 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2665 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2666 return false; 2667 2668 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2669 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2670 if (FromEInfo != ToEInfo) 2671 return false; 2672 2673 bool IncompatibleObjC = false; 2674 if (Context.hasSameType(FromFunctionType->getReturnType(), 2675 ToFunctionType->getReturnType())) { 2676 // Okay, the types match exactly. Nothing to do. 2677 } else { 2678 QualType RHS = FromFunctionType->getReturnType(); 2679 QualType LHS = ToFunctionType->getReturnType(); 2680 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2681 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2682 LHS = LHS.getUnqualifiedType(); 2683 2684 if (Context.hasSameType(RHS,LHS)) { 2685 // OK exact match. 2686 } else if (isObjCPointerConversion(RHS, LHS, 2687 ConvertedType, IncompatibleObjC)) { 2688 if (IncompatibleObjC) 2689 return false; 2690 // Okay, we have an Objective-C pointer conversion. 2691 } 2692 else 2693 return false; 2694 } 2695 2696 // Check argument types. 2697 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2698 ArgIdx != NumArgs; ++ArgIdx) { 2699 IncompatibleObjC = false; 2700 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2701 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2702 if (Context.hasSameType(FromArgType, ToArgType)) { 2703 // Okay, the types match exactly. Nothing to do. 2704 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2705 ConvertedType, IncompatibleObjC)) { 2706 if (IncompatibleObjC) 2707 return false; 2708 // Okay, we have an Objective-C pointer conversion. 2709 } else 2710 // Argument types are too different. Abort. 2711 return false; 2712 } 2713 2714 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2715 bool CanUseToFPT, CanUseFromFPT; 2716 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2717 CanUseToFPT, CanUseFromFPT, 2718 NewParamInfos)) 2719 return false; 2720 2721 ConvertedType = ToType; 2722 return true; 2723 } 2724 2725 enum { 2726 ft_default, 2727 ft_different_class, 2728 ft_parameter_arity, 2729 ft_parameter_mismatch, 2730 ft_return_type, 2731 ft_qualifer_mismatch, 2732 ft_noexcept 2733 }; 2734 2735 /// Attempts to get the FunctionProtoType from a Type. Handles 2736 /// MemberFunctionPointers properly. 2737 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2738 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2739 return FPT; 2740 2741 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2742 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2743 2744 return nullptr; 2745 } 2746 2747 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2748 /// function types. Catches different number of parameter, mismatch in 2749 /// parameter types, and different return types. 2750 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2751 QualType FromType, QualType ToType) { 2752 // If either type is not valid, include no extra info. 2753 if (FromType.isNull() || ToType.isNull()) { 2754 PDiag << ft_default; 2755 return; 2756 } 2757 2758 // Get the function type from the pointers. 2759 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2760 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2761 *ToMember = ToType->getAs<MemberPointerType>(); 2762 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2763 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2764 << QualType(FromMember->getClass(), 0); 2765 return; 2766 } 2767 FromType = FromMember->getPointeeType(); 2768 ToType = ToMember->getPointeeType(); 2769 } 2770 2771 if (FromType->isPointerType()) 2772 FromType = FromType->getPointeeType(); 2773 if (ToType->isPointerType()) 2774 ToType = ToType->getPointeeType(); 2775 2776 // Remove references. 2777 FromType = FromType.getNonReferenceType(); 2778 ToType = ToType.getNonReferenceType(); 2779 2780 // Don't print extra info for non-specialized template functions. 2781 if (FromType->isInstantiationDependentType() && 2782 !FromType->getAs<TemplateSpecializationType>()) { 2783 PDiag << ft_default; 2784 return; 2785 } 2786 2787 // No extra info for same types. 2788 if (Context.hasSameType(FromType, ToType)) { 2789 PDiag << ft_default; 2790 return; 2791 } 2792 2793 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2794 *ToFunction = tryGetFunctionProtoType(ToType); 2795 2796 // Both types need to be function types. 2797 if (!FromFunction || !ToFunction) { 2798 PDiag << ft_default; 2799 return; 2800 } 2801 2802 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2803 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2804 << FromFunction->getNumParams(); 2805 return; 2806 } 2807 2808 // Handle different parameter types. 2809 unsigned ArgPos; 2810 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2811 PDiag << ft_parameter_mismatch << ArgPos + 1 2812 << ToFunction->getParamType(ArgPos) 2813 << FromFunction->getParamType(ArgPos); 2814 return; 2815 } 2816 2817 // Handle different return type. 2818 if (!Context.hasSameType(FromFunction->getReturnType(), 2819 ToFunction->getReturnType())) { 2820 PDiag << ft_return_type << ToFunction->getReturnType() 2821 << FromFunction->getReturnType(); 2822 return; 2823 } 2824 2825 unsigned FromQuals = FromFunction->getTypeQuals(), 2826 ToQuals = ToFunction->getTypeQuals(); 2827 if (FromQuals != ToQuals) { 2828 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2829 return; 2830 } 2831 2832 // Handle exception specification differences on canonical type (in C++17 2833 // onwards). 2834 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2835 ->isNothrow() != 2836 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2837 ->isNothrow()) { 2838 PDiag << ft_noexcept; 2839 return; 2840 } 2841 2842 // Unable to find a difference, so add no extra info. 2843 PDiag << ft_default; 2844 } 2845 2846 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2847 /// for equality of their argument types. Caller has already checked that 2848 /// they have same number of arguments. If the parameters are different, 2849 /// ArgPos will have the parameter index of the first different parameter. 2850 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2851 const FunctionProtoType *NewType, 2852 unsigned *ArgPos) { 2853 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2854 N = NewType->param_type_begin(), 2855 E = OldType->param_type_end(); 2856 O && (O != E); ++O, ++N) { 2857 if (!Context.hasSameType(O->getUnqualifiedType(), 2858 N->getUnqualifiedType())) { 2859 if (ArgPos) 2860 *ArgPos = O - OldType->param_type_begin(); 2861 return false; 2862 } 2863 } 2864 return true; 2865 } 2866 2867 /// CheckPointerConversion - Check the pointer conversion from the 2868 /// expression From to the type ToType. This routine checks for 2869 /// ambiguous or inaccessible derived-to-base pointer 2870 /// conversions for which IsPointerConversion has already returned 2871 /// true. It returns true and produces a diagnostic if there was an 2872 /// error, or returns false otherwise. 2873 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2874 CastKind &Kind, 2875 CXXCastPath& BasePath, 2876 bool IgnoreBaseAccess, 2877 bool Diagnose) { 2878 QualType FromType = From->getType(); 2879 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2880 2881 Kind = CK_BitCast; 2882 2883 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2884 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2885 Expr::NPCK_ZeroExpression) { 2886 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2887 DiagRuntimeBehavior(From->getExprLoc(), From, 2888 PDiag(diag::warn_impcast_bool_to_null_pointer) 2889 << ToType << From->getSourceRange()); 2890 else if (!isUnevaluatedContext()) 2891 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2892 << ToType << From->getSourceRange(); 2893 } 2894 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2895 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2896 QualType FromPointeeType = FromPtrType->getPointeeType(), 2897 ToPointeeType = ToPtrType->getPointeeType(); 2898 2899 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2900 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2901 // We must have a derived-to-base conversion. Check an 2902 // ambiguous or inaccessible conversion. 2903 unsigned InaccessibleID = 0; 2904 unsigned AmbigiousID = 0; 2905 if (Diagnose) { 2906 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2907 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2908 } 2909 if (CheckDerivedToBaseConversion( 2910 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2911 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2912 &BasePath, IgnoreBaseAccess)) 2913 return true; 2914 2915 // The conversion was successful. 2916 Kind = CK_DerivedToBase; 2917 } 2918 2919 if (Diagnose && !IsCStyleOrFunctionalCast && 2920 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2921 assert(getLangOpts().MSVCCompat && 2922 "this should only be possible with MSVCCompat!"); 2923 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2924 << From->getSourceRange(); 2925 } 2926 } 2927 } else if (const ObjCObjectPointerType *ToPtrType = 2928 ToType->getAs<ObjCObjectPointerType>()) { 2929 if (const ObjCObjectPointerType *FromPtrType = 2930 FromType->getAs<ObjCObjectPointerType>()) { 2931 // Objective-C++ conversions are always okay. 2932 // FIXME: We should have a different class of conversions for the 2933 // Objective-C++ implicit conversions. 2934 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2935 return false; 2936 } else if (FromType->isBlockPointerType()) { 2937 Kind = CK_BlockPointerToObjCPointerCast; 2938 } else { 2939 Kind = CK_CPointerToObjCPointerCast; 2940 } 2941 } else if (ToType->isBlockPointerType()) { 2942 if (!FromType->isBlockPointerType()) 2943 Kind = CK_AnyPointerToBlockPointerCast; 2944 } 2945 2946 // We shouldn't fall into this case unless it's valid for other 2947 // reasons. 2948 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2949 Kind = CK_NullToPointer; 2950 2951 return false; 2952 } 2953 2954 /// IsMemberPointerConversion - Determines whether the conversion of the 2955 /// expression From, which has the (possibly adjusted) type FromType, can be 2956 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2957 /// If so, returns true and places the converted type (that might differ from 2958 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2959 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2960 QualType ToType, 2961 bool InOverloadResolution, 2962 QualType &ConvertedType) { 2963 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2964 if (!ToTypePtr) 2965 return false; 2966 2967 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2968 if (From->isNullPointerConstant(Context, 2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2970 : Expr::NPC_ValueDependentIsNull)) { 2971 ConvertedType = ToType; 2972 return true; 2973 } 2974 2975 // Otherwise, both types have to be member pointers. 2976 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2977 if (!FromTypePtr) 2978 return false; 2979 2980 // A pointer to member of B can be converted to a pointer to member of D, 2981 // where D is derived from B (C++ 4.11p2). 2982 QualType FromClass(FromTypePtr->getClass(), 0); 2983 QualType ToClass(ToTypePtr->getClass(), 0); 2984 2985 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2986 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 2987 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2988 ToClass.getTypePtr()); 2989 return true; 2990 } 2991 2992 return false; 2993 } 2994 2995 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2996 /// expression From to the type ToType. This routine checks for ambiguous or 2997 /// virtual or inaccessible base-to-derived member pointer conversions 2998 /// for which IsMemberPointerConversion has already returned true. It returns 2999 /// true and produces a diagnostic if there was an error, or returns false 3000 /// otherwise. 3001 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3002 CastKind &Kind, 3003 CXXCastPath &BasePath, 3004 bool IgnoreBaseAccess) { 3005 QualType FromType = From->getType(); 3006 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3007 if (!FromPtrType) { 3008 // This must be a null pointer to member pointer conversion 3009 assert(From->isNullPointerConstant(Context, 3010 Expr::NPC_ValueDependentIsNull) && 3011 "Expr must be null pointer constant!"); 3012 Kind = CK_NullToMemberPointer; 3013 return false; 3014 } 3015 3016 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3017 assert(ToPtrType && "No member pointer cast has a target type " 3018 "that is not a member pointer."); 3019 3020 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3021 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3022 3023 // FIXME: What about dependent types? 3024 assert(FromClass->isRecordType() && "Pointer into non-class."); 3025 assert(ToClass->isRecordType() && "Pointer into non-class."); 3026 3027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3028 /*DetectVirtual=*/true); 3029 bool DerivationOkay = 3030 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3031 assert(DerivationOkay && 3032 "Should not have been called if derivation isn't OK."); 3033 (void)DerivationOkay; 3034 3035 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3036 getUnqualifiedType())) { 3037 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3038 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3039 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3040 return true; 3041 } 3042 3043 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3044 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3045 << FromClass << ToClass << QualType(VBase, 0) 3046 << From->getSourceRange(); 3047 return true; 3048 } 3049 3050 if (!IgnoreBaseAccess) 3051 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3052 Paths.front(), 3053 diag::err_downcast_from_inaccessible_base); 3054 3055 // Must be a base to derived member conversion. 3056 BuildBasePathArray(Paths, BasePath); 3057 Kind = CK_BaseToDerivedMemberPointer; 3058 return false; 3059 } 3060 3061 /// Determine whether the lifetime conversion between the two given 3062 /// qualifiers sets is nontrivial. 3063 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3064 Qualifiers ToQuals) { 3065 // Converting anything to const __unsafe_unretained is trivial. 3066 if (ToQuals.hasConst() && 3067 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3068 return false; 3069 3070 return true; 3071 } 3072 3073 /// IsQualificationConversion - Determines whether the conversion from 3074 /// an rvalue of type FromType to ToType is a qualification conversion 3075 /// (C++ 4.4). 3076 /// 3077 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3078 /// when the qualification conversion involves a change in the Objective-C 3079 /// object lifetime. 3080 bool 3081 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3082 bool CStyle, bool &ObjCLifetimeConversion) { 3083 FromType = Context.getCanonicalType(FromType); 3084 ToType = Context.getCanonicalType(ToType); 3085 ObjCLifetimeConversion = false; 3086 3087 // If FromType and ToType are the same type, this is not a 3088 // qualification conversion. 3089 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3090 return false; 3091 3092 // (C++ 4.4p4): 3093 // A conversion can add cv-qualifiers at levels other than the first 3094 // in multi-level pointers, subject to the following rules: [...] 3095 bool PreviousToQualsIncludeConst = true; 3096 bool UnwrappedAnyPointer = false; 3097 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3098 // Within each iteration of the loop, we check the qualifiers to 3099 // determine if this still looks like a qualification 3100 // conversion. Then, if all is well, we unwrap one more level of 3101 // pointers or pointers-to-members and do it all again 3102 // until there are no more pointers or pointers-to-members left to 3103 // unwrap. 3104 UnwrappedAnyPointer = true; 3105 3106 Qualifiers FromQuals = FromType.getQualifiers(); 3107 Qualifiers ToQuals = ToType.getQualifiers(); 3108 3109 // Ignore __unaligned qualifier if this type is void. 3110 if (ToType.getUnqualifiedType()->isVoidType()) 3111 FromQuals.removeUnaligned(); 3112 3113 // Objective-C ARC: 3114 // Check Objective-C lifetime conversions. 3115 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3116 UnwrappedAnyPointer) { 3117 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3118 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3119 ObjCLifetimeConversion = true; 3120 FromQuals.removeObjCLifetime(); 3121 ToQuals.removeObjCLifetime(); 3122 } else { 3123 // Qualification conversions cannot cast between different 3124 // Objective-C lifetime qualifiers. 3125 return false; 3126 } 3127 } 3128 3129 // Allow addition/removal of GC attributes but not changing GC attributes. 3130 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3131 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3132 FromQuals.removeObjCGCAttr(); 3133 ToQuals.removeObjCGCAttr(); 3134 } 3135 3136 // -- for every j > 0, if const is in cv 1,j then const is in cv 3137 // 2,j, and similarly for volatile. 3138 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3139 return false; 3140 3141 // -- if the cv 1,j and cv 2,j are different, then const is in 3142 // every cv for 0 < k < j. 3143 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3144 && !PreviousToQualsIncludeConst) 3145 return false; 3146 3147 // Keep track of whether all prior cv-qualifiers in the "to" type 3148 // include const. 3149 PreviousToQualsIncludeConst 3150 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3151 } 3152 3153 // Allows address space promotion by language rules implemented in 3154 // Type::Qualifiers::isAddressSpaceSupersetOf. 3155 Qualifiers FromQuals = FromType.getQualifiers(); 3156 Qualifiers ToQuals = ToType.getQualifiers(); 3157 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3158 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3159 return false; 3160 } 3161 3162 // We are left with FromType and ToType being the pointee types 3163 // after unwrapping the original FromType and ToType the same number 3164 // of types. If we unwrapped any pointers, and if FromType and 3165 // ToType have the same unqualified type (since we checked 3166 // qualifiers above), then this is a qualification conversion. 3167 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3168 } 3169 3170 /// - Determine whether this is a conversion from a scalar type to an 3171 /// atomic type. 3172 /// 3173 /// If successful, updates \c SCS's second and third steps in the conversion 3174 /// sequence to finish the conversion. 3175 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3176 bool InOverloadResolution, 3177 StandardConversionSequence &SCS, 3178 bool CStyle) { 3179 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3180 if (!ToAtomic) 3181 return false; 3182 3183 StandardConversionSequence InnerSCS; 3184 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3185 InOverloadResolution, InnerSCS, 3186 CStyle, /*AllowObjCWritebackConversion=*/false)) 3187 return false; 3188 3189 SCS.Second = InnerSCS.Second; 3190 SCS.setToType(1, InnerSCS.getToType(1)); 3191 SCS.Third = InnerSCS.Third; 3192 SCS.QualificationIncludesObjCLifetime 3193 = InnerSCS.QualificationIncludesObjCLifetime; 3194 SCS.setToType(2, InnerSCS.getToType(2)); 3195 return true; 3196 } 3197 3198 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3199 CXXConstructorDecl *Constructor, 3200 QualType Type) { 3201 const FunctionProtoType *CtorType = 3202 Constructor->getType()->getAs<FunctionProtoType>(); 3203 if (CtorType->getNumParams() > 0) { 3204 QualType FirstArg = CtorType->getParamType(0); 3205 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3206 return true; 3207 } 3208 return false; 3209 } 3210 3211 static OverloadingResult 3212 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3213 CXXRecordDecl *To, 3214 UserDefinedConversionSequence &User, 3215 OverloadCandidateSet &CandidateSet, 3216 bool AllowExplicit) { 3217 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3218 for (auto *D : S.LookupConstructors(To)) { 3219 auto Info = getConstructorInfo(D); 3220 if (!Info) 3221 continue; 3222 3223 bool Usable = !Info.Constructor->isInvalidDecl() && 3224 S.isInitListConstructor(Info.Constructor) && 3225 (AllowExplicit || !Info.Constructor->isExplicit()); 3226 if (Usable) { 3227 // If the first argument is (a reference to) the target type, 3228 // suppress conversions. 3229 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3230 S.Context, Info.Constructor, ToType); 3231 if (Info.ConstructorTmpl) 3232 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3233 /*ExplicitArgs*/ nullptr, From, 3234 CandidateSet, SuppressUserConversions); 3235 else 3236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3237 CandidateSet, SuppressUserConversions); 3238 } 3239 } 3240 3241 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3242 3243 OverloadCandidateSet::iterator Best; 3244 switch (auto Result = 3245 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3246 case OR_Deleted: 3247 case OR_Success: { 3248 // Record the standard conversion we used and the conversion function. 3249 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3250 QualType ThisType = Constructor->getThisType(S.Context); 3251 // Initializer lists don't have conversions as such. 3252 User.Before.setAsIdentityConversion(); 3253 User.HadMultipleCandidates = HadMultipleCandidates; 3254 User.ConversionFunction = Constructor; 3255 User.FoundConversionFunction = Best->FoundDecl; 3256 User.After.setAsIdentityConversion(); 3257 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3258 User.After.setAllToTypes(ToType); 3259 return Result; 3260 } 3261 3262 case OR_No_Viable_Function: 3263 return OR_No_Viable_Function; 3264 case OR_Ambiguous: 3265 return OR_Ambiguous; 3266 } 3267 3268 llvm_unreachable("Invalid OverloadResult!"); 3269 } 3270 3271 /// Determines whether there is a user-defined conversion sequence 3272 /// (C++ [over.ics.user]) that converts expression From to the type 3273 /// ToType. If such a conversion exists, User will contain the 3274 /// user-defined conversion sequence that performs such a conversion 3275 /// and this routine will return true. Otherwise, this routine returns 3276 /// false and User is unspecified. 3277 /// 3278 /// \param AllowExplicit true if the conversion should consider C++0x 3279 /// "explicit" conversion functions as well as non-explicit conversion 3280 /// functions (C++0x [class.conv.fct]p2). 3281 /// 3282 /// \param AllowObjCConversionOnExplicit true if the conversion should 3283 /// allow an extra Objective-C pointer conversion on uses of explicit 3284 /// constructors. Requires \c AllowExplicit to also be set. 3285 static OverloadingResult 3286 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3287 UserDefinedConversionSequence &User, 3288 OverloadCandidateSet &CandidateSet, 3289 bool AllowExplicit, 3290 bool AllowObjCConversionOnExplicit) { 3291 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3292 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3293 3294 // Whether we will only visit constructors. 3295 bool ConstructorsOnly = false; 3296 3297 // If the type we are conversion to is a class type, enumerate its 3298 // constructors. 3299 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3300 // C++ [over.match.ctor]p1: 3301 // When objects of class type are direct-initialized (8.5), or 3302 // copy-initialized from an expression of the same or a 3303 // derived class type (8.5), overload resolution selects the 3304 // constructor. [...] For copy-initialization, the candidate 3305 // functions are all the converting constructors (12.3.1) of 3306 // that class. The argument list is the expression-list within 3307 // the parentheses of the initializer. 3308 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3309 (From->getType()->getAs<RecordType>() && 3310 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3311 ConstructorsOnly = true; 3312 3313 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3314 // We're not going to find any constructors. 3315 } else if (CXXRecordDecl *ToRecordDecl 3316 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3317 3318 Expr **Args = &From; 3319 unsigned NumArgs = 1; 3320 bool ListInitializing = false; 3321 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3322 // But first, see if there is an init-list-constructor that will work. 3323 OverloadingResult Result = IsInitializerListConstructorConversion( 3324 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3325 if (Result != OR_No_Viable_Function) 3326 return Result; 3327 // Never mind. 3328 CandidateSet.clear( 3329 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3330 3331 // If we're list-initializing, we pass the individual elements as 3332 // arguments, not the entire list. 3333 Args = InitList->getInits(); 3334 NumArgs = InitList->getNumInits(); 3335 ListInitializing = true; 3336 } 3337 3338 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3339 auto Info = getConstructorInfo(D); 3340 if (!Info) 3341 continue; 3342 3343 bool Usable = !Info.Constructor->isInvalidDecl(); 3344 if (ListInitializing) 3345 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3346 else 3347 Usable = Usable && 3348 Info.Constructor->isConvertingConstructor(AllowExplicit); 3349 if (Usable) { 3350 bool SuppressUserConversions = !ConstructorsOnly; 3351 if (SuppressUserConversions && ListInitializing) { 3352 SuppressUserConversions = false; 3353 if (NumArgs == 1) { 3354 // If the first argument is (a reference to) the target type, 3355 // suppress conversions. 3356 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3357 S.Context, Info.Constructor, ToType); 3358 } 3359 } 3360 if (Info.ConstructorTmpl) 3361 S.AddTemplateOverloadCandidate( 3362 Info.ConstructorTmpl, Info.FoundDecl, 3363 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3364 CandidateSet, SuppressUserConversions); 3365 else 3366 // Allow one user-defined conversion when user specifies a 3367 // From->ToType conversion via an static cast (c-style, etc). 3368 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3369 llvm::makeArrayRef(Args, NumArgs), 3370 CandidateSet, SuppressUserConversions); 3371 } 3372 } 3373 } 3374 } 3375 3376 // Enumerate conversion functions, if we're allowed to. 3377 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3378 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3379 // No conversion functions from incomplete types. 3380 } else if (const RecordType *FromRecordType = 3381 From->getType()->getAs<RecordType>()) { 3382 if (CXXRecordDecl *FromRecordDecl 3383 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3384 // Add all of the conversion functions as candidates. 3385 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3386 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3387 DeclAccessPair FoundDecl = I.getPair(); 3388 NamedDecl *D = FoundDecl.getDecl(); 3389 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3390 if (isa<UsingShadowDecl>(D)) 3391 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3392 3393 CXXConversionDecl *Conv; 3394 FunctionTemplateDecl *ConvTemplate; 3395 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3396 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3397 else 3398 Conv = cast<CXXConversionDecl>(D); 3399 3400 if (AllowExplicit || !Conv->isExplicit()) { 3401 if (ConvTemplate) 3402 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3403 ActingContext, From, ToType, 3404 CandidateSet, 3405 AllowObjCConversionOnExplicit); 3406 else 3407 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3408 From, ToType, CandidateSet, 3409 AllowObjCConversionOnExplicit); 3410 } 3411 } 3412 } 3413 } 3414 3415 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3416 3417 OverloadCandidateSet::iterator Best; 3418 switch (auto Result = 3419 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3420 case OR_Success: 3421 case OR_Deleted: 3422 // Record the standard conversion we used and the conversion function. 3423 if (CXXConstructorDecl *Constructor 3424 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3425 // C++ [over.ics.user]p1: 3426 // If the user-defined conversion is specified by a 3427 // constructor (12.3.1), the initial standard conversion 3428 // sequence converts the source type to the type required by 3429 // the argument of the constructor. 3430 // 3431 QualType ThisType = Constructor->getThisType(S.Context); 3432 if (isa<InitListExpr>(From)) { 3433 // Initializer lists don't have conversions as such. 3434 User.Before.setAsIdentityConversion(); 3435 } else { 3436 if (Best->Conversions[0].isEllipsis()) 3437 User.EllipsisConversion = true; 3438 else { 3439 User.Before = Best->Conversions[0].Standard; 3440 User.EllipsisConversion = false; 3441 } 3442 } 3443 User.HadMultipleCandidates = HadMultipleCandidates; 3444 User.ConversionFunction = Constructor; 3445 User.FoundConversionFunction = Best->FoundDecl; 3446 User.After.setAsIdentityConversion(); 3447 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3448 User.After.setAllToTypes(ToType); 3449 return Result; 3450 } 3451 if (CXXConversionDecl *Conversion 3452 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3453 // C++ [over.ics.user]p1: 3454 // 3455 // [...] If the user-defined conversion is specified by a 3456 // conversion function (12.3.2), the initial standard 3457 // conversion sequence converts the source type to the 3458 // implicit object parameter of the conversion function. 3459 User.Before = Best->Conversions[0].Standard; 3460 User.HadMultipleCandidates = HadMultipleCandidates; 3461 User.ConversionFunction = Conversion; 3462 User.FoundConversionFunction = Best->FoundDecl; 3463 User.EllipsisConversion = false; 3464 3465 // C++ [over.ics.user]p2: 3466 // The second standard conversion sequence converts the 3467 // result of the user-defined conversion to the target type 3468 // for the sequence. Since an implicit conversion sequence 3469 // is an initialization, the special rules for 3470 // initialization by user-defined conversion apply when 3471 // selecting the best user-defined conversion for a 3472 // user-defined conversion sequence (see 13.3.3 and 3473 // 13.3.3.1). 3474 User.After = Best->FinalConversion; 3475 return Result; 3476 } 3477 llvm_unreachable("Not a constructor or conversion function?"); 3478 3479 case OR_No_Viable_Function: 3480 return OR_No_Viable_Function; 3481 3482 case OR_Ambiguous: 3483 return OR_Ambiguous; 3484 } 3485 3486 llvm_unreachable("Invalid OverloadResult!"); 3487 } 3488 3489 bool 3490 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3491 ImplicitConversionSequence ICS; 3492 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3493 OverloadCandidateSet::CSK_Normal); 3494 OverloadingResult OvResult = 3495 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3496 CandidateSet, false, false); 3497 if (OvResult == OR_Ambiguous) 3498 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3499 << From->getType() << ToType << From->getSourceRange(); 3500 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3501 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3502 diag::err_typecheck_nonviable_condition_incomplete, 3503 From->getType(), From->getSourceRange())) 3504 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3505 << false << From->getType() << From->getSourceRange() << ToType; 3506 } else 3507 return false; 3508 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3509 return true; 3510 } 3511 3512 /// Compare the user-defined conversion functions or constructors 3513 /// of two user-defined conversion sequences to determine whether any ordering 3514 /// is possible. 3515 static ImplicitConversionSequence::CompareKind 3516 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3517 FunctionDecl *Function2) { 3518 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3519 return ImplicitConversionSequence::Indistinguishable; 3520 3521 // Objective-C++: 3522 // If both conversion functions are implicitly-declared conversions from 3523 // a lambda closure type to a function pointer and a block pointer, 3524 // respectively, always prefer the conversion to a function pointer, 3525 // because the function pointer is more lightweight and is more likely 3526 // to keep code working. 3527 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3528 if (!Conv1) 3529 return ImplicitConversionSequence::Indistinguishable; 3530 3531 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3532 if (!Conv2) 3533 return ImplicitConversionSequence::Indistinguishable; 3534 3535 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3536 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3537 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3538 if (Block1 != Block2) 3539 return Block1 ? ImplicitConversionSequence::Worse 3540 : ImplicitConversionSequence::Better; 3541 } 3542 3543 return ImplicitConversionSequence::Indistinguishable; 3544 } 3545 3546 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3547 const ImplicitConversionSequence &ICS) { 3548 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3549 (ICS.isUserDefined() && 3550 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3551 } 3552 3553 /// CompareImplicitConversionSequences - Compare two implicit 3554 /// conversion sequences to determine whether one is better than the 3555 /// other or if they are indistinguishable (C++ 13.3.3.2). 3556 static ImplicitConversionSequence::CompareKind 3557 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3558 const ImplicitConversionSequence& ICS1, 3559 const ImplicitConversionSequence& ICS2) 3560 { 3561 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3562 // conversion sequences (as defined in 13.3.3.1) 3563 // -- a standard conversion sequence (13.3.3.1.1) is a better 3564 // conversion sequence than a user-defined conversion sequence or 3565 // an ellipsis conversion sequence, and 3566 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3567 // conversion sequence than an ellipsis conversion sequence 3568 // (13.3.3.1.3). 3569 // 3570 // C++0x [over.best.ics]p10: 3571 // For the purpose of ranking implicit conversion sequences as 3572 // described in 13.3.3.2, the ambiguous conversion sequence is 3573 // treated as a user-defined sequence that is indistinguishable 3574 // from any other user-defined conversion sequence. 3575 3576 // String literal to 'char *' conversion has been deprecated in C++03. It has 3577 // been removed from C++11. We still accept this conversion, if it happens at 3578 // the best viable function. Otherwise, this conversion is considered worse 3579 // than ellipsis conversion. Consider this as an extension; this is not in the 3580 // standard. For example: 3581 // 3582 // int &f(...); // #1 3583 // void f(char*); // #2 3584 // void g() { int &r = f("foo"); } 3585 // 3586 // In C++03, we pick #2 as the best viable function. 3587 // In C++11, we pick #1 as the best viable function, because ellipsis 3588 // conversion is better than string-literal to char* conversion (since there 3589 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3590 // convert arguments, #2 would be the best viable function in C++11. 3591 // If the best viable function has this conversion, a warning will be issued 3592 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3593 3594 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3595 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3597 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3598 ? ImplicitConversionSequence::Worse 3599 : ImplicitConversionSequence::Better; 3600 3601 if (ICS1.getKindRank() < ICS2.getKindRank()) 3602 return ImplicitConversionSequence::Better; 3603 if (ICS2.getKindRank() < ICS1.getKindRank()) 3604 return ImplicitConversionSequence::Worse; 3605 3606 // The following checks require both conversion sequences to be of 3607 // the same kind. 3608 if (ICS1.getKind() != ICS2.getKind()) 3609 return ImplicitConversionSequence::Indistinguishable; 3610 3611 ImplicitConversionSequence::CompareKind Result = 3612 ImplicitConversionSequence::Indistinguishable; 3613 3614 // Two implicit conversion sequences of the same form are 3615 // indistinguishable conversion sequences unless one of the 3616 // following rules apply: (C++ 13.3.3.2p3): 3617 3618 // List-initialization sequence L1 is a better conversion sequence than 3619 // list-initialization sequence L2 if: 3620 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3621 // if not that, 3622 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3623 // and N1 is smaller than N2., 3624 // even if one of the other rules in this paragraph would otherwise apply. 3625 if (!ICS1.isBad()) { 3626 if (ICS1.isStdInitializerListElement() && 3627 !ICS2.isStdInitializerListElement()) 3628 return ImplicitConversionSequence::Better; 3629 if (!ICS1.isStdInitializerListElement() && 3630 ICS2.isStdInitializerListElement()) 3631 return ImplicitConversionSequence::Worse; 3632 } 3633 3634 if (ICS1.isStandard()) 3635 // Standard conversion sequence S1 is a better conversion sequence than 3636 // standard conversion sequence S2 if [...] 3637 Result = CompareStandardConversionSequences(S, Loc, 3638 ICS1.Standard, ICS2.Standard); 3639 else if (ICS1.isUserDefined()) { 3640 // User-defined conversion sequence U1 is a better conversion 3641 // sequence than another user-defined conversion sequence U2 if 3642 // they contain the same user-defined conversion function or 3643 // constructor and if the second standard conversion sequence of 3644 // U1 is better than the second standard conversion sequence of 3645 // U2 (C++ 13.3.3.2p3). 3646 if (ICS1.UserDefined.ConversionFunction == 3647 ICS2.UserDefined.ConversionFunction) 3648 Result = CompareStandardConversionSequences(S, Loc, 3649 ICS1.UserDefined.After, 3650 ICS2.UserDefined.After); 3651 else 3652 Result = compareConversionFunctions(S, 3653 ICS1.UserDefined.ConversionFunction, 3654 ICS2.UserDefined.ConversionFunction); 3655 } 3656 3657 return Result; 3658 } 3659 3660 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3661 // determine if one is a proper subset of the other. 3662 static ImplicitConversionSequence::CompareKind 3663 compareStandardConversionSubsets(ASTContext &Context, 3664 const StandardConversionSequence& SCS1, 3665 const StandardConversionSequence& SCS2) { 3666 ImplicitConversionSequence::CompareKind Result 3667 = ImplicitConversionSequence::Indistinguishable; 3668 3669 // the identity conversion sequence is considered to be a subsequence of 3670 // any non-identity conversion sequence 3671 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3672 return ImplicitConversionSequence::Better; 3673 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3674 return ImplicitConversionSequence::Worse; 3675 3676 if (SCS1.Second != SCS2.Second) { 3677 if (SCS1.Second == ICK_Identity) 3678 Result = ImplicitConversionSequence::Better; 3679 else if (SCS2.Second == ICK_Identity) 3680 Result = ImplicitConversionSequence::Worse; 3681 else 3682 return ImplicitConversionSequence::Indistinguishable; 3683 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3684 return ImplicitConversionSequence::Indistinguishable; 3685 3686 if (SCS1.Third == SCS2.Third) { 3687 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3688 : ImplicitConversionSequence::Indistinguishable; 3689 } 3690 3691 if (SCS1.Third == ICK_Identity) 3692 return Result == ImplicitConversionSequence::Worse 3693 ? ImplicitConversionSequence::Indistinguishable 3694 : ImplicitConversionSequence::Better; 3695 3696 if (SCS2.Third == ICK_Identity) 3697 return Result == ImplicitConversionSequence::Better 3698 ? ImplicitConversionSequence::Indistinguishable 3699 : ImplicitConversionSequence::Worse; 3700 3701 return ImplicitConversionSequence::Indistinguishable; 3702 } 3703 3704 /// Determine whether one of the given reference bindings is better 3705 /// than the other based on what kind of bindings they are. 3706 static bool 3707 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3708 const StandardConversionSequence &SCS2) { 3709 // C++0x [over.ics.rank]p3b4: 3710 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3711 // implicit object parameter of a non-static member function declared 3712 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3713 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3714 // lvalue reference to a function lvalue and S2 binds an rvalue 3715 // reference*. 3716 // 3717 // FIXME: Rvalue references. We're going rogue with the above edits, 3718 // because the semantics in the current C++0x working paper (N3225 at the 3719 // time of this writing) break the standard definition of std::forward 3720 // and std::reference_wrapper when dealing with references to functions. 3721 // Proposed wording changes submitted to CWG for consideration. 3722 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3723 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3724 return false; 3725 3726 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3727 SCS2.IsLvalueReference) || 3728 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3729 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3730 } 3731 3732 /// CompareStandardConversionSequences - Compare two standard 3733 /// conversion sequences to determine whether one is better than the 3734 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3735 static ImplicitConversionSequence::CompareKind 3736 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3737 const StandardConversionSequence& SCS1, 3738 const StandardConversionSequence& SCS2) 3739 { 3740 // Standard conversion sequence S1 is a better conversion sequence 3741 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3742 3743 // -- S1 is a proper subsequence of S2 (comparing the conversion 3744 // sequences in the canonical form defined by 13.3.3.1.1, 3745 // excluding any Lvalue Transformation; the identity conversion 3746 // sequence is considered to be a subsequence of any 3747 // non-identity conversion sequence) or, if not that, 3748 if (ImplicitConversionSequence::CompareKind CK 3749 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3750 return CK; 3751 3752 // -- the rank of S1 is better than the rank of S2 (by the rules 3753 // defined below), or, if not that, 3754 ImplicitConversionRank Rank1 = SCS1.getRank(); 3755 ImplicitConversionRank Rank2 = SCS2.getRank(); 3756 if (Rank1 < Rank2) 3757 return ImplicitConversionSequence::Better; 3758 else if (Rank2 < Rank1) 3759 return ImplicitConversionSequence::Worse; 3760 3761 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3762 // are indistinguishable unless one of the following rules 3763 // applies: 3764 3765 // A conversion that is not a conversion of a pointer, or 3766 // pointer to member, to bool is better than another conversion 3767 // that is such a conversion. 3768 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3769 return SCS2.isPointerConversionToBool() 3770 ? ImplicitConversionSequence::Better 3771 : ImplicitConversionSequence::Worse; 3772 3773 // C++ [over.ics.rank]p4b2: 3774 // 3775 // If class B is derived directly or indirectly from class A, 3776 // conversion of B* to A* is better than conversion of B* to 3777 // void*, and conversion of A* to void* is better than conversion 3778 // of B* to void*. 3779 bool SCS1ConvertsToVoid 3780 = SCS1.isPointerConversionToVoidPointer(S.Context); 3781 bool SCS2ConvertsToVoid 3782 = SCS2.isPointerConversionToVoidPointer(S.Context); 3783 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3784 // Exactly one of the conversion sequences is a conversion to 3785 // a void pointer; it's the worse conversion. 3786 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3787 : ImplicitConversionSequence::Worse; 3788 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3789 // Neither conversion sequence converts to a void pointer; compare 3790 // their derived-to-base conversions. 3791 if (ImplicitConversionSequence::CompareKind DerivedCK 3792 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3793 return DerivedCK; 3794 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3795 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3796 // Both conversion sequences are conversions to void 3797 // pointers. Compare the source types to determine if there's an 3798 // inheritance relationship in their sources. 3799 QualType FromType1 = SCS1.getFromType(); 3800 QualType FromType2 = SCS2.getFromType(); 3801 3802 // Adjust the types we're converting from via the array-to-pointer 3803 // conversion, if we need to. 3804 if (SCS1.First == ICK_Array_To_Pointer) 3805 FromType1 = S.Context.getArrayDecayedType(FromType1); 3806 if (SCS2.First == ICK_Array_To_Pointer) 3807 FromType2 = S.Context.getArrayDecayedType(FromType2); 3808 3809 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3810 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3811 3812 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3813 return ImplicitConversionSequence::Better; 3814 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3815 return ImplicitConversionSequence::Worse; 3816 3817 // Objective-C++: If one interface is more specific than the 3818 // other, it is the better one. 3819 const ObjCObjectPointerType* FromObjCPtr1 3820 = FromType1->getAs<ObjCObjectPointerType>(); 3821 const ObjCObjectPointerType* FromObjCPtr2 3822 = FromType2->getAs<ObjCObjectPointerType>(); 3823 if (FromObjCPtr1 && FromObjCPtr2) { 3824 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3825 FromObjCPtr2); 3826 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3827 FromObjCPtr1); 3828 if (AssignLeft != AssignRight) { 3829 return AssignLeft? ImplicitConversionSequence::Better 3830 : ImplicitConversionSequence::Worse; 3831 } 3832 } 3833 } 3834 3835 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3836 // bullet 3). 3837 if (ImplicitConversionSequence::CompareKind QualCK 3838 = CompareQualificationConversions(S, SCS1, SCS2)) 3839 return QualCK; 3840 3841 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3842 // Check for a better reference binding based on the kind of bindings. 3843 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3844 return ImplicitConversionSequence::Better; 3845 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3846 return ImplicitConversionSequence::Worse; 3847 3848 // C++ [over.ics.rank]p3b4: 3849 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3850 // which the references refer are the same type except for 3851 // top-level cv-qualifiers, and the type to which the reference 3852 // initialized by S2 refers is more cv-qualified than the type 3853 // to which the reference initialized by S1 refers. 3854 QualType T1 = SCS1.getToType(2); 3855 QualType T2 = SCS2.getToType(2); 3856 T1 = S.Context.getCanonicalType(T1); 3857 T2 = S.Context.getCanonicalType(T2); 3858 Qualifiers T1Quals, T2Quals; 3859 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3860 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3861 if (UnqualT1 == UnqualT2) { 3862 // Objective-C++ ARC: If the references refer to objects with different 3863 // lifetimes, prefer bindings that don't change lifetime. 3864 if (SCS1.ObjCLifetimeConversionBinding != 3865 SCS2.ObjCLifetimeConversionBinding) { 3866 return SCS1.ObjCLifetimeConversionBinding 3867 ? ImplicitConversionSequence::Worse 3868 : ImplicitConversionSequence::Better; 3869 } 3870 3871 // If the type is an array type, promote the element qualifiers to the 3872 // type for comparison. 3873 if (isa<ArrayType>(T1) && T1Quals) 3874 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3875 if (isa<ArrayType>(T2) && T2Quals) 3876 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3877 if (T2.isMoreQualifiedThan(T1)) 3878 return ImplicitConversionSequence::Better; 3879 else if (T1.isMoreQualifiedThan(T2)) 3880 return ImplicitConversionSequence::Worse; 3881 } 3882 } 3883 3884 // In Microsoft mode, prefer an integral conversion to a 3885 // floating-to-integral conversion if the integral conversion 3886 // is between types of the same size. 3887 // For example: 3888 // void f(float); 3889 // void f(int); 3890 // int main { 3891 // long a; 3892 // f(a); 3893 // } 3894 // Here, MSVC will call f(int) instead of generating a compile error 3895 // as clang will do in standard mode. 3896 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3897 SCS2.Second == ICK_Floating_Integral && 3898 S.Context.getTypeSize(SCS1.getFromType()) == 3899 S.Context.getTypeSize(SCS1.getToType(2))) 3900 return ImplicitConversionSequence::Better; 3901 3902 return ImplicitConversionSequence::Indistinguishable; 3903 } 3904 3905 /// CompareQualificationConversions - Compares two standard conversion 3906 /// sequences to determine whether they can be ranked based on their 3907 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3908 static ImplicitConversionSequence::CompareKind 3909 CompareQualificationConversions(Sema &S, 3910 const StandardConversionSequence& SCS1, 3911 const StandardConversionSequence& SCS2) { 3912 // C++ 13.3.3.2p3: 3913 // -- S1 and S2 differ only in their qualification conversion and 3914 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3915 // cv-qualification signature of type T1 is a proper subset of 3916 // the cv-qualification signature of type T2, and S1 is not the 3917 // deprecated string literal array-to-pointer conversion (4.2). 3918 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3919 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3920 return ImplicitConversionSequence::Indistinguishable; 3921 3922 // FIXME: the example in the standard doesn't use a qualification 3923 // conversion (!) 3924 QualType T1 = SCS1.getToType(2); 3925 QualType T2 = SCS2.getToType(2); 3926 T1 = S.Context.getCanonicalType(T1); 3927 T2 = S.Context.getCanonicalType(T2); 3928 Qualifiers T1Quals, T2Quals; 3929 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3930 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3931 3932 // If the types are the same, we won't learn anything by unwrapped 3933 // them. 3934 if (UnqualT1 == UnqualT2) 3935 return ImplicitConversionSequence::Indistinguishable; 3936 3937 // If the type is an array type, promote the element qualifiers to the type 3938 // for comparison. 3939 if (isa<ArrayType>(T1) && T1Quals) 3940 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3941 if (isa<ArrayType>(T2) && T2Quals) 3942 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3943 3944 ImplicitConversionSequence::CompareKind Result 3945 = ImplicitConversionSequence::Indistinguishable; 3946 3947 // Objective-C++ ARC: 3948 // Prefer qualification conversions not involving a change in lifetime 3949 // to qualification conversions that do not change lifetime. 3950 if (SCS1.QualificationIncludesObjCLifetime != 3951 SCS2.QualificationIncludesObjCLifetime) { 3952 Result = SCS1.QualificationIncludesObjCLifetime 3953 ? ImplicitConversionSequence::Worse 3954 : ImplicitConversionSequence::Better; 3955 } 3956 3957 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 3958 // Within each iteration of the loop, we check the qualifiers to 3959 // determine if this still looks like a qualification 3960 // conversion. Then, if all is well, we unwrap one more level of 3961 // pointers or pointers-to-members and do it all again 3962 // until there are no more pointers or pointers-to-members left 3963 // to unwrap. This essentially mimics what 3964 // IsQualificationConversion does, but here we're checking for a 3965 // strict subset of qualifiers. 3966 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3967 // The qualifiers are the same, so this doesn't tell us anything 3968 // about how the sequences rank. 3969 ; 3970 else if (T2.isMoreQualifiedThan(T1)) { 3971 // T1 has fewer qualifiers, so it could be the better sequence. 3972 if (Result == ImplicitConversionSequence::Worse) 3973 // Neither has qualifiers that are a subset of the other's 3974 // qualifiers. 3975 return ImplicitConversionSequence::Indistinguishable; 3976 3977 Result = ImplicitConversionSequence::Better; 3978 } else if (T1.isMoreQualifiedThan(T2)) { 3979 // T2 has fewer qualifiers, so it could be the better sequence. 3980 if (Result == ImplicitConversionSequence::Better) 3981 // Neither has qualifiers that are a subset of the other's 3982 // qualifiers. 3983 return ImplicitConversionSequence::Indistinguishable; 3984 3985 Result = ImplicitConversionSequence::Worse; 3986 } else { 3987 // Qualifiers are disjoint. 3988 return ImplicitConversionSequence::Indistinguishable; 3989 } 3990 3991 // If the types after this point are equivalent, we're done. 3992 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3993 break; 3994 } 3995 3996 // Check that the winning standard conversion sequence isn't using 3997 // the deprecated string literal array to pointer conversion. 3998 switch (Result) { 3999 case ImplicitConversionSequence::Better: 4000 if (SCS1.DeprecatedStringLiteralToCharPtr) 4001 Result = ImplicitConversionSequence::Indistinguishable; 4002 break; 4003 4004 case ImplicitConversionSequence::Indistinguishable: 4005 break; 4006 4007 case ImplicitConversionSequence::Worse: 4008 if (SCS2.DeprecatedStringLiteralToCharPtr) 4009 Result = ImplicitConversionSequence::Indistinguishable; 4010 break; 4011 } 4012 4013 return Result; 4014 } 4015 4016 /// CompareDerivedToBaseConversions - Compares two standard conversion 4017 /// sequences to determine whether they can be ranked based on their 4018 /// various kinds of derived-to-base conversions (C++ 4019 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4020 /// conversions between Objective-C interface types. 4021 static ImplicitConversionSequence::CompareKind 4022 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4023 const StandardConversionSequence& SCS1, 4024 const StandardConversionSequence& SCS2) { 4025 QualType FromType1 = SCS1.getFromType(); 4026 QualType ToType1 = SCS1.getToType(1); 4027 QualType FromType2 = SCS2.getFromType(); 4028 QualType ToType2 = SCS2.getToType(1); 4029 4030 // Adjust the types we're converting from via the array-to-pointer 4031 // conversion, if we need to. 4032 if (SCS1.First == ICK_Array_To_Pointer) 4033 FromType1 = S.Context.getArrayDecayedType(FromType1); 4034 if (SCS2.First == ICK_Array_To_Pointer) 4035 FromType2 = S.Context.getArrayDecayedType(FromType2); 4036 4037 // Canonicalize all of the types. 4038 FromType1 = S.Context.getCanonicalType(FromType1); 4039 ToType1 = S.Context.getCanonicalType(ToType1); 4040 FromType2 = S.Context.getCanonicalType(FromType2); 4041 ToType2 = S.Context.getCanonicalType(ToType2); 4042 4043 // C++ [over.ics.rank]p4b3: 4044 // 4045 // If class B is derived directly or indirectly from class A and 4046 // class C is derived directly or indirectly from B, 4047 // 4048 // Compare based on pointer conversions. 4049 if (SCS1.Second == ICK_Pointer_Conversion && 4050 SCS2.Second == ICK_Pointer_Conversion && 4051 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4052 FromType1->isPointerType() && FromType2->isPointerType() && 4053 ToType1->isPointerType() && ToType2->isPointerType()) { 4054 QualType FromPointee1 4055 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4056 QualType ToPointee1 4057 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4058 QualType FromPointee2 4059 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4060 QualType ToPointee2 4061 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4062 4063 // -- conversion of C* to B* is better than conversion of C* to A*, 4064 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4065 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4066 return ImplicitConversionSequence::Better; 4067 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4068 return ImplicitConversionSequence::Worse; 4069 } 4070 4071 // -- conversion of B* to A* is better than conversion of C* to A*, 4072 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4073 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4074 return ImplicitConversionSequence::Better; 4075 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4076 return ImplicitConversionSequence::Worse; 4077 } 4078 } else if (SCS1.Second == ICK_Pointer_Conversion && 4079 SCS2.Second == ICK_Pointer_Conversion) { 4080 const ObjCObjectPointerType *FromPtr1 4081 = FromType1->getAs<ObjCObjectPointerType>(); 4082 const ObjCObjectPointerType *FromPtr2 4083 = FromType2->getAs<ObjCObjectPointerType>(); 4084 const ObjCObjectPointerType *ToPtr1 4085 = ToType1->getAs<ObjCObjectPointerType>(); 4086 const ObjCObjectPointerType *ToPtr2 4087 = ToType2->getAs<ObjCObjectPointerType>(); 4088 4089 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4090 // Apply the same conversion ranking rules for Objective-C pointer types 4091 // that we do for C++ pointers to class types. However, we employ the 4092 // Objective-C pseudo-subtyping relationship used for assignment of 4093 // Objective-C pointer types. 4094 bool FromAssignLeft 4095 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4096 bool FromAssignRight 4097 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4098 bool ToAssignLeft 4099 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4100 bool ToAssignRight 4101 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4102 4103 // A conversion to an a non-id object pointer type or qualified 'id' 4104 // type is better than a conversion to 'id'. 4105 if (ToPtr1->isObjCIdType() && 4106 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4107 return ImplicitConversionSequence::Worse; 4108 if (ToPtr2->isObjCIdType() && 4109 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4110 return ImplicitConversionSequence::Better; 4111 4112 // A conversion to a non-id object pointer type is better than a 4113 // conversion to a qualified 'id' type 4114 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4115 return ImplicitConversionSequence::Worse; 4116 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4117 return ImplicitConversionSequence::Better; 4118 4119 // A conversion to an a non-Class object pointer type or qualified 'Class' 4120 // type is better than a conversion to 'Class'. 4121 if (ToPtr1->isObjCClassType() && 4122 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4123 return ImplicitConversionSequence::Worse; 4124 if (ToPtr2->isObjCClassType() && 4125 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4126 return ImplicitConversionSequence::Better; 4127 4128 // A conversion to a non-Class object pointer type is better than a 4129 // conversion to a qualified 'Class' type. 4130 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4131 return ImplicitConversionSequence::Worse; 4132 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4133 return ImplicitConversionSequence::Better; 4134 4135 // -- "conversion of C* to B* is better than conversion of C* to A*," 4136 if (S.Context.hasSameType(FromType1, FromType2) && 4137 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4138 (ToAssignLeft != ToAssignRight)) { 4139 if (FromPtr1->isSpecialized()) { 4140 // "conversion of B<A> * to B * is better than conversion of B * to 4141 // C *. 4142 bool IsFirstSame = 4143 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4144 bool IsSecondSame = 4145 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4146 if (IsFirstSame) { 4147 if (!IsSecondSame) 4148 return ImplicitConversionSequence::Better; 4149 } else if (IsSecondSame) 4150 return ImplicitConversionSequence::Worse; 4151 } 4152 return ToAssignLeft? ImplicitConversionSequence::Worse 4153 : ImplicitConversionSequence::Better; 4154 } 4155 4156 // -- "conversion of B* to A* is better than conversion of C* to A*," 4157 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4158 (FromAssignLeft != FromAssignRight)) 4159 return FromAssignLeft? ImplicitConversionSequence::Better 4160 : ImplicitConversionSequence::Worse; 4161 } 4162 } 4163 4164 // Ranking of member-pointer types. 4165 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4166 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4167 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4168 const MemberPointerType * FromMemPointer1 = 4169 FromType1->getAs<MemberPointerType>(); 4170 const MemberPointerType * ToMemPointer1 = 4171 ToType1->getAs<MemberPointerType>(); 4172 const MemberPointerType * FromMemPointer2 = 4173 FromType2->getAs<MemberPointerType>(); 4174 const MemberPointerType * ToMemPointer2 = 4175 ToType2->getAs<MemberPointerType>(); 4176 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4177 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4178 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4179 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4180 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4181 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4182 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4183 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4184 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4185 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4186 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4187 return ImplicitConversionSequence::Worse; 4188 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4189 return ImplicitConversionSequence::Better; 4190 } 4191 // conversion of B::* to C::* is better than conversion of A::* to C::* 4192 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4193 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4194 return ImplicitConversionSequence::Better; 4195 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4196 return ImplicitConversionSequence::Worse; 4197 } 4198 } 4199 4200 if (SCS1.Second == ICK_Derived_To_Base) { 4201 // -- conversion of C to B is better than conversion of C to A, 4202 // -- binding of an expression of type C to a reference of type 4203 // B& is better than binding an expression of type C to a 4204 // reference of type A&, 4205 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4206 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4207 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4208 return ImplicitConversionSequence::Better; 4209 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4210 return ImplicitConversionSequence::Worse; 4211 } 4212 4213 // -- conversion of B to A is better than conversion of C to A. 4214 // -- binding of an expression of type B to a reference of type 4215 // A& is better than binding an expression of type C to a 4216 // reference of type A&, 4217 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4218 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4219 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4220 return ImplicitConversionSequence::Better; 4221 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4222 return ImplicitConversionSequence::Worse; 4223 } 4224 } 4225 4226 return ImplicitConversionSequence::Indistinguishable; 4227 } 4228 4229 /// Determine whether the given type is valid, e.g., it is not an invalid 4230 /// C++ class. 4231 static bool isTypeValid(QualType T) { 4232 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4233 return !Record->isInvalidDecl(); 4234 4235 return true; 4236 } 4237 4238 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4239 /// determine whether they are reference-related, 4240 /// reference-compatible, reference-compatible with added 4241 /// qualification, or incompatible, for use in C++ initialization by 4242 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4243 /// type, and the first type (T1) is the pointee type of the reference 4244 /// type being initialized. 4245 Sema::ReferenceCompareResult 4246 Sema::CompareReferenceRelationship(SourceLocation Loc, 4247 QualType OrigT1, QualType OrigT2, 4248 bool &DerivedToBase, 4249 bool &ObjCConversion, 4250 bool &ObjCLifetimeConversion) { 4251 assert(!OrigT1->isReferenceType() && 4252 "T1 must be the pointee type of the reference type"); 4253 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4254 4255 QualType T1 = Context.getCanonicalType(OrigT1); 4256 QualType T2 = Context.getCanonicalType(OrigT2); 4257 Qualifiers T1Quals, T2Quals; 4258 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4259 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4260 4261 // C++ [dcl.init.ref]p4: 4262 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4263 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4264 // T1 is a base class of T2. 4265 DerivedToBase = false; 4266 ObjCConversion = false; 4267 ObjCLifetimeConversion = false; 4268 QualType ConvertedT2; 4269 if (UnqualT1 == UnqualT2) { 4270 // Nothing to do. 4271 } else if (isCompleteType(Loc, OrigT2) && 4272 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4273 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4274 DerivedToBase = true; 4275 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4276 UnqualT2->isObjCObjectOrInterfaceType() && 4277 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4278 ObjCConversion = true; 4279 else if (UnqualT2->isFunctionType() && 4280 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4281 // C++1z [dcl.init.ref]p4: 4282 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4283 // function" and T1 is "function" 4284 // 4285 // We extend this to also apply to 'noreturn', so allow any function 4286 // conversion between function types. 4287 return Ref_Compatible; 4288 else 4289 return Ref_Incompatible; 4290 4291 // At this point, we know that T1 and T2 are reference-related (at 4292 // least). 4293 4294 // If the type is an array type, promote the element qualifiers to the type 4295 // for comparison. 4296 if (isa<ArrayType>(T1) && T1Quals) 4297 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4298 if (isa<ArrayType>(T2) && T2Quals) 4299 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4300 4301 // C++ [dcl.init.ref]p4: 4302 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4303 // reference-related to T2 and cv1 is the same cv-qualification 4304 // as, or greater cv-qualification than, cv2. For purposes of 4305 // overload resolution, cases for which cv1 is greater 4306 // cv-qualification than cv2 are identified as 4307 // reference-compatible with added qualification (see 13.3.3.2). 4308 // 4309 // Note that we also require equivalence of Objective-C GC and address-space 4310 // qualifiers when performing these computations, so that e.g., an int in 4311 // address space 1 is not reference-compatible with an int in address 4312 // space 2. 4313 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4314 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4315 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4316 ObjCLifetimeConversion = true; 4317 4318 T1Quals.removeObjCLifetime(); 4319 T2Quals.removeObjCLifetime(); 4320 } 4321 4322 // MS compiler ignores __unaligned qualifier for references; do the same. 4323 T1Quals.removeUnaligned(); 4324 T2Quals.removeUnaligned(); 4325 4326 if (T1Quals.compatiblyIncludes(T2Quals)) 4327 return Ref_Compatible; 4328 else 4329 return Ref_Related; 4330 } 4331 4332 /// Look for a user-defined conversion to a value reference-compatible 4333 /// with DeclType. Return true if something definite is found. 4334 static bool 4335 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4336 QualType DeclType, SourceLocation DeclLoc, 4337 Expr *Init, QualType T2, bool AllowRvalues, 4338 bool AllowExplicit) { 4339 assert(T2->isRecordType() && "Can only find conversions of record types."); 4340 CXXRecordDecl *T2RecordDecl 4341 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4342 4343 OverloadCandidateSet CandidateSet( 4344 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4345 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4346 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4347 NamedDecl *D = *I; 4348 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4349 if (isa<UsingShadowDecl>(D)) 4350 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4351 4352 FunctionTemplateDecl *ConvTemplate 4353 = dyn_cast<FunctionTemplateDecl>(D); 4354 CXXConversionDecl *Conv; 4355 if (ConvTemplate) 4356 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4357 else 4358 Conv = cast<CXXConversionDecl>(D); 4359 4360 // If this is an explicit conversion, and we're not allowed to consider 4361 // explicit conversions, skip it. 4362 if (!AllowExplicit && Conv->isExplicit()) 4363 continue; 4364 4365 if (AllowRvalues) { 4366 bool DerivedToBase = false; 4367 bool ObjCConversion = false; 4368 bool ObjCLifetimeConversion = false; 4369 4370 // If we are initializing an rvalue reference, don't permit conversion 4371 // functions that return lvalues. 4372 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4373 const ReferenceType *RefType 4374 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4375 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4376 continue; 4377 } 4378 4379 if (!ConvTemplate && 4380 S.CompareReferenceRelationship( 4381 DeclLoc, 4382 Conv->getConversionType().getNonReferenceType() 4383 .getUnqualifiedType(), 4384 DeclType.getNonReferenceType().getUnqualifiedType(), 4385 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4386 Sema::Ref_Incompatible) 4387 continue; 4388 } else { 4389 // If the conversion function doesn't return a reference type, 4390 // it can't be considered for this conversion. An rvalue reference 4391 // is only acceptable if its referencee is a function type. 4392 4393 const ReferenceType *RefType = 4394 Conv->getConversionType()->getAs<ReferenceType>(); 4395 if (!RefType || 4396 (!RefType->isLValueReferenceType() && 4397 !RefType->getPointeeType()->isFunctionType())) 4398 continue; 4399 } 4400 4401 if (ConvTemplate) 4402 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4403 Init, DeclType, CandidateSet, 4404 /*AllowObjCConversionOnExplicit=*/false); 4405 else 4406 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4407 DeclType, CandidateSet, 4408 /*AllowObjCConversionOnExplicit=*/false); 4409 } 4410 4411 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4412 4413 OverloadCandidateSet::iterator Best; 4414 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4415 case OR_Success: 4416 // C++ [over.ics.ref]p1: 4417 // 4418 // [...] If the parameter binds directly to the result of 4419 // applying a conversion function to the argument 4420 // expression, the implicit conversion sequence is a 4421 // user-defined conversion sequence (13.3.3.1.2), with the 4422 // second standard conversion sequence either an identity 4423 // conversion or, if the conversion function returns an 4424 // entity of a type that is a derived class of the parameter 4425 // type, a derived-to-base Conversion. 4426 if (!Best->FinalConversion.DirectBinding) 4427 return false; 4428 4429 ICS.setUserDefined(); 4430 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4431 ICS.UserDefined.After = Best->FinalConversion; 4432 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4433 ICS.UserDefined.ConversionFunction = Best->Function; 4434 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4435 ICS.UserDefined.EllipsisConversion = false; 4436 assert(ICS.UserDefined.After.ReferenceBinding && 4437 ICS.UserDefined.After.DirectBinding && 4438 "Expected a direct reference binding!"); 4439 return true; 4440 4441 case OR_Ambiguous: 4442 ICS.setAmbiguous(); 4443 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4444 Cand != CandidateSet.end(); ++Cand) 4445 if (Cand->Viable) 4446 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4447 return true; 4448 4449 case OR_No_Viable_Function: 4450 case OR_Deleted: 4451 // There was no suitable conversion, or we found a deleted 4452 // conversion; continue with other checks. 4453 return false; 4454 } 4455 4456 llvm_unreachable("Invalid OverloadResult!"); 4457 } 4458 4459 /// Compute an implicit conversion sequence for reference 4460 /// initialization. 4461 static ImplicitConversionSequence 4462 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4463 SourceLocation DeclLoc, 4464 bool SuppressUserConversions, 4465 bool AllowExplicit) { 4466 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4467 4468 // Most paths end in a failed conversion. 4469 ImplicitConversionSequence ICS; 4470 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4471 4472 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4473 QualType T2 = Init->getType(); 4474 4475 // If the initializer is the address of an overloaded function, try 4476 // to resolve the overloaded function. If all goes well, T2 is the 4477 // type of the resulting function. 4478 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4479 DeclAccessPair Found; 4480 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4481 false, Found)) 4482 T2 = Fn->getType(); 4483 } 4484 4485 // Compute some basic properties of the types and the initializer. 4486 bool isRValRef = DeclType->isRValueReferenceType(); 4487 bool DerivedToBase = false; 4488 bool ObjCConversion = false; 4489 bool ObjCLifetimeConversion = false; 4490 Expr::Classification InitCategory = Init->Classify(S.Context); 4491 Sema::ReferenceCompareResult RefRelationship 4492 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4493 ObjCConversion, ObjCLifetimeConversion); 4494 4495 4496 // C++0x [dcl.init.ref]p5: 4497 // A reference to type "cv1 T1" is initialized by an expression 4498 // of type "cv2 T2" as follows: 4499 4500 // -- If reference is an lvalue reference and the initializer expression 4501 if (!isRValRef) { 4502 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4503 // reference-compatible with "cv2 T2," or 4504 // 4505 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4506 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4507 // C++ [over.ics.ref]p1: 4508 // When a parameter of reference type binds directly (8.5.3) 4509 // to an argument expression, the implicit conversion sequence 4510 // is the identity conversion, unless the argument expression 4511 // has a type that is a derived class of the parameter type, 4512 // in which case the implicit conversion sequence is a 4513 // derived-to-base Conversion (13.3.3.1). 4514 ICS.setStandard(); 4515 ICS.Standard.First = ICK_Identity; 4516 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4517 : ObjCConversion? ICK_Compatible_Conversion 4518 : ICK_Identity; 4519 ICS.Standard.Third = ICK_Identity; 4520 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4521 ICS.Standard.setToType(0, T2); 4522 ICS.Standard.setToType(1, T1); 4523 ICS.Standard.setToType(2, T1); 4524 ICS.Standard.ReferenceBinding = true; 4525 ICS.Standard.DirectBinding = true; 4526 ICS.Standard.IsLvalueReference = !isRValRef; 4527 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4528 ICS.Standard.BindsToRvalue = false; 4529 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4530 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4531 ICS.Standard.CopyConstructor = nullptr; 4532 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4533 4534 // Nothing more to do: the inaccessibility/ambiguity check for 4535 // derived-to-base conversions is suppressed when we're 4536 // computing the implicit conversion sequence (C++ 4537 // [over.best.ics]p2). 4538 return ICS; 4539 } 4540 4541 // -- has a class type (i.e., T2 is a class type), where T1 is 4542 // not reference-related to T2, and can be implicitly 4543 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4544 // is reference-compatible with "cv3 T3" 92) (this 4545 // conversion is selected by enumerating the applicable 4546 // conversion functions (13.3.1.6) and choosing the best 4547 // one through overload resolution (13.3)), 4548 if (!SuppressUserConversions && T2->isRecordType() && 4549 S.isCompleteType(DeclLoc, T2) && 4550 RefRelationship == Sema::Ref_Incompatible) { 4551 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4552 Init, T2, /*AllowRvalues=*/false, 4553 AllowExplicit)) 4554 return ICS; 4555 } 4556 } 4557 4558 // -- Otherwise, the reference shall be an lvalue reference to a 4559 // non-volatile const type (i.e., cv1 shall be const), or the reference 4560 // shall be an rvalue reference. 4561 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4562 return ICS; 4563 4564 // -- If the initializer expression 4565 // 4566 // -- is an xvalue, class prvalue, array prvalue or function 4567 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4568 if (RefRelationship == Sema::Ref_Compatible && 4569 (InitCategory.isXValue() || 4570 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4571 (InitCategory.isLValue() && T2->isFunctionType()))) { 4572 ICS.setStandard(); 4573 ICS.Standard.First = ICK_Identity; 4574 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4575 : ObjCConversion? ICK_Compatible_Conversion 4576 : ICK_Identity; 4577 ICS.Standard.Third = ICK_Identity; 4578 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4579 ICS.Standard.setToType(0, T2); 4580 ICS.Standard.setToType(1, T1); 4581 ICS.Standard.setToType(2, T1); 4582 ICS.Standard.ReferenceBinding = true; 4583 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4584 // binding unless we're binding to a class prvalue. 4585 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4586 // allow the use of rvalue references in C++98/03 for the benefit of 4587 // standard library implementors; therefore, we need the xvalue check here. 4588 ICS.Standard.DirectBinding = 4589 S.getLangOpts().CPlusPlus11 || 4590 !(InitCategory.isPRValue() || T2->isRecordType()); 4591 ICS.Standard.IsLvalueReference = !isRValRef; 4592 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4593 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4594 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4595 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4596 ICS.Standard.CopyConstructor = nullptr; 4597 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4598 return ICS; 4599 } 4600 4601 // -- has a class type (i.e., T2 is a class type), where T1 is not 4602 // reference-related to T2, and can be implicitly converted to 4603 // an xvalue, class prvalue, or function lvalue of type 4604 // "cv3 T3", where "cv1 T1" is reference-compatible with 4605 // "cv3 T3", 4606 // 4607 // then the reference is bound to the value of the initializer 4608 // expression in the first case and to the result of the conversion 4609 // in the second case (or, in either case, to an appropriate base 4610 // class subobject). 4611 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4612 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4613 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4614 Init, T2, /*AllowRvalues=*/true, 4615 AllowExplicit)) { 4616 // In the second case, if the reference is an rvalue reference 4617 // and the second standard conversion sequence of the 4618 // user-defined conversion sequence includes an lvalue-to-rvalue 4619 // conversion, the program is ill-formed. 4620 if (ICS.isUserDefined() && isRValRef && 4621 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4622 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4623 4624 return ICS; 4625 } 4626 4627 // A temporary of function type cannot be created; don't even try. 4628 if (T1->isFunctionType()) 4629 return ICS; 4630 4631 // -- Otherwise, a temporary of type "cv1 T1" is created and 4632 // initialized from the initializer expression using the 4633 // rules for a non-reference copy initialization (8.5). The 4634 // reference is then bound to the temporary. If T1 is 4635 // reference-related to T2, cv1 must be the same 4636 // cv-qualification as, or greater cv-qualification than, 4637 // cv2; otherwise, the program is ill-formed. 4638 if (RefRelationship == Sema::Ref_Related) { 4639 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4640 // we would be reference-compatible or reference-compatible with 4641 // added qualification. But that wasn't the case, so the reference 4642 // initialization fails. 4643 // 4644 // Note that we only want to check address spaces and cvr-qualifiers here. 4645 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4646 Qualifiers T1Quals = T1.getQualifiers(); 4647 Qualifiers T2Quals = T2.getQualifiers(); 4648 T1Quals.removeObjCGCAttr(); 4649 T1Quals.removeObjCLifetime(); 4650 T2Quals.removeObjCGCAttr(); 4651 T2Quals.removeObjCLifetime(); 4652 // MS compiler ignores __unaligned qualifier for references; do the same. 4653 T1Quals.removeUnaligned(); 4654 T2Quals.removeUnaligned(); 4655 if (!T1Quals.compatiblyIncludes(T2Quals)) 4656 return ICS; 4657 } 4658 4659 // If at least one of the types is a class type, the types are not 4660 // related, and we aren't allowed any user conversions, the 4661 // reference binding fails. This case is important for breaking 4662 // recursion, since TryImplicitConversion below will attempt to 4663 // create a temporary through the use of a copy constructor. 4664 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4665 (T1->isRecordType() || T2->isRecordType())) 4666 return ICS; 4667 4668 // If T1 is reference-related to T2 and the reference is an rvalue 4669 // reference, the initializer expression shall not be an lvalue. 4670 if (RefRelationship >= Sema::Ref_Related && 4671 isRValRef && Init->Classify(S.Context).isLValue()) 4672 return ICS; 4673 4674 // C++ [over.ics.ref]p2: 4675 // When a parameter of reference type is not bound directly to 4676 // an argument expression, the conversion sequence is the one 4677 // required to convert the argument expression to the 4678 // underlying type of the reference according to 4679 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4680 // to copy-initializing a temporary of the underlying type with 4681 // the argument expression. Any difference in top-level 4682 // cv-qualification is subsumed by the initialization itself 4683 // and does not constitute a conversion. 4684 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4685 /*AllowExplicit=*/false, 4686 /*InOverloadResolution=*/false, 4687 /*CStyle=*/false, 4688 /*AllowObjCWritebackConversion=*/false, 4689 /*AllowObjCConversionOnExplicit=*/false); 4690 4691 // Of course, that's still a reference binding. 4692 if (ICS.isStandard()) { 4693 ICS.Standard.ReferenceBinding = true; 4694 ICS.Standard.IsLvalueReference = !isRValRef; 4695 ICS.Standard.BindsToFunctionLvalue = false; 4696 ICS.Standard.BindsToRvalue = true; 4697 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4698 ICS.Standard.ObjCLifetimeConversionBinding = false; 4699 } else if (ICS.isUserDefined()) { 4700 const ReferenceType *LValRefType = 4701 ICS.UserDefined.ConversionFunction->getReturnType() 4702 ->getAs<LValueReferenceType>(); 4703 4704 // C++ [over.ics.ref]p3: 4705 // Except for an implicit object parameter, for which see 13.3.1, a 4706 // standard conversion sequence cannot be formed if it requires [...] 4707 // binding an rvalue reference to an lvalue other than a function 4708 // lvalue. 4709 // Note that the function case is not possible here. 4710 if (DeclType->isRValueReferenceType() && LValRefType) { 4711 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4712 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4713 // reference to an rvalue! 4714 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4715 return ICS; 4716 } 4717 4718 ICS.UserDefined.After.ReferenceBinding = true; 4719 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4720 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4721 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4722 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4723 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4724 } 4725 4726 return ICS; 4727 } 4728 4729 static ImplicitConversionSequence 4730 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4731 bool SuppressUserConversions, 4732 bool InOverloadResolution, 4733 bool AllowObjCWritebackConversion, 4734 bool AllowExplicit = false); 4735 4736 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4737 /// initializer list From. 4738 static ImplicitConversionSequence 4739 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4740 bool SuppressUserConversions, 4741 bool InOverloadResolution, 4742 bool AllowObjCWritebackConversion) { 4743 // C++11 [over.ics.list]p1: 4744 // When an argument is an initializer list, it is not an expression and 4745 // special rules apply for converting it to a parameter type. 4746 4747 ImplicitConversionSequence Result; 4748 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4749 4750 // We need a complete type for what follows. Incomplete types can never be 4751 // initialized from init lists. 4752 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4753 return Result; 4754 4755 // Per DR1467: 4756 // If the parameter type is a class X and the initializer list has a single 4757 // element of type cv U, where U is X or a class derived from X, the 4758 // implicit conversion sequence is the one required to convert the element 4759 // to the parameter type. 4760 // 4761 // Otherwise, if the parameter type is a character array [... ] 4762 // and the initializer list has a single element that is an 4763 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4764 // implicit conversion sequence is the identity conversion. 4765 if (From->getNumInits() == 1) { 4766 if (ToType->isRecordType()) { 4767 QualType InitType = From->getInit(0)->getType(); 4768 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4769 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4770 return TryCopyInitialization(S, From->getInit(0), ToType, 4771 SuppressUserConversions, 4772 InOverloadResolution, 4773 AllowObjCWritebackConversion); 4774 } 4775 // FIXME: Check the other conditions here: array of character type, 4776 // initializer is a string literal. 4777 if (ToType->isArrayType()) { 4778 InitializedEntity Entity = 4779 InitializedEntity::InitializeParameter(S.Context, ToType, 4780 /*Consumed=*/false); 4781 if (S.CanPerformCopyInitialization(Entity, From)) { 4782 Result.setStandard(); 4783 Result.Standard.setAsIdentityConversion(); 4784 Result.Standard.setFromType(ToType); 4785 Result.Standard.setAllToTypes(ToType); 4786 return Result; 4787 } 4788 } 4789 } 4790 4791 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4792 // C++11 [over.ics.list]p2: 4793 // If the parameter type is std::initializer_list<X> or "array of X" and 4794 // all the elements can be implicitly converted to X, the implicit 4795 // conversion sequence is the worst conversion necessary to convert an 4796 // element of the list to X. 4797 // 4798 // C++14 [over.ics.list]p3: 4799 // Otherwise, if the parameter type is "array of N X", if the initializer 4800 // list has exactly N elements or if it has fewer than N elements and X is 4801 // default-constructible, and if all the elements of the initializer list 4802 // can be implicitly converted to X, the implicit conversion sequence is 4803 // the worst conversion necessary to convert an element of the list to X. 4804 // 4805 // FIXME: We're missing a lot of these checks. 4806 bool toStdInitializerList = false; 4807 QualType X; 4808 if (ToType->isArrayType()) 4809 X = S.Context.getAsArrayType(ToType)->getElementType(); 4810 else 4811 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4812 if (!X.isNull()) { 4813 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4814 Expr *Init = From->getInit(i); 4815 ImplicitConversionSequence ICS = 4816 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4817 InOverloadResolution, 4818 AllowObjCWritebackConversion); 4819 // If a single element isn't convertible, fail. 4820 if (ICS.isBad()) { 4821 Result = ICS; 4822 break; 4823 } 4824 // Otherwise, look for the worst conversion. 4825 if (Result.isBad() || CompareImplicitConversionSequences( 4826 S, From->getBeginLoc(), ICS, Result) == 4827 ImplicitConversionSequence::Worse) 4828 Result = ICS; 4829 } 4830 4831 // For an empty list, we won't have computed any conversion sequence. 4832 // Introduce the identity conversion sequence. 4833 if (From->getNumInits() == 0) { 4834 Result.setStandard(); 4835 Result.Standard.setAsIdentityConversion(); 4836 Result.Standard.setFromType(ToType); 4837 Result.Standard.setAllToTypes(ToType); 4838 } 4839 4840 Result.setStdInitializerListElement(toStdInitializerList); 4841 return Result; 4842 } 4843 4844 // C++14 [over.ics.list]p4: 4845 // C++11 [over.ics.list]p3: 4846 // Otherwise, if the parameter is a non-aggregate class X and overload 4847 // resolution chooses a single best constructor [...] the implicit 4848 // conversion sequence is a user-defined conversion sequence. If multiple 4849 // constructors are viable but none is better than the others, the 4850 // implicit conversion sequence is a user-defined conversion sequence. 4851 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4852 // This function can deal with initializer lists. 4853 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4854 /*AllowExplicit=*/false, 4855 InOverloadResolution, /*CStyle=*/false, 4856 AllowObjCWritebackConversion, 4857 /*AllowObjCConversionOnExplicit=*/false); 4858 } 4859 4860 // C++14 [over.ics.list]p5: 4861 // C++11 [over.ics.list]p4: 4862 // Otherwise, if the parameter has an aggregate type which can be 4863 // initialized from the initializer list [...] the implicit conversion 4864 // sequence is a user-defined conversion sequence. 4865 if (ToType->isAggregateType()) { 4866 // Type is an aggregate, argument is an init list. At this point it comes 4867 // down to checking whether the initialization works. 4868 // FIXME: Find out whether this parameter is consumed or not. 4869 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4870 // need to call into the initialization code here; overload resolution 4871 // should not be doing that. 4872 InitializedEntity Entity = 4873 InitializedEntity::InitializeParameter(S.Context, ToType, 4874 /*Consumed=*/false); 4875 if (S.CanPerformCopyInitialization(Entity, From)) { 4876 Result.setUserDefined(); 4877 Result.UserDefined.Before.setAsIdentityConversion(); 4878 // Initializer lists don't have a type. 4879 Result.UserDefined.Before.setFromType(QualType()); 4880 Result.UserDefined.Before.setAllToTypes(QualType()); 4881 4882 Result.UserDefined.After.setAsIdentityConversion(); 4883 Result.UserDefined.After.setFromType(ToType); 4884 Result.UserDefined.After.setAllToTypes(ToType); 4885 Result.UserDefined.ConversionFunction = nullptr; 4886 } 4887 return Result; 4888 } 4889 4890 // C++14 [over.ics.list]p6: 4891 // C++11 [over.ics.list]p5: 4892 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4893 if (ToType->isReferenceType()) { 4894 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4895 // mention initializer lists in any way. So we go by what list- 4896 // initialization would do and try to extrapolate from that. 4897 4898 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4899 4900 // If the initializer list has a single element that is reference-related 4901 // to the parameter type, we initialize the reference from that. 4902 if (From->getNumInits() == 1) { 4903 Expr *Init = From->getInit(0); 4904 4905 QualType T2 = Init->getType(); 4906 4907 // If the initializer is the address of an overloaded function, try 4908 // to resolve the overloaded function. If all goes well, T2 is the 4909 // type of the resulting function. 4910 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4911 DeclAccessPair Found; 4912 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4913 Init, ToType, false, Found)) 4914 T2 = Fn->getType(); 4915 } 4916 4917 // Compute some basic properties of the types and the initializer. 4918 bool dummy1 = false; 4919 bool dummy2 = false; 4920 bool dummy3 = false; 4921 Sema::ReferenceCompareResult RefRelationship = 4922 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4923 dummy2, dummy3); 4924 4925 if (RefRelationship >= Sema::Ref_Related) { 4926 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4927 SuppressUserConversions, 4928 /*AllowExplicit=*/false); 4929 } 4930 } 4931 4932 // Otherwise, we bind the reference to a temporary created from the 4933 // initializer list. 4934 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4935 InOverloadResolution, 4936 AllowObjCWritebackConversion); 4937 if (Result.isFailure()) 4938 return Result; 4939 assert(!Result.isEllipsis() && 4940 "Sub-initialization cannot result in ellipsis conversion."); 4941 4942 // Can we even bind to a temporary? 4943 if (ToType->isRValueReferenceType() || 4944 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4945 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4946 Result.UserDefined.After; 4947 SCS.ReferenceBinding = true; 4948 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4949 SCS.BindsToRvalue = true; 4950 SCS.BindsToFunctionLvalue = false; 4951 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4952 SCS.ObjCLifetimeConversionBinding = false; 4953 } else 4954 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4955 From, ToType); 4956 return Result; 4957 } 4958 4959 // C++14 [over.ics.list]p7: 4960 // C++11 [over.ics.list]p6: 4961 // Otherwise, if the parameter type is not a class: 4962 if (!ToType->isRecordType()) { 4963 // - if the initializer list has one element that is not itself an 4964 // initializer list, the implicit conversion sequence is the one 4965 // required to convert the element to the parameter type. 4966 unsigned NumInits = From->getNumInits(); 4967 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4968 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4969 SuppressUserConversions, 4970 InOverloadResolution, 4971 AllowObjCWritebackConversion); 4972 // - if the initializer list has no elements, the implicit conversion 4973 // sequence is the identity conversion. 4974 else if (NumInits == 0) { 4975 Result.setStandard(); 4976 Result.Standard.setAsIdentityConversion(); 4977 Result.Standard.setFromType(ToType); 4978 Result.Standard.setAllToTypes(ToType); 4979 } 4980 return Result; 4981 } 4982 4983 // C++14 [over.ics.list]p8: 4984 // C++11 [over.ics.list]p7: 4985 // In all cases other than those enumerated above, no conversion is possible 4986 return Result; 4987 } 4988 4989 /// TryCopyInitialization - Try to copy-initialize a value of type 4990 /// ToType from the expression From. Return the implicit conversion 4991 /// sequence required to pass this argument, which may be a bad 4992 /// conversion sequence (meaning that the argument cannot be passed to 4993 /// a parameter of this type). If @p SuppressUserConversions, then we 4994 /// do not permit any user-defined conversion sequences. 4995 static ImplicitConversionSequence 4996 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4997 bool SuppressUserConversions, 4998 bool InOverloadResolution, 4999 bool AllowObjCWritebackConversion, 5000 bool AllowExplicit) { 5001 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5002 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5003 InOverloadResolution,AllowObjCWritebackConversion); 5004 5005 if (ToType->isReferenceType()) 5006 return TryReferenceInit(S, From, ToType, 5007 /*FIXME:*/ From->getBeginLoc(), 5008 SuppressUserConversions, AllowExplicit); 5009 5010 return TryImplicitConversion(S, From, ToType, 5011 SuppressUserConversions, 5012 /*AllowExplicit=*/false, 5013 InOverloadResolution, 5014 /*CStyle=*/false, 5015 AllowObjCWritebackConversion, 5016 /*AllowObjCConversionOnExplicit=*/false); 5017 } 5018 5019 static bool TryCopyInitialization(const CanQualType FromQTy, 5020 const CanQualType ToQTy, 5021 Sema &S, 5022 SourceLocation Loc, 5023 ExprValueKind FromVK) { 5024 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5025 ImplicitConversionSequence ICS = 5026 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5027 5028 return !ICS.isBad(); 5029 } 5030 5031 /// TryObjectArgumentInitialization - Try to initialize the object 5032 /// parameter of the given member function (@c Method) from the 5033 /// expression @p From. 5034 static ImplicitConversionSequence 5035 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5036 Expr::Classification FromClassification, 5037 CXXMethodDecl *Method, 5038 CXXRecordDecl *ActingContext) { 5039 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5040 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5041 // const volatile object. 5042 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 5043 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 5044 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 5045 5046 // Set up the conversion sequence as a "bad" conversion, to allow us 5047 // to exit early. 5048 ImplicitConversionSequence ICS; 5049 5050 // We need to have an object of class type. 5051 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5052 FromType = PT->getPointeeType(); 5053 5054 // When we had a pointer, it's implicitly dereferenced, so we 5055 // better have an lvalue. 5056 assert(FromClassification.isLValue()); 5057 } 5058 5059 assert(FromType->isRecordType()); 5060 5061 // C++0x [over.match.funcs]p4: 5062 // For non-static member functions, the type of the implicit object 5063 // parameter is 5064 // 5065 // - "lvalue reference to cv X" for functions declared without a 5066 // ref-qualifier or with the & ref-qualifier 5067 // - "rvalue reference to cv X" for functions declared with the && 5068 // ref-qualifier 5069 // 5070 // where X is the class of which the function is a member and cv is the 5071 // cv-qualification on the member function declaration. 5072 // 5073 // However, when finding an implicit conversion sequence for the argument, we 5074 // are not allowed to perform user-defined conversions 5075 // (C++ [over.match.funcs]p5). We perform a simplified version of 5076 // reference binding here, that allows class rvalues to bind to 5077 // non-constant references. 5078 5079 // First check the qualifiers. 5080 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5081 if (ImplicitParamType.getCVRQualifiers() 5082 != FromTypeCanon.getLocalCVRQualifiers() && 5083 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5084 ICS.setBad(BadConversionSequence::bad_qualifiers, 5085 FromType, ImplicitParamType); 5086 return ICS; 5087 } 5088 5089 // Check that we have either the same type or a derived type. It 5090 // affects the conversion rank. 5091 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5092 ImplicitConversionKind SecondKind; 5093 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5094 SecondKind = ICK_Identity; 5095 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5096 SecondKind = ICK_Derived_To_Base; 5097 else { 5098 ICS.setBad(BadConversionSequence::unrelated_class, 5099 FromType, ImplicitParamType); 5100 return ICS; 5101 } 5102 5103 // Check the ref-qualifier. 5104 switch (Method->getRefQualifier()) { 5105 case RQ_None: 5106 // Do nothing; we don't care about lvalueness or rvalueness. 5107 break; 5108 5109 case RQ_LValue: 5110 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5111 // non-const lvalue reference cannot bind to an rvalue 5112 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5113 ImplicitParamType); 5114 return ICS; 5115 } 5116 break; 5117 5118 case RQ_RValue: 5119 if (!FromClassification.isRValue()) { 5120 // rvalue reference cannot bind to an lvalue 5121 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5122 ImplicitParamType); 5123 return ICS; 5124 } 5125 break; 5126 } 5127 5128 // Success. Mark this as a reference binding. 5129 ICS.setStandard(); 5130 ICS.Standard.setAsIdentityConversion(); 5131 ICS.Standard.Second = SecondKind; 5132 ICS.Standard.setFromType(FromType); 5133 ICS.Standard.setAllToTypes(ImplicitParamType); 5134 ICS.Standard.ReferenceBinding = true; 5135 ICS.Standard.DirectBinding = true; 5136 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5137 ICS.Standard.BindsToFunctionLvalue = false; 5138 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5139 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5140 = (Method->getRefQualifier() == RQ_None); 5141 return ICS; 5142 } 5143 5144 /// PerformObjectArgumentInitialization - Perform initialization of 5145 /// the implicit object parameter for the given Method with the given 5146 /// expression. 5147 ExprResult 5148 Sema::PerformObjectArgumentInitialization(Expr *From, 5149 NestedNameSpecifier *Qualifier, 5150 NamedDecl *FoundDecl, 5151 CXXMethodDecl *Method) { 5152 QualType FromRecordType, DestType; 5153 QualType ImplicitParamRecordType = 5154 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5155 5156 Expr::Classification FromClassification; 5157 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5158 FromRecordType = PT->getPointeeType(); 5159 DestType = Method->getThisType(Context); 5160 FromClassification = Expr::Classification::makeSimpleLValue(); 5161 } else { 5162 FromRecordType = From->getType(); 5163 DestType = ImplicitParamRecordType; 5164 FromClassification = From->Classify(Context); 5165 5166 // When performing member access on an rvalue, materialize a temporary. 5167 if (From->isRValue()) { 5168 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5169 Method->getRefQualifier() != 5170 RefQualifierKind::RQ_RValue); 5171 } 5172 } 5173 5174 // Note that we always use the true parent context when performing 5175 // the actual argument initialization. 5176 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5177 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5178 Method->getParent()); 5179 if (ICS.isBad()) { 5180 switch (ICS.Bad.Kind) { 5181 case BadConversionSequence::bad_qualifiers: { 5182 Qualifiers FromQs = FromRecordType.getQualifiers(); 5183 Qualifiers ToQs = DestType.getQualifiers(); 5184 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5185 if (CVR) { 5186 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5187 << Method->getDeclName() << FromRecordType << (CVR - 1) 5188 << From->getSourceRange(); 5189 Diag(Method->getLocation(), diag::note_previous_decl) 5190 << Method->getDeclName(); 5191 return ExprError(); 5192 } 5193 break; 5194 } 5195 5196 case BadConversionSequence::lvalue_ref_to_rvalue: 5197 case BadConversionSequence::rvalue_ref_to_lvalue: { 5198 bool IsRValueQualified = 5199 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5200 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5201 << Method->getDeclName() << FromClassification.isRValue() 5202 << IsRValueQualified; 5203 Diag(Method->getLocation(), diag::note_previous_decl) 5204 << Method->getDeclName(); 5205 return ExprError(); 5206 } 5207 5208 case BadConversionSequence::no_conversion: 5209 case BadConversionSequence::unrelated_class: 5210 break; 5211 } 5212 5213 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5214 << ImplicitParamRecordType << FromRecordType 5215 << From->getSourceRange(); 5216 } 5217 5218 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5219 ExprResult FromRes = 5220 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5221 if (FromRes.isInvalid()) 5222 return ExprError(); 5223 From = FromRes.get(); 5224 } 5225 5226 if (!Context.hasSameType(From->getType(), DestType)) 5227 From = ImpCastExprToType(From, DestType, CK_NoOp, 5228 From->getValueKind()).get(); 5229 return From; 5230 } 5231 5232 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5233 /// expression From to bool (C++0x [conv]p3). 5234 static ImplicitConversionSequence 5235 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5236 return TryImplicitConversion(S, From, S.Context.BoolTy, 5237 /*SuppressUserConversions=*/false, 5238 /*AllowExplicit=*/true, 5239 /*InOverloadResolution=*/false, 5240 /*CStyle=*/false, 5241 /*AllowObjCWritebackConversion=*/false, 5242 /*AllowObjCConversionOnExplicit=*/false); 5243 } 5244 5245 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5246 /// of the expression From to bool (C++0x [conv]p3). 5247 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5248 if (checkPlaceholderForOverload(*this, From)) 5249 return ExprError(); 5250 5251 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5252 if (!ICS.isBad()) 5253 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5254 5255 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5256 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5257 << From->getType() << From->getSourceRange(); 5258 return ExprError(); 5259 } 5260 5261 /// Check that the specified conversion is permitted in a converted constant 5262 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5263 /// is acceptable. 5264 static bool CheckConvertedConstantConversions(Sema &S, 5265 StandardConversionSequence &SCS) { 5266 // Since we know that the target type is an integral or unscoped enumeration 5267 // type, most conversion kinds are impossible. All possible First and Third 5268 // conversions are fine. 5269 switch (SCS.Second) { 5270 case ICK_Identity: 5271 case ICK_Function_Conversion: 5272 case ICK_Integral_Promotion: 5273 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5274 case ICK_Zero_Queue_Conversion: 5275 return true; 5276 5277 case ICK_Boolean_Conversion: 5278 // Conversion from an integral or unscoped enumeration type to bool is 5279 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5280 // conversion, so we allow it in a converted constant expression. 5281 // 5282 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5283 // a lot of popular code. We should at least add a warning for this 5284 // (non-conforming) extension. 5285 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5286 SCS.getToType(2)->isBooleanType(); 5287 5288 case ICK_Pointer_Conversion: 5289 case ICK_Pointer_Member: 5290 // C++1z: null pointer conversions and null member pointer conversions are 5291 // only permitted if the source type is std::nullptr_t. 5292 return SCS.getFromType()->isNullPtrType(); 5293 5294 case ICK_Floating_Promotion: 5295 case ICK_Complex_Promotion: 5296 case ICK_Floating_Conversion: 5297 case ICK_Complex_Conversion: 5298 case ICK_Floating_Integral: 5299 case ICK_Compatible_Conversion: 5300 case ICK_Derived_To_Base: 5301 case ICK_Vector_Conversion: 5302 case ICK_Vector_Splat: 5303 case ICK_Complex_Real: 5304 case ICK_Block_Pointer_Conversion: 5305 case ICK_TransparentUnionConversion: 5306 case ICK_Writeback_Conversion: 5307 case ICK_Zero_Event_Conversion: 5308 case ICK_C_Only_Conversion: 5309 case ICK_Incompatible_Pointer_Conversion: 5310 return false; 5311 5312 case ICK_Lvalue_To_Rvalue: 5313 case ICK_Array_To_Pointer: 5314 case ICK_Function_To_Pointer: 5315 llvm_unreachable("found a first conversion kind in Second"); 5316 5317 case ICK_Qualification: 5318 llvm_unreachable("found a third conversion kind in Second"); 5319 5320 case ICK_Num_Conversion_Kinds: 5321 break; 5322 } 5323 5324 llvm_unreachable("unknown conversion kind"); 5325 } 5326 5327 /// CheckConvertedConstantExpression - Check that the expression From is a 5328 /// converted constant expression of type T, perform the conversion and produce 5329 /// the converted expression, per C++11 [expr.const]p3. 5330 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5331 QualType T, APValue &Value, 5332 Sema::CCEKind CCE, 5333 bool RequireInt) { 5334 assert(S.getLangOpts().CPlusPlus11 && 5335 "converted constant expression outside C++11"); 5336 5337 if (checkPlaceholderForOverload(S, From)) 5338 return ExprError(); 5339 5340 // C++1z [expr.const]p3: 5341 // A converted constant expression of type T is an expression, 5342 // implicitly converted to type T, where the converted 5343 // expression is a constant expression and the implicit conversion 5344 // sequence contains only [... list of conversions ...]. 5345 // C++1z [stmt.if]p2: 5346 // If the if statement is of the form if constexpr, the value of the 5347 // condition shall be a contextually converted constant expression of type 5348 // bool. 5349 ImplicitConversionSequence ICS = 5350 CCE == Sema::CCEK_ConstexprIf 5351 ? TryContextuallyConvertToBool(S, From) 5352 : TryCopyInitialization(S, From, T, 5353 /*SuppressUserConversions=*/false, 5354 /*InOverloadResolution=*/false, 5355 /*AllowObjcWritebackConversion=*/false, 5356 /*AllowExplicit=*/false); 5357 StandardConversionSequence *SCS = nullptr; 5358 switch (ICS.getKind()) { 5359 case ImplicitConversionSequence::StandardConversion: 5360 SCS = &ICS.Standard; 5361 break; 5362 case ImplicitConversionSequence::UserDefinedConversion: 5363 // We are converting to a non-class type, so the Before sequence 5364 // must be trivial. 5365 SCS = &ICS.UserDefined.After; 5366 break; 5367 case ImplicitConversionSequence::AmbiguousConversion: 5368 case ImplicitConversionSequence::BadConversion: 5369 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5370 return S.Diag(From->getBeginLoc(), 5371 diag::err_typecheck_converted_constant_expression) 5372 << From->getType() << From->getSourceRange() << T; 5373 return ExprError(); 5374 5375 case ImplicitConversionSequence::EllipsisConversion: 5376 llvm_unreachable("ellipsis conversion in converted constant expression"); 5377 } 5378 5379 // Check that we would only use permitted conversions. 5380 if (!CheckConvertedConstantConversions(S, *SCS)) { 5381 return S.Diag(From->getBeginLoc(), 5382 diag::err_typecheck_converted_constant_expression_disallowed) 5383 << From->getType() << From->getSourceRange() << T; 5384 } 5385 // [...] and where the reference binding (if any) binds directly. 5386 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5387 return S.Diag(From->getBeginLoc(), 5388 diag::err_typecheck_converted_constant_expression_indirect) 5389 << From->getType() << From->getSourceRange() << T; 5390 } 5391 5392 ExprResult Result = 5393 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5394 if (Result.isInvalid()) 5395 return Result; 5396 5397 // Check for a narrowing implicit conversion. 5398 APValue PreNarrowingValue; 5399 QualType PreNarrowingType; 5400 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5401 PreNarrowingType)) { 5402 case NK_Dependent_Narrowing: 5403 // Implicit conversion to a narrower type, but the expression is 5404 // value-dependent so we can't tell whether it's actually narrowing. 5405 case NK_Variable_Narrowing: 5406 // Implicit conversion to a narrower type, and the value is not a constant 5407 // expression. We'll diagnose this in a moment. 5408 case NK_Not_Narrowing: 5409 break; 5410 5411 case NK_Constant_Narrowing: 5412 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5413 << CCE << /*Constant*/ 1 5414 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5415 break; 5416 5417 case NK_Type_Narrowing: 5418 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5419 << CCE << /*Constant*/ 0 << From->getType() << T; 5420 break; 5421 } 5422 5423 if (Result.get()->isValueDependent()) { 5424 Value = APValue(); 5425 return Result; 5426 } 5427 5428 // Check the expression is a constant expression. 5429 SmallVector<PartialDiagnosticAt, 8> Notes; 5430 Expr::EvalResult Eval; 5431 Eval.Diag = &Notes; 5432 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5433 ? Expr::EvaluateForMangling 5434 : Expr::EvaluateForCodeGen; 5435 5436 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5437 (RequireInt && !Eval.Val.isInt())) { 5438 // The expression can't be folded, so we can't keep it at this position in 5439 // the AST. 5440 Result = ExprError(); 5441 } else { 5442 Value = Eval.Val; 5443 5444 if (Notes.empty()) { 5445 // It's a constant expression. 5446 return Result; 5447 } 5448 } 5449 5450 // It's not a constant expression. Produce an appropriate diagnostic. 5451 if (Notes.size() == 1 && 5452 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5453 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5454 else { 5455 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5456 << CCE << From->getSourceRange(); 5457 for (unsigned I = 0; I < Notes.size(); ++I) 5458 S.Diag(Notes[I].first, Notes[I].second); 5459 } 5460 return ExprError(); 5461 } 5462 5463 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5464 APValue &Value, CCEKind CCE) { 5465 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5466 } 5467 5468 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5469 llvm::APSInt &Value, 5470 CCEKind CCE) { 5471 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5472 5473 APValue V; 5474 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5475 if (!R.isInvalid() && !R.get()->isValueDependent()) 5476 Value = V.getInt(); 5477 return R; 5478 } 5479 5480 5481 /// dropPointerConversions - If the given standard conversion sequence 5482 /// involves any pointer conversions, remove them. This may change 5483 /// the result type of the conversion sequence. 5484 static void dropPointerConversion(StandardConversionSequence &SCS) { 5485 if (SCS.Second == ICK_Pointer_Conversion) { 5486 SCS.Second = ICK_Identity; 5487 SCS.Third = ICK_Identity; 5488 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5489 } 5490 } 5491 5492 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5493 /// convert the expression From to an Objective-C pointer type. 5494 static ImplicitConversionSequence 5495 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5496 // Do an implicit conversion to 'id'. 5497 QualType Ty = S.Context.getObjCIdType(); 5498 ImplicitConversionSequence ICS 5499 = TryImplicitConversion(S, From, Ty, 5500 // FIXME: Are these flags correct? 5501 /*SuppressUserConversions=*/false, 5502 /*AllowExplicit=*/true, 5503 /*InOverloadResolution=*/false, 5504 /*CStyle=*/false, 5505 /*AllowObjCWritebackConversion=*/false, 5506 /*AllowObjCConversionOnExplicit=*/true); 5507 5508 // Strip off any final conversions to 'id'. 5509 switch (ICS.getKind()) { 5510 case ImplicitConversionSequence::BadConversion: 5511 case ImplicitConversionSequence::AmbiguousConversion: 5512 case ImplicitConversionSequence::EllipsisConversion: 5513 break; 5514 5515 case ImplicitConversionSequence::UserDefinedConversion: 5516 dropPointerConversion(ICS.UserDefined.After); 5517 break; 5518 5519 case ImplicitConversionSequence::StandardConversion: 5520 dropPointerConversion(ICS.Standard); 5521 break; 5522 } 5523 5524 return ICS; 5525 } 5526 5527 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5528 /// conversion of the expression From to an Objective-C pointer type. 5529 /// Returns a valid but null ExprResult if no conversion sequence exists. 5530 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5531 if (checkPlaceholderForOverload(*this, From)) 5532 return ExprError(); 5533 5534 QualType Ty = Context.getObjCIdType(); 5535 ImplicitConversionSequence ICS = 5536 TryContextuallyConvertToObjCPointer(*this, From); 5537 if (!ICS.isBad()) 5538 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5539 return ExprResult(); 5540 } 5541 5542 /// Determine whether the provided type is an integral type, or an enumeration 5543 /// type of a permitted flavor. 5544 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5545 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5546 : T->isIntegralOrUnscopedEnumerationType(); 5547 } 5548 5549 static ExprResult 5550 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5551 Sema::ContextualImplicitConverter &Converter, 5552 QualType T, UnresolvedSetImpl &ViableConversions) { 5553 5554 if (Converter.Suppress) 5555 return ExprError(); 5556 5557 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5558 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5559 CXXConversionDecl *Conv = 5560 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5561 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5562 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5563 } 5564 return From; 5565 } 5566 5567 static bool 5568 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5569 Sema::ContextualImplicitConverter &Converter, 5570 QualType T, bool HadMultipleCandidates, 5571 UnresolvedSetImpl &ExplicitConversions) { 5572 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5573 DeclAccessPair Found = ExplicitConversions[0]; 5574 CXXConversionDecl *Conversion = 5575 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5576 5577 // The user probably meant to invoke the given explicit 5578 // conversion; use it. 5579 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5580 std::string TypeStr; 5581 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5582 5583 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5584 << FixItHint::CreateInsertion(From->getBeginLoc(), 5585 "static_cast<" + TypeStr + ">(") 5586 << FixItHint::CreateInsertion( 5587 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5588 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5589 5590 // If we aren't in a SFINAE context, build a call to the 5591 // explicit conversion function. 5592 if (SemaRef.isSFINAEContext()) 5593 return true; 5594 5595 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5596 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5597 HadMultipleCandidates); 5598 if (Result.isInvalid()) 5599 return true; 5600 // Record usage of conversion in an implicit cast. 5601 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5602 CK_UserDefinedConversion, Result.get(), 5603 nullptr, Result.get()->getValueKind()); 5604 } 5605 return false; 5606 } 5607 5608 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5609 Sema::ContextualImplicitConverter &Converter, 5610 QualType T, bool HadMultipleCandidates, 5611 DeclAccessPair &Found) { 5612 CXXConversionDecl *Conversion = 5613 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5614 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5615 5616 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5617 if (!Converter.SuppressConversion) { 5618 if (SemaRef.isSFINAEContext()) 5619 return true; 5620 5621 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5622 << From->getSourceRange(); 5623 } 5624 5625 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5626 HadMultipleCandidates); 5627 if (Result.isInvalid()) 5628 return true; 5629 // Record usage of conversion in an implicit cast. 5630 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5631 CK_UserDefinedConversion, Result.get(), 5632 nullptr, Result.get()->getValueKind()); 5633 return false; 5634 } 5635 5636 static ExprResult finishContextualImplicitConversion( 5637 Sema &SemaRef, SourceLocation Loc, Expr *From, 5638 Sema::ContextualImplicitConverter &Converter) { 5639 if (!Converter.match(From->getType()) && !Converter.Suppress) 5640 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5641 << From->getSourceRange(); 5642 5643 return SemaRef.DefaultLvalueConversion(From); 5644 } 5645 5646 static void 5647 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5648 UnresolvedSetImpl &ViableConversions, 5649 OverloadCandidateSet &CandidateSet) { 5650 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5651 DeclAccessPair FoundDecl = ViableConversions[I]; 5652 NamedDecl *D = FoundDecl.getDecl(); 5653 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5654 if (isa<UsingShadowDecl>(D)) 5655 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5656 5657 CXXConversionDecl *Conv; 5658 FunctionTemplateDecl *ConvTemplate; 5659 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5660 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5661 else 5662 Conv = cast<CXXConversionDecl>(D); 5663 5664 if (ConvTemplate) 5665 SemaRef.AddTemplateConversionCandidate( 5666 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5667 /*AllowObjCConversionOnExplicit=*/false); 5668 else 5669 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5670 ToType, CandidateSet, 5671 /*AllowObjCConversionOnExplicit=*/false); 5672 } 5673 } 5674 5675 /// Attempt to convert the given expression to a type which is accepted 5676 /// by the given converter. 5677 /// 5678 /// This routine will attempt to convert an expression of class type to a 5679 /// type accepted by the specified converter. In C++11 and before, the class 5680 /// must have a single non-explicit conversion function converting to a matching 5681 /// type. In C++1y, there can be multiple such conversion functions, but only 5682 /// one target type. 5683 /// 5684 /// \param Loc The source location of the construct that requires the 5685 /// conversion. 5686 /// 5687 /// \param From The expression we're converting from. 5688 /// 5689 /// \param Converter Used to control and diagnose the conversion process. 5690 /// 5691 /// \returns The expression, converted to an integral or enumeration type if 5692 /// successful. 5693 ExprResult Sema::PerformContextualImplicitConversion( 5694 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5695 // We can't perform any more checking for type-dependent expressions. 5696 if (From->isTypeDependent()) 5697 return From; 5698 5699 // Process placeholders immediately. 5700 if (From->hasPlaceholderType()) { 5701 ExprResult result = CheckPlaceholderExpr(From); 5702 if (result.isInvalid()) 5703 return result; 5704 From = result.get(); 5705 } 5706 5707 // If the expression already has a matching type, we're golden. 5708 QualType T = From->getType(); 5709 if (Converter.match(T)) 5710 return DefaultLvalueConversion(From); 5711 5712 // FIXME: Check for missing '()' if T is a function type? 5713 5714 // We can only perform contextual implicit conversions on objects of class 5715 // type. 5716 const RecordType *RecordTy = T->getAs<RecordType>(); 5717 if (!RecordTy || !getLangOpts().CPlusPlus) { 5718 if (!Converter.Suppress) 5719 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5720 return From; 5721 } 5722 5723 // We must have a complete class type. 5724 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5725 ContextualImplicitConverter &Converter; 5726 Expr *From; 5727 5728 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5729 : Converter(Converter), From(From) {} 5730 5731 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5732 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5733 } 5734 } IncompleteDiagnoser(Converter, From); 5735 5736 if (Converter.Suppress ? !isCompleteType(Loc, T) 5737 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5738 return From; 5739 5740 // Look for a conversion to an integral or enumeration type. 5741 UnresolvedSet<4> 5742 ViableConversions; // These are *potentially* viable in C++1y. 5743 UnresolvedSet<4> ExplicitConversions; 5744 const auto &Conversions = 5745 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5746 5747 bool HadMultipleCandidates = 5748 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5749 5750 // To check that there is only one target type, in C++1y: 5751 QualType ToType; 5752 bool HasUniqueTargetType = true; 5753 5754 // Collect explicit or viable (potentially in C++1y) conversions. 5755 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5756 NamedDecl *D = (*I)->getUnderlyingDecl(); 5757 CXXConversionDecl *Conversion; 5758 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5759 if (ConvTemplate) { 5760 if (getLangOpts().CPlusPlus14) 5761 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5762 else 5763 continue; // C++11 does not consider conversion operator templates(?). 5764 } else 5765 Conversion = cast<CXXConversionDecl>(D); 5766 5767 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5768 "Conversion operator templates are considered potentially " 5769 "viable in C++1y"); 5770 5771 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5772 if (Converter.match(CurToType) || ConvTemplate) { 5773 5774 if (Conversion->isExplicit()) { 5775 // FIXME: For C++1y, do we need this restriction? 5776 // cf. diagnoseNoViableConversion() 5777 if (!ConvTemplate) 5778 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5779 } else { 5780 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5781 if (ToType.isNull()) 5782 ToType = CurToType.getUnqualifiedType(); 5783 else if (HasUniqueTargetType && 5784 (CurToType.getUnqualifiedType() != ToType)) 5785 HasUniqueTargetType = false; 5786 } 5787 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5788 } 5789 } 5790 } 5791 5792 if (getLangOpts().CPlusPlus14) { 5793 // C++1y [conv]p6: 5794 // ... An expression e of class type E appearing in such a context 5795 // is said to be contextually implicitly converted to a specified 5796 // type T and is well-formed if and only if e can be implicitly 5797 // converted to a type T that is determined as follows: E is searched 5798 // for conversion functions whose return type is cv T or reference to 5799 // cv T such that T is allowed by the context. There shall be 5800 // exactly one such T. 5801 5802 // If no unique T is found: 5803 if (ToType.isNull()) { 5804 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5805 HadMultipleCandidates, 5806 ExplicitConversions)) 5807 return ExprError(); 5808 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5809 } 5810 5811 // If more than one unique Ts are found: 5812 if (!HasUniqueTargetType) 5813 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5814 ViableConversions); 5815 5816 // If one unique T is found: 5817 // First, build a candidate set from the previously recorded 5818 // potentially viable conversions. 5819 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5820 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5821 CandidateSet); 5822 5823 // Then, perform overload resolution over the candidate set. 5824 OverloadCandidateSet::iterator Best; 5825 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5826 case OR_Success: { 5827 // Apply this conversion. 5828 DeclAccessPair Found = 5829 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5830 if (recordConversion(*this, Loc, From, Converter, T, 5831 HadMultipleCandidates, Found)) 5832 return ExprError(); 5833 break; 5834 } 5835 case OR_Ambiguous: 5836 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5837 ViableConversions); 5838 case OR_No_Viable_Function: 5839 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5840 HadMultipleCandidates, 5841 ExplicitConversions)) 5842 return ExprError(); 5843 LLVM_FALLTHROUGH; 5844 case OR_Deleted: 5845 // We'll complain below about a non-integral condition type. 5846 break; 5847 } 5848 } else { 5849 switch (ViableConversions.size()) { 5850 case 0: { 5851 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5852 HadMultipleCandidates, 5853 ExplicitConversions)) 5854 return ExprError(); 5855 5856 // We'll complain below about a non-integral condition type. 5857 break; 5858 } 5859 case 1: { 5860 // Apply this conversion. 5861 DeclAccessPair Found = ViableConversions[0]; 5862 if (recordConversion(*this, Loc, From, Converter, T, 5863 HadMultipleCandidates, Found)) 5864 return ExprError(); 5865 break; 5866 } 5867 default: 5868 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5869 ViableConversions); 5870 } 5871 } 5872 5873 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5874 } 5875 5876 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5877 /// an acceptable non-member overloaded operator for a call whose 5878 /// arguments have types T1 (and, if non-empty, T2). This routine 5879 /// implements the check in C++ [over.match.oper]p3b2 concerning 5880 /// enumeration types. 5881 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5882 FunctionDecl *Fn, 5883 ArrayRef<Expr *> Args) { 5884 QualType T1 = Args[0]->getType(); 5885 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5886 5887 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5888 return true; 5889 5890 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5891 return true; 5892 5893 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5894 if (Proto->getNumParams() < 1) 5895 return false; 5896 5897 if (T1->isEnumeralType()) { 5898 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5899 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5900 return true; 5901 } 5902 5903 if (Proto->getNumParams() < 2) 5904 return false; 5905 5906 if (!T2.isNull() && T2->isEnumeralType()) { 5907 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5908 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5909 return true; 5910 } 5911 5912 return false; 5913 } 5914 5915 /// AddOverloadCandidate - Adds the given function to the set of 5916 /// candidate functions, using the given function call arguments. If 5917 /// @p SuppressUserConversions, then don't allow user-defined 5918 /// conversions via constructors or conversion operators. 5919 /// 5920 /// \param PartialOverloading true if we are performing "partial" overloading 5921 /// based on an incomplete set of function arguments. This feature is used by 5922 /// code completion. 5923 void 5924 Sema::AddOverloadCandidate(FunctionDecl *Function, 5925 DeclAccessPair FoundDecl, 5926 ArrayRef<Expr *> Args, 5927 OverloadCandidateSet &CandidateSet, 5928 bool SuppressUserConversions, 5929 bool PartialOverloading, 5930 bool AllowExplicit, 5931 ConversionSequenceList EarlyConversions) { 5932 const FunctionProtoType *Proto 5933 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5934 assert(Proto && "Functions without a prototype cannot be overloaded"); 5935 assert(!Function->getDescribedFunctionTemplate() && 5936 "Use AddTemplateOverloadCandidate for function templates"); 5937 5938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5939 if (!isa<CXXConstructorDecl>(Method)) { 5940 // If we get here, it's because we're calling a member function 5941 // that is named without a member access expression (e.g., 5942 // "this->f") that was either written explicitly or created 5943 // implicitly. This can happen with a qualified call to a member 5944 // function, e.g., X::f(). We use an empty type for the implied 5945 // object argument (C++ [over.call.func]p3), and the acting context 5946 // is irrelevant. 5947 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5948 Expr::Classification::makeSimpleLValue(), Args, 5949 CandidateSet, SuppressUserConversions, 5950 PartialOverloading, EarlyConversions); 5951 return; 5952 } 5953 // We treat a constructor like a non-member function, since its object 5954 // argument doesn't participate in overload resolution. 5955 } 5956 5957 if (!CandidateSet.isNewCandidate(Function)) 5958 return; 5959 5960 // C++ [over.match.oper]p3: 5961 // if no operand has a class type, only those non-member functions in the 5962 // lookup set that have a first parameter of type T1 or "reference to 5963 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5964 // is a right operand) a second parameter of type T2 or "reference to 5965 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5966 // candidate functions. 5967 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5968 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5969 return; 5970 5971 // C++11 [class.copy]p11: [DR1402] 5972 // A defaulted move constructor that is defined as deleted is ignored by 5973 // overload resolution. 5974 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5975 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5976 Constructor->isMoveConstructor()) 5977 return; 5978 5979 // Overload resolution is always an unevaluated context. 5980 EnterExpressionEvaluationContext Unevaluated( 5981 *this, Sema::ExpressionEvaluationContext::Unevaluated); 5982 5983 // Add this candidate 5984 OverloadCandidate &Candidate = 5985 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5986 Candidate.FoundDecl = FoundDecl; 5987 Candidate.Function = Function; 5988 Candidate.Viable = true; 5989 Candidate.IsSurrogate = false; 5990 Candidate.IgnoreObjectArgument = false; 5991 Candidate.ExplicitCallArguments = Args.size(); 5992 5993 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 5994 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 5995 Candidate.Viable = false; 5996 Candidate.FailureKind = ovl_non_default_multiversion_function; 5997 return; 5998 } 5999 6000 if (Constructor) { 6001 // C++ [class.copy]p3: 6002 // A member function template is never instantiated to perform the copy 6003 // of a class object to an object of its class type. 6004 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6005 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6006 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6007 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6008 ClassType))) { 6009 Candidate.Viable = false; 6010 Candidate.FailureKind = ovl_fail_illegal_constructor; 6011 return; 6012 } 6013 6014 // C++ [over.match.funcs]p8: (proposed DR resolution) 6015 // A constructor inherited from class type C that has a first parameter 6016 // of type "reference to P" (including such a constructor instantiated 6017 // from a template) is excluded from the set of candidate functions when 6018 // constructing an object of type cv D if the argument list has exactly 6019 // one argument and D is reference-related to P and P is reference-related 6020 // to C. 6021 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6022 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6023 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6024 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6025 QualType C = Context.getRecordType(Constructor->getParent()); 6026 QualType D = Context.getRecordType(Shadow->getParent()); 6027 SourceLocation Loc = Args.front()->getExprLoc(); 6028 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6029 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6030 Candidate.Viable = false; 6031 Candidate.FailureKind = ovl_fail_inhctor_slice; 6032 return; 6033 } 6034 } 6035 } 6036 6037 unsigned NumParams = Proto->getNumParams(); 6038 6039 // (C++ 13.3.2p2): A candidate function having fewer than m 6040 // parameters is viable only if it has an ellipsis in its parameter 6041 // list (8.3.5). 6042 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6043 !Proto->isVariadic()) { 6044 Candidate.Viable = false; 6045 Candidate.FailureKind = ovl_fail_too_many_arguments; 6046 return; 6047 } 6048 6049 // (C++ 13.3.2p2): A candidate function having more than m parameters 6050 // is viable only if the (m+1)st parameter has a default argument 6051 // (8.3.6). For the purposes of overload resolution, the 6052 // parameter list is truncated on the right, so that there are 6053 // exactly m parameters. 6054 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6055 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6056 // Not enough arguments. 6057 Candidate.Viable = false; 6058 Candidate.FailureKind = ovl_fail_too_few_arguments; 6059 return; 6060 } 6061 6062 // (CUDA B.1): Check for invalid calls between targets. 6063 if (getLangOpts().CUDA) 6064 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6065 // Skip the check for callers that are implicit members, because in this 6066 // case we may not yet know what the member's target is; the target is 6067 // inferred for the member automatically, based on the bases and fields of 6068 // the class. 6069 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6070 Candidate.Viable = false; 6071 Candidate.FailureKind = ovl_fail_bad_target; 6072 return; 6073 } 6074 6075 // Determine the implicit conversion sequences for each of the 6076 // arguments. 6077 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6078 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6079 // We already formed a conversion sequence for this parameter during 6080 // template argument deduction. 6081 } else if (ArgIdx < NumParams) { 6082 // (C++ 13.3.2p3): for F to be a viable function, there shall 6083 // exist for each argument an implicit conversion sequence 6084 // (13.3.3.1) that converts that argument to the corresponding 6085 // parameter of F. 6086 QualType ParamType = Proto->getParamType(ArgIdx); 6087 Candidate.Conversions[ArgIdx] 6088 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6089 SuppressUserConversions, 6090 /*InOverloadResolution=*/true, 6091 /*AllowObjCWritebackConversion=*/ 6092 getLangOpts().ObjCAutoRefCount, 6093 AllowExplicit); 6094 if (Candidate.Conversions[ArgIdx].isBad()) { 6095 Candidate.Viable = false; 6096 Candidate.FailureKind = ovl_fail_bad_conversion; 6097 return; 6098 } 6099 } else { 6100 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6101 // argument for which there is no corresponding parameter is 6102 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6103 Candidate.Conversions[ArgIdx].setEllipsis(); 6104 } 6105 } 6106 6107 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6108 Candidate.Viable = false; 6109 Candidate.FailureKind = ovl_fail_enable_if; 6110 Candidate.DeductionFailure.Data = FailedAttr; 6111 return; 6112 } 6113 6114 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6115 Candidate.Viable = false; 6116 Candidate.FailureKind = ovl_fail_ext_disabled; 6117 return; 6118 } 6119 } 6120 6121 ObjCMethodDecl * 6122 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6123 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6124 if (Methods.size() <= 1) 6125 return nullptr; 6126 6127 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6128 bool Match = true; 6129 ObjCMethodDecl *Method = Methods[b]; 6130 unsigned NumNamedArgs = Sel.getNumArgs(); 6131 // Method might have more arguments than selector indicates. This is due 6132 // to addition of c-style arguments in method. 6133 if (Method->param_size() > NumNamedArgs) 6134 NumNamedArgs = Method->param_size(); 6135 if (Args.size() < NumNamedArgs) 6136 continue; 6137 6138 for (unsigned i = 0; i < NumNamedArgs; i++) { 6139 // We can't do any type-checking on a type-dependent argument. 6140 if (Args[i]->isTypeDependent()) { 6141 Match = false; 6142 break; 6143 } 6144 6145 ParmVarDecl *param = Method->parameters()[i]; 6146 Expr *argExpr = Args[i]; 6147 assert(argExpr && "SelectBestMethod(): missing expression"); 6148 6149 // Strip the unbridged-cast placeholder expression off unless it's 6150 // a consumed argument. 6151 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6152 !param->hasAttr<CFConsumedAttr>()) 6153 argExpr = stripARCUnbridgedCast(argExpr); 6154 6155 // If the parameter is __unknown_anytype, move on to the next method. 6156 if (param->getType() == Context.UnknownAnyTy) { 6157 Match = false; 6158 break; 6159 } 6160 6161 ImplicitConversionSequence ConversionState 6162 = TryCopyInitialization(*this, argExpr, param->getType(), 6163 /*SuppressUserConversions*/false, 6164 /*InOverloadResolution=*/true, 6165 /*AllowObjCWritebackConversion=*/ 6166 getLangOpts().ObjCAutoRefCount, 6167 /*AllowExplicit*/false); 6168 // This function looks for a reasonably-exact match, so we consider 6169 // incompatible pointer conversions to be a failure here. 6170 if (ConversionState.isBad() || 6171 (ConversionState.isStandard() && 6172 ConversionState.Standard.Second == 6173 ICK_Incompatible_Pointer_Conversion)) { 6174 Match = false; 6175 break; 6176 } 6177 } 6178 // Promote additional arguments to variadic methods. 6179 if (Match && Method->isVariadic()) { 6180 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6181 if (Args[i]->isTypeDependent()) { 6182 Match = false; 6183 break; 6184 } 6185 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6186 nullptr); 6187 if (Arg.isInvalid()) { 6188 Match = false; 6189 break; 6190 } 6191 } 6192 } else { 6193 // Check for extra arguments to non-variadic methods. 6194 if (Args.size() != NumNamedArgs) 6195 Match = false; 6196 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6197 // Special case when selectors have no argument. In this case, select 6198 // one with the most general result type of 'id'. 6199 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6200 QualType ReturnT = Methods[b]->getReturnType(); 6201 if (ReturnT->isObjCIdType()) 6202 return Methods[b]; 6203 } 6204 } 6205 } 6206 6207 if (Match) 6208 return Method; 6209 } 6210 return nullptr; 6211 } 6212 6213 static bool 6214 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6215 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6216 bool MissingImplicitThis, Expr *&ConvertedThis, 6217 SmallVectorImpl<Expr *> &ConvertedArgs) { 6218 if (ThisArg) { 6219 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6220 assert(!isa<CXXConstructorDecl>(Method) && 6221 "Shouldn't have `this` for ctors!"); 6222 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6223 ExprResult R = S.PerformObjectArgumentInitialization( 6224 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6225 if (R.isInvalid()) 6226 return false; 6227 ConvertedThis = R.get(); 6228 } else { 6229 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6230 (void)MD; 6231 assert((MissingImplicitThis || MD->isStatic() || 6232 isa<CXXConstructorDecl>(MD)) && 6233 "Expected `this` for non-ctor instance methods"); 6234 } 6235 ConvertedThis = nullptr; 6236 } 6237 6238 // Ignore any variadic arguments. Converting them is pointless, since the 6239 // user can't refer to them in the function condition. 6240 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6241 6242 // Convert the arguments. 6243 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6244 ExprResult R; 6245 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6246 S.Context, Function->getParamDecl(I)), 6247 SourceLocation(), Args[I]); 6248 6249 if (R.isInvalid()) 6250 return false; 6251 6252 ConvertedArgs.push_back(R.get()); 6253 } 6254 6255 if (Trap.hasErrorOccurred()) 6256 return false; 6257 6258 // Push default arguments if needed. 6259 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6260 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6261 ParmVarDecl *P = Function->getParamDecl(i); 6262 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6263 ? P->getUninstantiatedDefaultArg() 6264 : P->getDefaultArg(); 6265 // This can only happen in code completion, i.e. when PartialOverloading 6266 // is true. 6267 if (!DefArg) 6268 return false; 6269 ExprResult R = 6270 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6271 S.Context, Function->getParamDecl(i)), 6272 SourceLocation(), DefArg); 6273 if (R.isInvalid()) 6274 return false; 6275 ConvertedArgs.push_back(R.get()); 6276 } 6277 6278 if (Trap.hasErrorOccurred()) 6279 return false; 6280 } 6281 return true; 6282 } 6283 6284 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6285 bool MissingImplicitThis) { 6286 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6287 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6288 return nullptr; 6289 6290 SFINAETrap Trap(*this); 6291 SmallVector<Expr *, 16> ConvertedArgs; 6292 // FIXME: We should look into making enable_if late-parsed. 6293 Expr *DiscardedThis; 6294 if (!convertArgsForAvailabilityChecks( 6295 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6296 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6297 return *EnableIfAttrs.begin(); 6298 6299 for (auto *EIA : EnableIfAttrs) { 6300 APValue Result; 6301 // FIXME: This doesn't consider value-dependent cases, because doing so is 6302 // very difficult. Ideally, we should handle them more gracefully. 6303 if (!EIA->getCond()->EvaluateWithSubstitution( 6304 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6305 return EIA; 6306 6307 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6308 return EIA; 6309 } 6310 return nullptr; 6311 } 6312 6313 template <typename CheckFn> 6314 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6315 bool ArgDependent, SourceLocation Loc, 6316 CheckFn &&IsSuccessful) { 6317 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6318 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6319 if (ArgDependent == DIA->getArgDependent()) 6320 Attrs.push_back(DIA); 6321 } 6322 6323 // Common case: No diagnose_if attributes, so we can quit early. 6324 if (Attrs.empty()) 6325 return false; 6326 6327 auto WarningBegin = std::stable_partition( 6328 Attrs.begin(), Attrs.end(), 6329 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6330 6331 // Note that diagnose_if attributes are late-parsed, so they appear in the 6332 // correct order (unlike enable_if attributes). 6333 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6334 IsSuccessful); 6335 if (ErrAttr != WarningBegin) { 6336 const DiagnoseIfAttr *DIA = *ErrAttr; 6337 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6338 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6339 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6340 return true; 6341 } 6342 6343 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6344 if (IsSuccessful(DIA)) { 6345 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6346 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6347 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6348 } 6349 6350 return false; 6351 } 6352 6353 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6354 const Expr *ThisArg, 6355 ArrayRef<const Expr *> Args, 6356 SourceLocation Loc) { 6357 return diagnoseDiagnoseIfAttrsWith( 6358 *this, Function, /*ArgDependent=*/true, Loc, 6359 [&](const DiagnoseIfAttr *DIA) { 6360 APValue Result; 6361 // It's sane to use the same Args for any redecl of this function, since 6362 // EvaluateWithSubstitution only cares about the position of each 6363 // argument in the arg list, not the ParmVarDecl* it maps to. 6364 if (!DIA->getCond()->EvaluateWithSubstitution( 6365 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6366 return false; 6367 return Result.isInt() && Result.getInt().getBoolValue(); 6368 }); 6369 } 6370 6371 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6372 SourceLocation Loc) { 6373 return diagnoseDiagnoseIfAttrsWith( 6374 *this, ND, /*ArgDependent=*/false, Loc, 6375 [&](const DiagnoseIfAttr *DIA) { 6376 bool Result; 6377 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6378 Result; 6379 }); 6380 } 6381 6382 /// Add all of the function declarations in the given function set to 6383 /// the overload candidate set. 6384 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6385 ArrayRef<Expr *> Args, 6386 OverloadCandidateSet &CandidateSet, 6387 TemplateArgumentListInfo *ExplicitTemplateArgs, 6388 bool SuppressUserConversions, 6389 bool PartialOverloading, 6390 bool FirstArgumentIsBase) { 6391 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6392 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6393 ArrayRef<Expr *> FunctionArgs = Args; 6394 6395 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6396 FunctionDecl *FD = 6397 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6398 6399 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6400 QualType ObjectType; 6401 Expr::Classification ObjectClassification; 6402 if (Args.size() > 0) { 6403 if (Expr *E = Args[0]) { 6404 // Use the explicit base to restrict the lookup: 6405 ObjectType = E->getType(); 6406 ObjectClassification = E->Classify(Context); 6407 } // .. else there is an implicit base. 6408 FunctionArgs = Args.slice(1); 6409 } 6410 if (FunTmpl) { 6411 AddMethodTemplateCandidate( 6412 FunTmpl, F.getPair(), 6413 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6414 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6415 FunctionArgs, CandidateSet, SuppressUserConversions, 6416 PartialOverloading); 6417 } else { 6418 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6419 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6420 ObjectClassification, FunctionArgs, CandidateSet, 6421 SuppressUserConversions, PartialOverloading); 6422 } 6423 } else { 6424 // This branch handles both standalone functions and static methods. 6425 6426 // Slice the first argument (which is the base) when we access 6427 // static method as non-static. 6428 if (Args.size() > 0 && 6429 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6430 !isa<CXXConstructorDecl>(FD)))) { 6431 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6432 FunctionArgs = Args.slice(1); 6433 } 6434 if (FunTmpl) { 6435 AddTemplateOverloadCandidate( 6436 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6437 CandidateSet, SuppressUserConversions, PartialOverloading); 6438 } else { 6439 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6440 SuppressUserConversions, 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() && Method->hasAttr<TargetAttr>() && 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(), VK_LValue, 6946 From->getBeginLoc()); 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->getBeginLoc(), 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->getBeginLoc()); 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() && Conversion->hasAttr<TargetAttr>() && 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 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 8947 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 8948 8949 auto Cand1I = Cand1Attrs.begin(); 8950 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8951 for (EnableIfAttr *Cand2A : Cand2Attrs) { 8952 Cand1ID.clear(); 8953 Cand2ID.clear(); 8954 8955 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8956 // has fewer enable_if attributes than Cand2. 8957 auto Cand1A = Cand1I++; 8958 if (Cand1A == Cand1Attrs.end()) 8959 return Comparison::Worse; 8960 8961 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8962 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8963 if (Cand1ID != Cand2ID) 8964 return Comparison::Worse; 8965 } 8966 8967 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8968 } 8969 8970 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 8971 const OverloadCandidate &Cand2) { 8972 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 8973 !Cand2.Function->isMultiVersion()) 8974 return false; 8975 8976 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 8977 // cpu_dispatch, else arbitrarily based on the identifiers. 8978 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 8979 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 8980 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 8981 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 8982 8983 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 8984 return false; 8985 8986 if (Cand1CPUDisp && !Cand2CPUDisp) 8987 return true; 8988 if (Cand2CPUDisp && !Cand1CPUDisp) 8989 return false; 8990 8991 if (Cand1CPUSpec && Cand2CPUSpec) { 8992 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 8993 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 8994 8995 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 8996 FirstDiff = std::mismatch( 8997 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 8998 Cand2CPUSpec->cpus_begin(), 8999 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9000 return LHS->getName() == RHS->getName(); 9001 }); 9002 9003 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9004 "Two different cpu-specific versions should not have the same " 9005 "identifier list, otherwise they'd be the same decl!"); 9006 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9007 } 9008 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9009 } 9010 9011 /// isBetterOverloadCandidate - Determines whether the first overload 9012 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9013 bool clang::isBetterOverloadCandidate( 9014 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9015 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9016 // Define viable functions to be better candidates than non-viable 9017 // functions. 9018 if (!Cand2.Viable) 9019 return Cand1.Viable; 9020 else if (!Cand1.Viable) 9021 return false; 9022 9023 // C++ [over.match.best]p1: 9024 // 9025 // -- if F is a static member function, ICS1(F) is defined such 9026 // that ICS1(F) is neither better nor worse than ICS1(G) for 9027 // any function G, and, symmetrically, ICS1(G) is neither 9028 // better nor worse than ICS1(F). 9029 unsigned StartArg = 0; 9030 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9031 StartArg = 1; 9032 9033 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9034 // We don't allow incompatible pointer conversions in C++. 9035 if (!S.getLangOpts().CPlusPlus) 9036 return ICS.isStandard() && 9037 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9038 9039 // The only ill-formed conversion we allow in C++ is the string literal to 9040 // char* conversion, which is only considered ill-formed after C++11. 9041 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9042 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9043 }; 9044 9045 // Define functions that don't require ill-formed conversions for a given 9046 // argument to be better candidates than functions that do. 9047 unsigned NumArgs = Cand1.Conversions.size(); 9048 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9049 bool HasBetterConversion = false; 9050 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9051 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9052 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9053 if (Cand1Bad != Cand2Bad) { 9054 if (Cand1Bad) 9055 return false; 9056 HasBetterConversion = true; 9057 } 9058 } 9059 9060 if (HasBetterConversion) 9061 return true; 9062 9063 // C++ [over.match.best]p1: 9064 // A viable function F1 is defined to be a better function than another 9065 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9066 // conversion sequence than ICSi(F2), and then... 9067 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9068 switch (CompareImplicitConversionSequences(S, Loc, 9069 Cand1.Conversions[ArgIdx], 9070 Cand2.Conversions[ArgIdx])) { 9071 case ImplicitConversionSequence::Better: 9072 // Cand1 has a better conversion sequence. 9073 HasBetterConversion = true; 9074 break; 9075 9076 case ImplicitConversionSequence::Worse: 9077 // Cand1 can't be better than Cand2. 9078 return false; 9079 9080 case ImplicitConversionSequence::Indistinguishable: 9081 // Do nothing. 9082 break; 9083 } 9084 } 9085 9086 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9087 // ICSj(F2), or, if not that, 9088 if (HasBetterConversion) 9089 return true; 9090 9091 // -- the context is an initialization by user-defined conversion 9092 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9093 // from the return type of F1 to the destination type (i.e., 9094 // the type of the entity being initialized) is a better 9095 // conversion sequence than the standard conversion sequence 9096 // from the return type of F2 to the destination type. 9097 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9098 Cand1.Function && Cand2.Function && 9099 isa<CXXConversionDecl>(Cand1.Function) && 9100 isa<CXXConversionDecl>(Cand2.Function)) { 9101 // First check whether we prefer one of the conversion functions over the 9102 // other. This only distinguishes the results in non-standard, extension 9103 // cases such as the conversion from a lambda closure type to a function 9104 // pointer or block. 9105 ImplicitConversionSequence::CompareKind Result = 9106 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9107 if (Result == ImplicitConversionSequence::Indistinguishable) 9108 Result = CompareStandardConversionSequences(S, Loc, 9109 Cand1.FinalConversion, 9110 Cand2.FinalConversion); 9111 9112 if (Result != ImplicitConversionSequence::Indistinguishable) 9113 return Result == ImplicitConversionSequence::Better; 9114 9115 // FIXME: Compare kind of reference binding if conversion functions 9116 // convert to a reference type used in direct reference binding, per 9117 // C++14 [over.match.best]p1 section 2 bullet 3. 9118 } 9119 9120 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9121 // as combined with the resolution to CWG issue 243. 9122 // 9123 // When the context is initialization by constructor ([over.match.ctor] or 9124 // either phase of [over.match.list]), a constructor is preferred over 9125 // a conversion function. 9126 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9127 Cand1.Function && Cand2.Function && 9128 isa<CXXConstructorDecl>(Cand1.Function) != 9129 isa<CXXConstructorDecl>(Cand2.Function)) 9130 return isa<CXXConstructorDecl>(Cand1.Function); 9131 9132 // -- F1 is a non-template function and F2 is a function template 9133 // specialization, or, if not that, 9134 bool Cand1IsSpecialization = Cand1.Function && 9135 Cand1.Function->getPrimaryTemplate(); 9136 bool Cand2IsSpecialization = Cand2.Function && 9137 Cand2.Function->getPrimaryTemplate(); 9138 if (Cand1IsSpecialization != Cand2IsSpecialization) 9139 return Cand2IsSpecialization; 9140 9141 // -- F1 and F2 are function template specializations, and the function 9142 // template for F1 is more specialized than the template for F2 9143 // according to the partial ordering rules described in 14.5.5.2, or, 9144 // if not that, 9145 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9146 if (FunctionTemplateDecl *BetterTemplate 9147 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9148 Cand2.Function->getPrimaryTemplate(), 9149 Loc, 9150 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9151 : TPOC_Call, 9152 Cand1.ExplicitCallArguments, 9153 Cand2.ExplicitCallArguments)) 9154 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9155 } 9156 9157 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9158 // A derived-class constructor beats an (inherited) base class constructor. 9159 bool Cand1IsInherited = 9160 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9161 bool Cand2IsInherited = 9162 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9163 if (Cand1IsInherited != Cand2IsInherited) 9164 return Cand2IsInherited; 9165 else if (Cand1IsInherited) { 9166 assert(Cand2IsInherited); 9167 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9168 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9169 if (Cand1Class->isDerivedFrom(Cand2Class)) 9170 return true; 9171 if (Cand2Class->isDerivedFrom(Cand1Class)) 9172 return false; 9173 // Inherited from sibling base classes: still ambiguous. 9174 } 9175 9176 // Check C++17 tie-breakers for deduction guides. 9177 { 9178 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9179 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9180 if (Guide1 && Guide2) { 9181 // -- F1 is generated from a deduction-guide and F2 is not 9182 if (Guide1->isImplicit() != Guide2->isImplicit()) 9183 return Guide2->isImplicit(); 9184 9185 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9186 if (Guide1->isCopyDeductionCandidate()) 9187 return true; 9188 } 9189 } 9190 9191 // Check for enable_if value-based overload resolution. 9192 if (Cand1.Function && Cand2.Function) { 9193 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9194 if (Cmp != Comparison::Equal) 9195 return Cmp == Comparison::Better; 9196 } 9197 9198 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9199 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9200 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9201 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9202 } 9203 9204 bool HasPS1 = Cand1.Function != nullptr && 9205 functionHasPassObjectSizeParams(Cand1.Function); 9206 bool HasPS2 = Cand2.Function != nullptr && 9207 functionHasPassObjectSizeParams(Cand2.Function); 9208 if (HasPS1 != HasPS2 && HasPS1) 9209 return true; 9210 9211 return isBetterMultiversionCandidate(Cand1, Cand2); 9212 } 9213 9214 /// Determine whether two declarations are "equivalent" for the purposes of 9215 /// name lookup and overload resolution. This applies when the same internal/no 9216 /// linkage entity is defined by two modules (probably by textually including 9217 /// the same header). In such a case, we don't consider the declarations to 9218 /// declare the same entity, but we also don't want lookups with both 9219 /// declarations visible to be ambiguous in some cases (this happens when using 9220 /// a modularized libstdc++). 9221 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9222 const NamedDecl *B) { 9223 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9224 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9225 if (!VA || !VB) 9226 return false; 9227 9228 // The declarations must be declaring the same name as an internal linkage 9229 // entity in different modules. 9230 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9231 VB->getDeclContext()->getRedeclContext()) || 9232 getOwningModule(const_cast<ValueDecl *>(VA)) == 9233 getOwningModule(const_cast<ValueDecl *>(VB)) || 9234 VA->isExternallyVisible() || VB->isExternallyVisible()) 9235 return false; 9236 9237 // Check that the declarations appear to be equivalent. 9238 // 9239 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9240 // For constants and functions, we should check the initializer or body is 9241 // the same. For non-constant variables, we shouldn't allow it at all. 9242 if (Context.hasSameType(VA->getType(), VB->getType())) 9243 return true; 9244 9245 // Enum constants within unnamed enumerations will have different types, but 9246 // may still be similar enough to be interchangeable for our purposes. 9247 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9248 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9249 // Only handle anonymous enums. If the enumerations were named and 9250 // equivalent, they would have been merged to the same type. 9251 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9252 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9253 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9254 !Context.hasSameType(EnumA->getIntegerType(), 9255 EnumB->getIntegerType())) 9256 return false; 9257 // Allow this only if the value is the same for both enumerators. 9258 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9259 } 9260 } 9261 9262 // Nothing else is sufficiently similar. 9263 return false; 9264 } 9265 9266 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9267 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9268 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9269 9270 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9271 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9272 << !M << (M ? M->getFullModuleName() : ""); 9273 9274 for (auto *E : Equiv) { 9275 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9276 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9277 << !M << (M ? M->getFullModuleName() : ""); 9278 } 9279 } 9280 9281 /// Computes the best viable function (C++ 13.3.3) 9282 /// within an overload candidate set. 9283 /// 9284 /// \param Loc The location of the function name (or operator symbol) for 9285 /// which overload resolution occurs. 9286 /// 9287 /// \param Best If overload resolution was successful or found a deleted 9288 /// function, \p Best points to the candidate function found. 9289 /// 9290 /// \returns The result of overload resolution. 9291 OverloadingResult 9292 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9293 iterator &Best) { 9294 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9295 std::transform(begin(), end(), std::back_inserter(Candidates), 9296 [](OverloadCandidate &Cand) { return &Cand; }); 9297 9298 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9299 // are accepted by both clang and NVCC. However, during a particular 9300 // compilation mode only one call variant is viable. We need to 9301 // exclude non-viable overload candidates from consideration based 9302 // only on their host/device attributes. Specifically, if one 9303 // candidate call is WrongSide and the other is SameSide, we ignore 9304 // the WrongSide candidate. 9305 if (S.getLangOpts().CUDA) { 9306 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9307 bool ContainsSameSideCandidate = 9308 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9309 return Cand->Function && 9310 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9311 Sema::CFP_SameSide; 9312 }); 9313 if (ContainsSameSideCandidate) { 9314 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9315 return Cand->Function && 9316 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9317 Sema::CFP_WrongSide; 9318 }; 9319 llvm::erase_if(Candidates, IsWrongSideCandidate); 9320 } 9321 } 9322 9323 // Find the best viable function. 9324 Best = end(); 9325 for (auto *Cand : Candidates) 9326 if (Cand->Viable) 9327 if (Best == end() || 9328 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9329 Best = Cand; 9330 9331 // If we didn't find any viable functions, abort. 9332 if (Best == end()) 9333 return OR_No_Viable_Function; 9334 9335 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9336 9337 // Make sure that this function is better than every other viable 9338 // function. If not, we have an ambiguity. 9339 for (auto *Cand : Candidates) { 9340 if (Cand->Viable && Cand != Best && 9341 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9342 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9343 Cand->Function)) { 9344 EquivalentCands.push_back(Cand->Function); 9345 continue; 9346 } 9347 9348 Best = end(); 9349 return OR_Ambiguous; 9350 } 9351 } 9352 9353 // Best is the best viable function. 9354 if (Best->Function && 9355 (Best->Function->isDeleted() || 9356 S.isFunctionConsideredUnavailable(Best->Function))) 9357 return OR_Deleted; 9358 9359 if (!EquivalentCands.empty()) 9360 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9361 EquivalentCands); 9362 9363 return OR_Success; 9364 } 9365 9366 namespace { 9367 9368 enum OverloadCandidateKind { 9369 oc_function, 9370 oc_method, 9371 oc_constructor, 9372 oc_implicit_default_constructor, 9373 oc_implicit_copy_constructor, 9374 oc_implicit_move_constructor, 9375 oc_implicit_copy_assignment, 9376 oc_implicit_move_assignment, 9377 oc_inherited_constructor 9378 }; 9379 9380 enum OverloadCandidateSelect { 9381 ocs_non_template, 9382 ocs_template, 9383 ocs_described_template, 9384 }; 9385 9386 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9387 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9388 std::string &Description) { 9389 9390 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9391 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9392 isTemplate = true; 9393 Description = S.getTemplateArgumentBindingsText( 9394 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9395 } 9396 9397 OverloadCandidateSelect Select = [&]() { 9398 if (!Description.empty()) 9399 return ocs_described_template; 9400 return isTemplate ? ocs_template : ocs_non_template; 9401 }(); 9402 9403 OverloadCandidateKind Kind = [&]() { 9404 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9405 if (!Ctor->isImplicit()) { 9406 if (isa<ConstructorUsingShadowDecl>(Found)) 9407 return oc_inherited_constructor; 9408 else 9409 return oc_constructor; 9410 } 9411 9412 if (Ctor->isDefaultConstructor()) 9413 return oc_implicit_default_constructor; 9414 9415 if (Ctor->isMoveConstructor()) 9416 return oc_implicit_move_constructor; 9417 9418 assert(Ctor->isCopyConstructor() && 9419 "unexpected sort of implicit constructor"); 9420 return oc_implicit_copy_constructor; 9421 } 9422 9423 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9424 // This actually gets spelled 'candidate function' for now, but 9425 // it doesn't hurt to split it out. 9426 if (!Meth->isImplicit()) 9427 return oc_method; 9428 9429 if (Meth->isMoveAssignmentOperator()) 9430 return oc_implicit_move_assignment; 9431 9432 if (Meth->isCopyAssignmentOperator()) 9433 return oc_implicit_copy_assignment; 9434 9435 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9436 return oc_method; 9437 } 9438 9439 return oc_function; 9440 }(); 9441 9442 return std::make_pair(Kind, Select); 9443 } 9444 9445 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9446 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9447 // set. 9448 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9449 S.Diag(FoundDecl->getLocation(), 9450 diag::note_ovl_candidate_inherited_constructor) 9451 << Shadow->getNominatedBaseClass(); 9452 } 9453 9454 } // end anonymous namespace 9455 9456 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9457 const FunctionDecl *FD) { 9458 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9459 bool AlwaysTrue; 9460 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9461 return false; 9462 if (!AlwaysTrue) 9463 return false; 9464 } 9465 return true; 9466 } 9467 9468 /// Returns true if we can take the address of the function. 9469 /// 9470 /// \param Complain - If true, we'll emit a diagnostic 9471 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9472 /// we in overload resolution? 9473 /// \param Loc - The location of the statement we're complaining about. Ignored 9474 /// if we're not complaining, or if we're in overload resolution. 9475 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9476 bool Complain, 9477 bool InOverloadResolution, 9478 SourceLocation Loc) { 9479 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9480 if (Complain) { 9481 if (InOverloadResolution) 9482 S.Diag(FD->getBeginLoc(), 9483 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9484 else 9485 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9486 } 9487 return false; 9488 } 9489 9490 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9491 return P->hasAttr<PassObjectSizeAttr>(); 9492 }); 9493 if (I == FD->param_end()) 9494 return true; 9495 9496 if (Complain) { 9497 // Add one to ParamNo because it's user-facing 9498 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9499 if (InOverloadResolution) 9500 S.Diag(FD->getLocation(), 9501 diag::note_ovl_candidate_has_pass_object_size_params) 9502 << ParamNo; 9503 else 9504 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9505 << FD << ParamNo; 9506 } 9507 return false; 9508 } 9509 9510 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9511 const FunctionDecl *FD) { 9512 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9513 /*InOverloadResolution=*/true, 9514 /*Loc=*/SourceLocation()); 9515 } 9516 9517 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9518 bool Complain, 9519 SourceLocation Loc) { 9520 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9521 /*InOverloadResolution=*/false, 9522 Loc); 9523 } 9524 9525 // Notes the location of an overload candidate. 9526 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9527 QualType DestType, bool TakingAddress) { 9528 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9529 return; 9530 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9531 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9532 return; 9533 9534 std::string FnDesc; 9535 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9536 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9537 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9538 << (unsigned)KSPair.first << (unsigned)KSPair.second 9539 << Fn << FnDesc; 9540 9541 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9542 Diag(Fn->getLocation(), PD); 9543 MaybeEmitInheritedConstructorNote(*this, Found); 9544 } 9545 9546 // Notes the location of all overload candidates designated through 9547 // OverloadedExpr 9548 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9549 bool TakingAddress) { 9550 assert(OverloadedExpr->getType() == Context.OverloadTy); 9551 9552 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9553 OverloadExpr *OvlExpr = Ovl.Expression; 9554 9555 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9556 IEnd = OvlExpr->decls_end(); 9557 I != IEnd; ++I) { 9558 if (FunctionTemplateDecl *FunTmpl = 9559 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9560 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9561 TakingAddress); 9562 } else if (FunctionDecl *Fun 9563 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9564 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9565 } 9566 } 9567 } 9568 9569 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9570 /// "lead" diagnostic; it will be given two arguments, the source and 9571 /// target types of the conversion. 9572 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9573 Sema &S, 9574 SourceLocation CaretLoc, 9575 const PartialDiagnostic &PDiag) const { 9576 S.Diag(CaretLoc, PDiag) 9577 << Ambiguous.getFromType() << Ambiguous.getToType(); 9578 // FIXME: The note limiting machinery is borrowed from 9579 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9580 // refactoring here. 9581 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9582 unsigned CandsShown = 0; 9583 AmbiguousConversionSequence::const_iterator I, E; 9584 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9585 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9586 break; 9587 ++CandsShown; 9588 S.NoteOverloadCandidate(I->first, I->second); 9589 } 9590 if (I != E) 9591 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9592 } 9593 9594 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9595 unsigned I, bool TakingCandidateAddress) { 9596 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9597 assert(Conv.isBad()); 9598 assert(Cand->Function && "for now, candidate must be a function"); 9599 FunctionDecl *Fn = Cand->Function; 9600 9601 // There's a conversion slot for the object argument if this is a 9602 // non-constructor method. Note that 'I' corresponds the 9603 // conversion-slot index. 9604 bool isObjectArgument = false; 9605 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9606 if (I == 0) 9607 isObjectArgument = true; 9608 else 9609 I--; 9610 } 9611 9612 std::string FnDesc; 9613 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9614 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9615 9616 Expr *FromExpr = Conv.Bad.FromExpr; 9617 QualType FromTy = Conv.Bad.getFromType(); 9618 QualType ToTy = Conv.Bad.getToType(); 9619 9620 if (FromTy == S.Context.OverloadTy) { 9621 assert(FromExpr && "overload set argument came from implicit argument?"); 9622 Expr *E = FromExpr->IgnoreParens(); 9623 if (isa<UnaryOperator>(E)) 9624 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9625 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9626 9627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9628 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9629 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9630 << Name << I + 1; 9631 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9632 return; 9633 } 9634 9635 // Do some hand-waving analysis to see if the non-viability is due 9636 // to a qualifier mismatch. 9637 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9638 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9639 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9640 CToTy = RT->getPointeeType(); 9641 else { 9642 // TODO: detect and diagnose the full richness of const mismatches. 9643 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9644 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9645 CFromTy = FromPT->getPointeeType(); 9646 CToTy = ToPT->getPointeeType(); 9647 } 9648 } 9649 9650 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9651 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9652 Qualifiers FromQs = CFromTy.getQualifiers(); 9653 Qualifiers ToQs = CToTy.getQualifiers(); 9654 9655 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9656 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9657 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9658 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9659 << ToTy << (unsigned)isObjectArgument << I + 1; 9660 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9661 return; 9662 } 9663 9664 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9666 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9667 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9668 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9669 << (unsigned)isObjectArgument << I + 1; 9670 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9671 return; 9672 } 9673 9674 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9675 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9676 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9677 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9678 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9679 << (unsigned)isObjectArgument << I + 1; 9680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9681 return; 9682 } 9683 9684 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9685 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9686 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9687 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9688 << FromQs.hasUnaligned() << I + 1; 9689 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9690 return; 9691 } 9692 9693 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9694 assert(CVR && "unexpected qualifiers mismatch"); 9695 9696 if (isObjectArgument) { 9697 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9698 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9699 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9700 << (CVR - 1); 9701 } else { 9702 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9703 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9704 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9705 << (CVR - 1) << I + 1; 9706 } 9707 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9708 return; 9709 } 9710 9711 // Special diagnostic for failure to convert an initializer list, since 9712 // telling the user that it has type void is not useful. 9713 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9715 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9716 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9717 << ToTy << (unsigned)isObjectArgument << I + 1; 9718 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9719 return; 9720 } 9721 9722 // Diagnose references or pointers to incomplete types differently, 9723 // since it's far from impossible that the incompleteness triggered 9724 // the failure. 9725 QualType TempFromTy = FromTy.getNonReferenceType(); 9726 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9727 TempFromTy = PTy->getPointeeType(); 9728 if (TempFromTy->isIncompleteType()) { 9729 // Emit the generic diagnostic and, optionally, add the hints to it. 9730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9731 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9732 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9733 << ToTy << (unsigned)isObjectArgument << I + 1 9734 << (unsigned)(Cand->Fix.Kind); 9735 9736 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9737 return; 9738 } 9739 9740 // Diagnose base -> derived pointer conversions. 9741 unsigned BaseToDerivedConversion = 0; 9742 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9743 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9744 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9745 FromPtrTy->getPointeeType()) && 9746 !FromPtrTy->getPointeeType()->isIncompleteType() && 9747 !ToPtrTy->getPointeeType()->isIncompleteType() && 9748 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9749 FromPtrTy->getPointeeType())) 9750 BaseToDerivedConversion = 1; 9751 } 9752 } else if (const ObjCObjectPointerType *FromPtrTy 9753 = FromTy->getAs<ObjCObjectPointerType>()) { 9754 if (const ObjCObjectPointerType *ToPtrTy 9755 = ToTy->getAs<ObjCObjectPointerType>()) 9756 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9757 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9758 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9759 FromPtrTy->getPointeeType()) && 9760 FromIface->isSuperClassOf(ToIface)) 9761 BaseToDerivedConversion = 2; 9762 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9763 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9764 !FromTy->isIncompleteType() && 9765 !ToRefTy->getPointeeType()->isIncompleteType() && 9766 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9767 BaseToDerivedConversion = 3; 9768 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9769 ToTy.getNonReferenceType().getCanonicalType() == 9770 FromTy.getNonReferenceType().getCanonicalType()) { 9771 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9772 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9773 << (unsigned)isObjectArgument << I + 1 9774 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9775 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9776 return; 9777 } 9778 } 9779 9780 if (BaseToDerivedConversion) { 9781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9782 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9783 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9784 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9785 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9786 return; 9787 } 9788 9789 if (isa<ObjCObjectPointerType>(CFromTy) && 9790 isa<PointerType>(CToTy)) { 9791 Qualifiers FromQs = CFromTy.getQualifiers(); 9792 Qualifiers ToQs = CToTy.getQualifiers(); 9793 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9794 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9795 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9796 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9797 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9798 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9799 return; 9800 } 9801 } 9802 9803 if (TakingCandidateAddress && 9804 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9805 return; 9806 9807 // Emit the generic diagnostic and, optionally, add the hints to it. 9808 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9809 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9811 << ToTy << (unsigned)isObjectArgument << I + 1 9812 << (unsigned)(Cand->Fix.Kind); 9813 9814 // If we can fix the conversion, suggest the FixIts. 9815 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9816 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9817 FDiag << *HI; 9818 S.Diag(Fn->getLocation(), FDiag); 9819 9820 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9821 } 9822 9823 /// Additional arity mismatch diagnosis specific to a function overload 9824 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9825 /// over a candidate in any candidate set. 9826 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9827 unsigned NumArgs) { 9828 FunctionDecl *Fn = Cand->Function; 9829 unsigned MinParams = Fn->getMinRequiredArguments(); 9830 9831 // With invalid overloaded operators, it's possible that we think we 9832 // have an arity mismatch when in fact it looks like we have the 9833 // right number of arguments, because only overloaded operators have 9834 // the weird behavior of overloading member and non-member functions. 9835 // Just don't report anything. 9836 if (Fn->isInvalidDecl() && 9837 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9838 return true; 9839 9840 if (NumArgs < MinParams) { 9841 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9842 (Cand->FailureKind == ovl_fail_bad_deduction && 9843 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9844 } else { 9845 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9846 (Cand->FailureKind == ovl_fail_bad_deduction && 9847 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9848 } 9849 9850 return false; 9851 } 9852 9853 /// General arity mismatch diagnosis over a candidate in a candidate set. 9854 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9855 unsigned NumFormalArgs) { 9856 assert(isa<FunctionDecl>(D) && 9857 "The templated declaration should at least be a function" 9858 " when diagnosing bad template argument deduction due to too many" 9859 " or too few arguments"); 9860 9861 FunctionDecl *Fn = cast<FunctionDecl>(D); 9862 9863 // TODO: treat calls to a missing default constructor as a special case 9864 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9865 unsigned MinParams = Fn->getMinRequiredArguments(); 9866 9867 // at least / at most / exactly 9868 unsigned mode, modeCount; 9869 if (NumFormalArgs < MinParams) { 9870 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9871 FnTy->isTemplateVariadic()) 9872 mode = 0; // "at least" 9873 else 9874 mode = 2; // "exactly" 9875 modeCount = MinParams; 9876 } else { 9877 if (MinParams != FnTy->getNumParams()) 9878 mode = 1; // "at most" 9879 else 9880 mode = 2; // "exactly" 9881 modeCount = FnTy->getNumParams(); 9882 } 9883 9884 std::string Description; 9885 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9886 ClassifyOverloadCandidate(S, Found, Fn, Description); 9887 9888 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9889 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9890 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9891 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9892 else 9893 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9894 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9895 << Description << mode << modeCount << NumFormalArgs; 9896 9897 MaybeEmitInheritedConstructorNote(S, Found); 9898 } 9899 9900 /// Arity mismatch diagnosis specific to a function overload candidate. 9901 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9902 unsigned NumFormalArgs) { 9903 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9904 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9905 } 9906 9907 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9908 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9909 return TD; 9910 llvm_unreachable("Unsupported: Getting the described template declaration" 9911 " for bad deduction diagnosis"); 9912 } 9913 9914 /// Diagnose a failed template-argument deduction. 9915 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9916 DeductionFailureInfo &DeductionFailure, 9917 unsigned NumArgs, 9918 bool TakingCandidateAddress) { 9919 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9920 NamedDecl *ParamD; 9921 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9922 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9923 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9924 switch (DeductionFailure.Result) { 9925 case Sema::TDK_Success: 9926 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9927 9928 case Sema::TDK_Incomplete: { 9929 assert(ParamD && "no parameter found for incomplete deduction result"); 9930 S.Diag(Templated->getLocation(), 9931 diag::note_ovl_candidate_incomplete_deduction) 9932 << ParamD->getDeclName(); 9933 MaybeEmitInheritedConstructorNote(S, Found); 9934 return; 9935 } 9936 9937 case Sema::TDK_IncompletePack: { 9938 assert(ParamD && "no parameter found for incomplete deduction result"); 9939 S.Diag(Templated->getLocation(), 9940 diag::note_ovl_candidate_incomplete_deduction_pack) 9941 << ParamD->getDeclName() 9942 << (DeductionFailure.getFirstArg()->pack_size() + 1) 9943 << *DeductionFailure.getFirstArg(); 9944 MaybeEmitInheritedConstructorNote(S, Found); 9945 return; 9946 } 9947 9948 case Sema::TDK_Underqualified: { 9949 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9950 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9951 9952 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9953 9954 // Param will have been canonicalized, but it should just be a 9955 // qualified version of ParamD, so move the qualifiers to that. 9956 QualifierCollector Qs; 9957 Qs.strip(Param); 9958 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9959 assert(S.Context.hasSameType(Param, NonCanonParam)); 9960 9961 // Arg has also been canonicalized, but there's nothing we can do 9962 // about that. It also doesn't matter as much, because it won't 9963 // have any template parameters in it (because deduction isn't 9964 // done on dependent types). 9965 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9966 9967 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9968 << ParamD->getDeclName() << Arg << NonCanonParam; 9969 MaybeEmitInheritedConstructorNote(S, Found); 9970 return; 9971 } 9972 9973 case Sema::TDK_Inconsistent: { 9974 assert(ParamD && "no parameter found for inconsistent deduction result"); 9975 int which = 0; 9976 if (isa<TemplateTypeParmDecl>(ParamD)) 9977 which = 0; 9978 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9979 // Deduction might have failed because we deduced arguments of two 9980 // different types for a non-type template parameter. 9981 // FIXME: Use a different TDK value for this. 9982 QualType T1 = 9983 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9984 QualType T2 = 9985 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9986 if (!S.Context.hasSameType(T1, T2)) { 9987 S.Diag(Templated->getLocation(), 9988 diag::note_ovl_candidate_inconsistent_deduction_types) 9989 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9990 << *DeductionFailure.getSecondArg() << T2; 9991 MaybeEmitInheritedConstructorNote(S, Found); 9992 return; 9993 } 9994 9995 which = 1; 9996 } else { 9997 which = 2; 9998 } 9999 10000 S.Diag(Templated->getLocation(), 10001 diag::note_ovl_candidate_inconsistent_deduction) 10002 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10003 << *DeductionFailure.getSecondArg(); 10004 MaybeEmitInheritedConstructorNote(S, Found); 10005 return; 10006 } 10007 10008 case Sema::TDK_InvalidExplicitArguments: 10009 assert(ParamD && "no parameter found for invalid explicit arguments"); 10010 if (ParamD->getDeclName()) 10011 S.Diag(Templated->getLocation(), 10012 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10013 << ParamD->getDeclName(); 10014 else { 10015 int index = 0; 10016 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10017 index = TTP->getIndex(); 10018 else if (NonTypeTemplateParmDecl *NTTP 10019 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10020 index = NTTP->getIndex(); 10021 else 10022 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10023 S.Diag(Templated->getLocation(), 10024 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10025 << (index + 1); 10026 } 10027 MaybeEmitInheritedConstructorNote(S, Found); 10028 return; 10029 10030 case Sema::TDK_TooManyArguments: 10031 case Sema::TDK_TooFewArguments: 10032 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10033 return; 10034 10035 case Sema::TDK_InstantiationDepth: 10036 S.Diag(Templated->getLocation(), 10037 diag::note_ovl_candidate_instantiation_depth); 10038 MaybeEmitInheritedConstructorNote(S, Found); 10039 return; 10040 10041 case Sema::TDK_SubstitutionFailure: { 10042 // Format the template argument list into the argument string. 10043 SmallString<128> TemplateArgString; 10044 if (TemplateArgumentList *Args = 10045 DeductionFailure.getTemplateArgumentList()) { 10046 TemplateArgString = " "; 10047 TemplateArgString += S.getTemplateArgumentBindingsText( 10048 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10049 } 10050 10051 // If this candidate was disabled by enable_if, say so. 10052 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10053 if (PDiag && PDiag->second.getDiagID() == 10054 diag::err_typename_nested_not_found_enable_if) { 10055 // FIXME: Use the source range of the condition, and the fully-qualified 10056 // name of the enable_if template. These are both present in PDiag. 10057 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10058 << "'enable_if'" << TemplateArgString; 10059 return; 10060 } 10061 10062 // We found a specific requirement that disabled the enable_if. 10063 if (PDiag && PDiag->second.getDiagID() == 10064 diag::err_typename_nested_not_found_requirement) { 10065 S.Diag(Templated->getLocation(), 10066 diag::note_ovl_candidate_disabled_by_requirement) 10067 << PDiag->second.getStringArg(0) << TemplateArgString; 10068 return; 10069 } 10070 10071 // Format the SFINAE diagnostic into the argument string. 10072 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10073 // formatted message in another diagnostic. 10074 SmallString<128> SFINAEArgString; 10075 SourceRange R; 10076 if (PDiag) { 10077 SFINAEArgString = ": "; 10078 R = SourceRange(PDiag->first, PDiag->first); 10079 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10080 } 10081 10082 S.Diag(Templated->getLocation(), 10083 diag::note_ovl_candidate_substitution_failure) 10084 << TemplateArgString << SFINAEArgString << R; 10085 MaybeEmitInheritedConstructorNote(S, Found); 10086 return; 10087 } 10088 10089 case Sema::TDK_DeducedMismatch: 10090 case Sema::TDK_DeducedMismatchNested: { 10091 // Format the template argument list into the argument string. 10092 SmallString<128> TemplateArgString; 10093 if (TemplateArgumentList *Args = 10094 DeductionFailure.getTemplateArgumentList()) { 10095 TemplateArgString = " "; 10096 TemplateArgString += S.getTemplateArgumentBindingsText( 10097 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10098 } 10099 10100 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10101 << (*DeductionFailure.getCallArgIndex() + 1) 10102 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10103 << TemplateArgString 10104 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10105 break; 10106 } 10107 10108 case Sema::TDK_NonDeducedMismatch: { 10109 // FIXME: Provide a source location to indicate what we couldn't match. 10110 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10111 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10112 if (FirstTA.getKind() == TemplateArgument::Template && 10113 SecondTA.getKind() == TemplateArgument::Template) { 10114 TemplateName FirstTN = FirstTA.getAsTemplate(); 10115 TemplateName SecondTN = SecondTA.getAsTemplate(); 10116 if (FirstTN.getKind() == TemplateName::Template && 10117 SecondTN.getKind() == TemplateName::Template) { 10118 if (FirstTN.getAsTemplateDecl()->getName() == 10119 SecondTN.getAsTemplateDecl()->getName()) { 10120 // FIXME: This fixes a bad diagnostic where both templates are named 10121 // the same. This particular case is a bit difficult since: 10122 // 1) It is passed as a string to the diagnostic printer. 10123 // 2) The diagnostic printer only attempts to find a better 10124 // name for types, not decls. 10125 // Ideally, this should folded into the diagnostic printer. 10126 S.Diag(Templated->getLocation(), 10127 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10128 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10129 return; 10130 } 10131 } 10132 } 10133 10134 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10135 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10136 return; 10137 10138 // FIXME: For generic lambda parameters, check if the function is a lambda 10139 // call operator, and if so, emit a prettier and more informative 10140 // diagnostic that mentions 'auto' and lambda in addition to 10141 // (or instead of?) the canonical template type parameters. 10142 S.Diag(Templated->getLocation(), 10143 diag::note_ovl_candidate_non_deduced_mismatch) 10144 << FirstTA << SecondTA; 10145 return; 10146 } 10147 // TODO: diagnose these individually, then kill off 10148 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10149 case Sema::TDK_MiscellaneousDeductionFailure: 10150 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10151 MaybeEmitInheritedConstructorNote(S, Found); 10152 return; 10153 case Sema::TDK_CUDATargetMismatch: 10154 S.Diag(Templated->getLocation(), 10155 diag::note_cuda_ovl_candidate_target_mismatch); 10156 return; 10157 } 10158 } 10159 10160 /// Diagnose a failed template-argument deduction, for function calls. 10161 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10162 unsigned NumArgs, 10163 bool TakingCandidateAddress) { 10164 unsigned TDK = Cand->DeductionFailure.Result; 10165 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10166 if (CheckArityMismatch(S, Cand, NumArgs)) 10167 return; 10168 } 10169 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10170 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10171 } 10172 10173 /// CUDA: diagnose an invalid call across targets. 10174 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10175 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10176 FunctionDecl *Callee = Cand->Function; 10177 10178 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10179 CalleeTarget = S.IdentifyCUDATarget(Callee); 10180 10181 std::string FnDesc; 10182 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10183 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10184 10185 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10186 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10187 << FnDesc /* Ignored */ 10188 << CalleeTarget << CallerTarget; 10189 10190 // This could be an implicit constructor for which we could not infer the 10191 // target due to a collsion. Diagnose that case. 10192 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10193 if (Meth != nullptr && Meth->isImplicit()) { 10194 CXXRecordDecl *ParentClass = Meth->getParent(); 10195 Sema::CXXSpecialMember CSM; 10196 10197 switch (FnKindPair.first) { 10198 default: 10199 return; 10200 case oc_implicit_default_constructor: 10201 CSM = Sema::CXXDefaultConstructor; 10202 break; 10203 case oc_implicit_copy_constructor: 10204 CSM = Sema::CXXCopyConstructor; 10205 break; 10206 case oc_implicit_move_constructor: 10207 CSM = Sema::CXXMoveConstructor; 10208 break; 10209 case oc_implicit_copy_assignment: 10210 CSM = Sema::CXXCopyAssignment; 10211 break; 10212 case oc_implicit_move_assignment: 10213 CSM = Sema::CXXMoveAssignment; 10214 break; 10215 }; 10216 10217 bool ConstRHS = false; 10218 if (Meth->getNumParams()) { 10219 if (const ReferenceType *RT = 10220 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10221 ConstRHS = RT->getPointeeType().isConstQualified(); 10222 } 10223 } 10224 10225 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10226 /* ConstRHS */ ConstRHS, 10227 /* Diagnose */ true); 10228 } 10229 } 10230 10231 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10232 FunctionDecl *Callee = Cand->Function; 10233 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10234 10235 S.Diag(Callee->getLocation(), 10236 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10237 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10238 } 10239 10240 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10241 FunctionDecl *Callee = Cand->Function; 10242 10243 S.Diag(Callee->getLocation(), 10244 diag::note_ovl_candidate_disabled_by_extension); 10245 } 10246 10247 /// Generates a 'note' diagnostic for an overload candidate. We've 10248 /// already generated a primary error at the call site. 10249 /// 10250 /// It really does need to be a single diagnostic with its caret 10251 /// pointed at the candidate declaration. Yes, this creates some 10252 /// major challenges of technical writing. Yes, this makes pointing 10253 /// out problems with specific arguments quite awkward. It's still 10254 /// better than generating twenty screens of text for every failed 10255 /// overload. 10256 /// 10257 /// It would be great to be able to express per-candidate problems 10258 /// more richly for those diagnostic clients that cared, but we'd 10259 /// still have to be just as careful with the default diagnostics. 10260 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10261 unsigned NumArgs, 10262 bool TakingCandidateAddress) { 10263 FunctionDecl *Fn = Cand->Function; 10264 10265 // Note deleted candidates, but only if they're viable. 10266 if (Cand->Viable) { 10267 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10268 std::string FnDesc; 10269 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10270 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10271 10272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10274 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10275 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10276 return; 10277 } 10278 10279 // We don't really have anything else to say about viable candidates. 10280 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10281 return; 10282 } 10283 10284 switch (Cand->FailureKind) { 10285 case ovl_fail_too_many_arguments: 10286 case ovl_fail_too_few_arguments: 10287 return DiagnoseArityMismatch(S, Cand, NumArgs); 10288 10289 case ovl_fail_bad_deduction: 10290 return DiagnoseBadDeduction(S, Cand, NumArgs, 10291 TakingCandidateAddress); 10292 10293 case ovl_fail_illegal_constructor: { 10294 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10295 << (Fn->getPrimaryTemplate() ? 1 : 0); 10296 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10297 return; 10298 } 10299 10300 case ovl_fail_trivial_conversion: 10301 case ovl_fail_bad_final_conversion: 10302 case ovl_fail_final_conversion_not_exact: 10303 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10304 10305 case ovl_fail_bad_conversion: { 10306 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10307 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10308 if (Cand->Conversions[I].isBad()) 10309 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10310 10311 // FIXME: this currently happens when we're called from SemaInit 10312 // when user-conversion overload fails. Figure out how to handle 10313 // those conditions and diagnose them well. 10314 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10315 } 10316 10317 case ovl_fail_bad_target: 10318 return DiagnoseBadTarget(S, Cand); 10319 10320 case ovl_fail_enable_if: 10321 return DiagnoseFailedEnableIfAttr(S, Cand); 10322 10323 case ovl_fail_ext_disabled: 10324 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10325 10326 case ovl_fail_inhctor_slice: 10327 // It's generally not interesting to note copy/move constructors here. 10328 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10329 return; 10330 S.Diag(Fn->getLocation(), 10331 diag::note_ovl_candidate_inherited_constructor_slice) 10332 << (Fn->getPrimaryTemplate() ? 1 : 0) 10333 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10334 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10335 return; 10336 10337 case ovl_fail_addr_not_available: { 10338 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10339 (void)Available; 10340 assert(!Available); 10341 break; 10342 } 10343 case ovl_non_default_multiversion_function: 10344 // Do nothing, these should simply be ignored. 10345 break; 10346 } 10347 } 10348 10349 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10350 // Desugar the type of the surrogate down to a function type, 10351 // retaining as many typedefs as possible while still showing 10352 // the function type (and, therefore, its parameter types). 10353 QualType FnType = Cand->Surrogate->getConversionType(); 10354 bool isLValueReference = false; 10355 bool isRValueReference = false; 10356 bool isPointer = false; 10357 if (const LValueReferenceType *FnTypeRef = 10358 FnType->getAs<LValueReferenceType>()) { 10359 FnType = FnTypeRef->getPointeeType(); 10360 isLValueReference = true; 10361 } else if (const RValueReferenceType *FnTypeRef = 10362 FnType->getAs<RValueReferenceType>()) { 10363 FnType = FnTypeRef->getPointeeType(); 10364 isRValueReference = true; 10365 } 10366 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10367 FnType = FnTypePtr->getPointeeType(); 10368 isPointer = true; 10369 } 10370 // Desugar down to a function type. 10371 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10372 // Reconstruct the pointer/reference as appropriate. 10373 if (isPointer) FnType = S.Context.getPointerType(FnType); 10374 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10375 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10376 10377 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10378 << FnType; 10379 } 10380 10381 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10382 SourceLocation OpLoc, 10383 OverloadCandidate *Cand) { 10384 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10385 std::string TypeStr("operator"); 10386 TypeStr += Opc; 10387 TypeStr += "("; 10388 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10389 if (Cand->Conversions.size() == 1) { 10390 TypeStr += ")"; 10391 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10392 } else { 10393 TypeStr += ", "; 10394 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10395 TypeStr += ")"; 10396 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10397 } 10398 } 10399 10400 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10401 OverloadCandidate *Cand) { 10402 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10403 if (ICS.isBad()) break; // all meaningless after first invalid 10404 if (!ICS.isAmbiguous()) continue; 10405 10406 ICS.DiagnoseAmbiguousConversion( 10407 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10408 } 10409 } 10410 10411 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10412 if (Cand->Function) 10413 return Cand->Function->getLocation(); 10414 if (Cand->IsSurrogate) 10415 return Cand->Surrogate->getLocation(); 10416 return SourceLocation(); 10417 } 10418 10419 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10420 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10421 case Sema::TDK_Success: 10422 case Sema::TDK_NonDependentConversionFailure: 10423 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10424 10425 case Sema::TDK_Invalid: 10426 case Sema::TDK_Incomplete: 10427 case Sema::TDK_IncompletePack: 10428 return 1; 10429 10430 case Sema::TDK_Underqualified: 10431 case Sema::TDK_Inconsistent: 10432 return 2; 10433 10434 case Sema::TDK_SubstitutionFailure: 10435 case Sema::TDK_DeducedMismatch: 10436 case Sema::TDK_DeducedMismatchNested: 10437 case Sema::TDK_NonDeducedMismatch: 10438 case Sema::TDK_MiscellaneousDeductionFailure: 10439 case Sema::TDK_CUDATargetMismatch: 10440 return 3; 10441 10442 case Sema::TDK_InstantiationDepth: 10443 return 4; 10444 10445 case Sema::TDK_InvalidExplicitArguments: 10446 return 5; 10447 10448 case Sema::TDK_TooManyArguments: 10449 case Sema::TDK_TooFewArguments: 10450 return 6; 10451 } 10452 llvm_unreachable("Unhandled deduction result"); 10453 } 10454 10455 namespace { 10456 struct CompareOverloadCandidatesForDisplay { 10457 Sema &S; 10458 SourceLocation Loc; 10459 size_t NumArgs; 10460 OverloadCandidateSet::CandidateSetKind CSK; 10461 10462 CompareOverloadCandidatesForDisplay( 10463 Sema &S, SourceLocation Loc, size_t NArgs, 10464 OverloadCandidateSet::CandidateSetKind CSK) 10465 : S(S), NumArgs(NArgs), CSK(CSK) {} 10466 10467 bool operator()(const OverloadCandidate *L, 10468 const OverloadCandidate *R) { 10469 // Fast-path this check. 10470 if (L == R) return false; 10471 10472 // Order first by viability. 10473 if (L->Viable) { 10474 if (!R->Viable) return true; 10475 10476 // TODO: introduce a tri-valued comparison for overload 10477 // candidates. Would be more worthwhile if we had a sort 10478 // that could exploit it. 10479 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10480 return true; 10481 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10482 return false; 10483 } else if (R->Viable) 10484 return false; 10485 10486 assert(L->Viable == R->Viable); 10487 10488 // Criteria by which we can sort non-viable candidates: 10489 if (!L->Viable) { 10490 // 1. Arity mismatches come after other candidates. 10491 if (L->FailureKind == ovl_fail_too_many_arguments || 10492 L->FailureKind == ovl_fail_too_few_arguments) { 10493 if (R->FailureKind == ovl_fail_too_many_arguments || 10494 R->FailureKind == ovl_fail_too_few_arguments) { 10495 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10496 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10497 if (LDist == RDist) { 10498 if (L->FailureKind == R->FailureKind) 10499 // Sort non-surrogates before surrogates. 10500 return !L->IsSurrogate && R->IsSurrogate; 10501 // Sort candidates requiring fewer parameters than there were 10502 // arguments given after candidates requiring more parameters 10503 // than there were arguments given. 10504 return L->FailureKind == ovl_fail_too_many_arguments; 10505 } 10506 return LDist < RDist; 10507 } 10508 return false; 10509 } 10510 if (R->FailureKind == ovl_fail_too_many_arguments || 10511 R->FailureKind == ovl_fail_too_few_arguments) 10512 return true; 10513 10514 // 2. Bad conversions come first and are ordered by the number 10515 // of bad conversions and quality of good conversions. 10516 if (L->FailureKind == ovl_fail_bad_conversion) { 10517 if (R->FailureKind != ovl_fail_bad_conversion) 10518 return true; 10519 10520 // The conversion that can be fixed with a smaller number of changes, 10521 // comes first. 10522 unsigned numLFixes = L->Fix.NumConversionsFixed; 10523 unsigned numRFixes = R->Fix.NumConversionsFixed; 10524 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10525 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10526 if (numLFixes != numRFixes) { 10527 return numLFixes < numRFixes; 10528 } 10529 10530 // If there's any ordering between the defined conversions... 10531 // FIXME: this might not be transitive. 10532 assert(L->Conversions.size() == R->Conversions.size()); 10533 10534 int leftBetter = 0; 10535 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10536 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10537 switch (CompareImplicitConversionSequences(S, Loc, 10538 L->Conversions[I], 10539 R->Conversions[I])) { 10540 case ImplicitConversionSequence::Better: 10541 leftBetter++; 10542 break; 10543 10544 case ImplicitConversionSequence::Worse: 10545 leftBetter--; 10546 break; 10547 10548 case ImplicitConversionSequence::Indistinguishable: 10549 break; 10550 } 10551 } 10552 if (leftBetter > 0) return true; 10553 if (leftBetter < 0) return false; 10554 10555 } else if (R->FailureKind == ovl_fail_bad_conversion) 10556 return false; 10557 10558 if (L->FailureKind == ovl_fail_bad_deduction) { 10559 if (R->FailureKind != ovl_fail_bad_deduction) 10560 return true; 10561 10562 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10563 return RankDeductionFailure(L->DeductionFailure) 10564 < RankDeductionFailure(R->DeductionFailure); 10565 } else if (R->FailureKind == ovl_fail_bad_deduction) 10566 return false; 10567 10568 // TODO: others? 10569 } 10570 10571 // Sort everything else by location. 10572 SourceLocation LLoc = GetLocationForCandidate(L); 10573 SourceLocation RLoc = GetLocationForCandidate(R); 10574 10575 // Put candidates without locations (e.g. builtins) at the end. 10576 if (LLoc.isInvalid()) return false; 10577 if (RLoc.isInvalid()) return true; 10578 10579 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10580 } 10581 }; 10582 } 10583 10584 /// CompleteNonViableCandidate - Normally, overload resolution only 10585 /// computes up to the first bad conversion. Produces the FixIt set if 10586 /// possible. 10587 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10588 ArrayRef<Expr *> Args) { 10589 assert(!Cand->Viable); 10590 10591 // Don't do anything on failures other than bad conversion. 10592 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10593 10594 // We only want the FixIts if all the arguments can be corrected. 10595 bool Unfixable = false; 10596 // Use a implicit copy initialization to check conversion fixes. 10597 Cand->Fix.setConversionChecker(TryCopyInitialization); 10598 10599 // Attempt to fix the bad conversion. 10600 unsigned ConvCount = Cand->Conversions.size(); 10601 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10602 ++ConvIdx) { 10603 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10604 if (Cand->Conversions[ConvIdx].isInitialized() && 10605 Cand->Conversions[ConvIdx].isBad()) { 10606 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10607 break; 10608 } 10609 } 10610 10611 // FIXME: this should probably be preserved from the overload 10612 // operation somehow. 10613 bool SuppressUserConversions = false; 10614 10615 unsigned ConvIdx = 0; 10616 ArrayRef<QualType> ParamTypes; 10617 10618 if (Cand->IsSurrogate) { 10619 QualType ConvType 10620 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10621 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10622 ConvType = ConvPtrType->getPointeeType(); 10623 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10624 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10625 ConvIdx = 1; 10626 } else if (Cand->Function) { 10627 ParamTypes = 10628 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10629 if (isa<CXXMethodDecl>(Cand->Function) && 10630 !isa<CXXConstructorDecl>(Cand->Function)) { 10631 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10632 ConvIdx = 1; 10633 } 10634 } else { 10635 // Builtin operator. 10636 assert(ConvCount <= 3); 10637 ParamTypes = Cand->BuiltinParamTypes; 10638 } 10639 10640 // Fill in the rest of the conversions. 10641 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10642 if (Cand->Conversions[ConvIdx].isInitialized()) { 10643 // We've already checked this conversion. 10644 } else if (ArgIdx < ParamTypes.size()) { 10645 if (ParamTypes[ArgIdx]->isDependentType()) 10646 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10647 Args[ArgIdx]->getType()); 10648 else { 10649 Cand->Conversions[ConvIdx] = 10650 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10651 SuppressUserConversions, 10652 /*InOverloadResolution=*/true, 10653 /*AllowObjCWritebackConversion=*/ 10654 S.getLangOpts().ObjCAutoRefCount); 10655 // Store the FixIt in the candidate if it exists. 10656 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10657 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10658 } 10659 } else 10660 Cand->Conversions[ConvIdx].setEllipsis(); 10661 } 10662 } 10663 10664 /// When overload resolution fails, prints diagnostic messages containing the 10665 /// candidates in the candidate set. 10666 void OverloadCandidateSet::NoteCandidates( 10667 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10668 StringRef Opc, SourceLocation OpLoc, 10669 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10670 // Sort the candidates by viability and position. Sorting directly would 10671 // be prohibitive, so we make a set of pointers and sort those. 10672 SmallVector<OverloadCandidate*, 32> Cands; 10673 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10674 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10675 if (!Filter(*Cand)) 10676 continue; 10677 if (Cand->Viable) 10678 Cands.push_back(Cand); 10679 else if (OCD == OCD_AllCandidates) { 10680 CompleteNonViableCandidate(S, Cand, Args); 10681 if (Cand->Function || Cand->IsSurrogate) 10682 Cands.push_back(Cand); 10683 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10684 // want to list every possible builtin candidate. 10685 } 10686 } 10687 10688 std::stable_sort(Cands.begin(), Cands.end(), 10689 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10690 10691 bool ReportedAmbiguousConversions = false; 10692 10693 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10694 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10695 unsigned CandsShown = 0; 10696 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10697 OverloadCandidate *Cand = *I; 10698 10699 // Set an arbitrary limit on the number of candidate functions we'll spam 10700 // the user with. FIXME: This limit should depend on details of the 10701 // candidate list. 10702 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10703 break; 10704 } 10705 ++CandsShown; 10706 10707 if (Cand->Function) 10708 NoteFunctionCandidate(S, Cand, Args.size(), 10709 /*TakingCandidateAddress=*/false); 10710 else if (Cand->IsSurrogate) 10711 NoteSurrogateCandidate(S, Cand); 10712 else { 10713 assert(Cand->Viable && 10714 "Non-viable built-in candidates are not added to Cands."); 10715 // Generally we only see ambiguities including viable builtin 10716 // operators if overload resolution got screwed up by an 10717 // ambiguous user-defined conversion. 10718 // 10719 // FIXME: It's quite possible for different conversions to see 10720 // different ambiguities, though. 10721 if (!ReportedAmbiguousConversions) { 10722 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10723 ReportedAmbiguousConversions = true; 10724 } 10725 10726 // If this is a viable builtin, print it. 10727 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10728 } 10729 } 10730 10731 if (I != E) 10732 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10733 } 10734 10735 static SourceLocation 10736 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10737 return Cand->Specialization ? Cand->Specialization->getLocation() 10738 : SourceLocation(); 10739 } 10740 10741 namespace { 10742 struct CompareTemplateSpecCandidatesForDisplay { 10743 Sema &S; 10744 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10745 10746 bool operator()(const TemplateSpecCandidate *L, 10747 const TemplateSpecCandidate *R) { 10748 // Fast-path this check. 10749 if (L == R) 10750 return false; 10751 10752 // Assuming that both candidates are not matches... 10753 10754 // Sort by the ranking of deduction failures. 10755 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10756 return RankDeductionFailure(L->DeductionFailure) < 10757 RankDeductionFailure(R->DeductionFailure); 10758 10759 // Sort everything else by location. 10760 SourceLocation LLoc = GetLocationForCandidate(L); 10761 SourceLocation RLoc = GetLocationForCandidate(R); 10762 10763 // Put candidates without locations (e.g. builtins) at the end. 10764 if (LLoc.isInvalid()) 10765 return false; 10766 if (RLoc.isInvalid()) 10767 return true; 10768 10769 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10770 } 10771 }; 10772 } 10773 10774 /// Diagnose a template argument deduction failure. 10775 /// We are treating these failures as overload failures due to bad 10776 /// deductions. 10777 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10778 bool ForTakingAddress) { 10779 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10780 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10781 } 10782 10783 void TemplateSpecCandidateSet::destroyCandidates() { 10784 for (iterator i = begin(), e = end(); i != e; ++i) { 10785 i->DeductionFailure.Destroy(); 10786 } 10787 } 10788 10789 void TemplateSpecCandidateSet::clear() { 10790 destroyCandidates(); 10791 Candidates.clear(); 10792 } 10793 10794 /// NoteCandidates - When no template specialization match is found, prints 10795 /// diagnostic messages containing the non-matching specializations that form 10796 /// the candidate set. 10797 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10798 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10799 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10800 // Sort the candidates by position (assuming no candidate is a match). 10801 // Sorting directly would be prohibitive, so we make a set of pointers 10802 // and sort those. 10803 SmallVector<TemplateSpecCandidate *, 32> Cands; 10804 Cands.reserve(size()); 10805 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10806 if (Cand->Specialization) 10807 Cands.push_back(Cand); 10808 // Otherwise, this is a non-matching builtin candidate. We do not, 10809 // in general, want to list every possible builtin candidate. 10810 } 10811 10812 llvm::sort(Cands.begin(), Cands.end(), 10813 CompareTemplateSpecCandidatesForDisplay(S)); 10814 10815 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10816 // for generalization purposes (?). 10817 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10818 10819 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10820 unsigned CandsShown = 0; 10821 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10822 TemplateSpecCandidate *Cand = *I; 10823 10824 // Set an arbitrary limit on the number of candidates we'll spam 10825 // the user with. FIXME: This limit should depend on details of the 10826 // candidate list. 10827 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10828 break; 10829 ++CandsShown; 10830 10831 assert(Cand->Specialization && 10832 "Non-matching built-in candidates are not added to Cands."); 10833 Cand->NoteDeductionFailure(S, ForTakingAddress); 10834 } 10835 10836 if (I != E) 10837 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10838 } 10839 10840 // [PossiblyAFunctionType] --> [Return] 10841 // NonFunctionType --> NonFunctionType 10842 // R (A) --> R(A) 10843 // R (*)(A) --> R (A) 10844 // R (&)(A) --> R (A) 10845 // R (S::*)(A) --> R (A) 10846 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10847 QualType Ret = PossiblyAFunctionType; 10848 if (const PointerType *ToTypePtr = 10849 PossiblyAFunctionType->getAs<PointerType>()) 10850 Ret = ToTypePtr->getPointeeType(); 10851 else if (const ReferenceType *ToTypeRef = 10852 PossiblyAFunctionType->getAs<ReferenceType>()) 10853 Ret = ToTypeRef->getPointeeType(); 10854 else if (const MemberPointerType *MemTypePtr = 10855 PossiblyAFunctionType->getAs<MemberPointerType>()) 10856 Ret = MemTypePtr->getPointeeType(); 10857 Ret = 10858 Context.getCanonicalType(Ret).getUnqualifiedType(); 10859 return Ret; 10860 } 10861 10862 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10863 bool Complain = true) { 10864 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10865 S.DeduceReturnType(FD, Loc, Complain)) 10866 return true; 10867 10868 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10869 if (S.getLangOpts().CPlusPlus17 && 10870 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10871 !S.ResolveExceptionSpec(Loc, FPT)) 10872 return true; 10873 10874 return false; 10875 } 10876 10877 namespace { 10878 // A helper class to help with address of function resolution 10879 // - allows us to avoid passing around all those ugly parameters 10880 class AddressOfFunctionResolver { 10881 Sema& S; 10882 Expr* SourceExpr; 10883 const QualType& TargetType; 10884 QualType TargetFunctionType; // Extracted function type from target type 10885 10886 bool Complain; 10887 //DeclAccessPair& ResultFunctionAccessPair; 10888 ASTContext& Context; 10889 10890 bool TargetTypeIsNonStaticMemberFunction; 10891 bool FoundNonTemplateFunction; 10892 bool StaticMemberFunctionFromBoundPointer; 10893 bool HasComplained; 10894 10895 OverloadExpr::FindResult OvlExprInfo; 10896 OverloadExpr *OvlExpr; 10897 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10898 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10899 TemplateSpecCandidateSet FailedCandidates; 10900 10901 public: 10902 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10903 const QualType &TargetType, bool Complain) 10904 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10905 Complain(Complain), Context(S.getASTContext()), 10906 TargetTypeIsNonStaticMemberFunction( 10907 !!TargetType->getAs<MemberPointerType>()), 10908 FoundNonTemplateFunction(false), 10909 StaticMemberFunctionFromBoundPointer(false), 10910 HasComplained(false), 10911 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10912 OvlExpr(OvlExprInfo.Expression), 10913 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10914 ExtractUnqualifiedFunctionTypeFromTargetType(); 10915 10916 if (TargetFunctionType->isFunctionType()) { 10917 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10918 if (!UME->isImplicitAccess() && 10919 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10920 StaticMemberFunctionFromBoundPointer = true; 10921 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10922 DeclAccessPair dap; 10923 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10924 OvlExpr, false, &dap)) { 10925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10926 if (!Method->isStatic()) { 10927 // If the target type is a non-function type and the function found 10928 // is a non-static member function, pretend as if that was the 10929 // target, it's the only possible type to end up with. 10930 TargetTypeIsNonStaticMemberFunction = true; 10931 10932 // And skip adding the function if its not in the proper form. 10933 // We'll diagnose this due to an empty set of functions. 10934 if (!OvlExprInfo.HasFormOfMemberPointer) 10935 return; 10936 } 10937 10938 Matches.push_back(std::make_pair(dap, Fn)); 10939 } 10940 return; 10941 } 10942 10943 if (OvlExpr->hasExplicitTemplateArgs()) 10944 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10945 10946 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10947 // C++ [over.over]p4: 10948 // If more than one function is selected, [...] 10949 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10950 if (FoundNonTemplateFunction) 10951 EliminateAllTemplateMatches(); 10952 else 10953 EliminateAllExceptMostSpecializedTemplate(); 10954 } 10955 } 10956 10957 if (S.getLangOpts().CUDA && Matches.size() > 1) 10958 EliminateSuboptimalCudaMatches(); 10959 } 10960 10961 bool hasComplained() const { return HasComplained; } 10962 10963 private: 10964 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10965 QualType Discard; 10966 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10967 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10968 } 10969 10970 /// \return true if A is considered a better overload candidate for the 10971 /// desired type than B. 10972 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10973 // If A doesn't have exactly the correct type, we don't want to classify it 10974 // as "better" than anything else. This way, the user is required to 10975 // disambiguate for us if there are multiple candidates and no exact match. 10976 return candidateHasExactlyCorrectType(A) && 10977 (!candidateHasExactlyCorrectType(B) || 10978 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10979 } 10980 10981 /// \return true if we were able to eliminate all but one overload candidate, 10982 /// false otherwise. 10983 bool eliminiateSuboptimalOverloadCandidates() { 10984 // Same algorithm as overload resolution -- one pass to pick the "best", 10985 // another pass to be sure that nothing is better than the best. 10986 auto Best = Matches.begin(); 10987 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10988 if (isBetterCandidate(I->second, Best->second)) 10989 Best = I; 10990 10991 const FunctionDecl *BestFn = Best->second; 10992 auto IsBestOrInferiorToBest = [this, BestFn]( 10993 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10994 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10995 }; 10996 10997 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10998 // option, so we can potentially give the user a better error 10999 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 11000 return false; 11001 Matches[0] = *Best; 11002 Matches.resize(1); 11003 return true; 11004 } 11005 11006 bool isTargetTypeAFunction() const { 11007 return TargetFunctionType->isFunctionType(); 11008 } 11009 11010 // [ToType] [Return] 11011 11012 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11013 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11014 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11015 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11016 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11017 } 11018 11019 // return true if any matching specializations were found 11020 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11021 const DeclAccessPair& CurAccessFunPair) { 11022 if (CXXMethodDecl *Method 11023 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11024 // Skip non-static function templates when converting to pointer, and 11025 // static when converting to member pointer. 11026 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11027 return false; 11028 } 11029 else if (TargetTypeIsNonStaticMemberFunction) 11030 return false; 11031 11032 // C++ [over.over]p2: 11033 // If the name is a function template, template argument deduction is 11034 // done (14.8.2.2), and if the argument deduction succeeds, the 11035 // resulting template argument list is used to generate a single 11036 // function template specialization, which is added to the set of 11037 // overloaded functions considered. 11038 FunctionDecl *Specialization = nullptr; 11039 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11040 if (Sema::TemplateDeductionResult Result 11041 = S.DeduceTemplateArguments(FunctionTemplate, 11042 &OvlExplicitTemplateArgs, 11043 TargetFunctionType, Specialization, 11044 Info, /*IsAddressOfFunction*/true)) { 11045 // Make a note of the failed deduction for diagnostics. 11046 FailedCandidates.addCandidate() 11047 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11048 MakeDeductionFailureInfo(Context, Result, Info)); 11049 return false; 11050 } 11051 11052 // Template argument deduction ensures that we have an exact match or 11053 // compatible pointer-to-function arguments that would be adjusted by ICS. 11054 // This function template specicalization works. 11055 assert(S.isSameOrCompatibleFunctionType( 11056 Context.getCanonicalType(Specialization->getType()), 11057 Context.getCanonicalType(TargetFunctionType))); 11058 11059 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11060 return false; 11061 11062 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11063 return true; 11064 } 11065 11066 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11067 const DeclAccessPair& CurAccessFunPair) { 11068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11069 // Skip non-static functions when converting to pointer, and static 11070 // when converting to member pointer. 11071 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11072 return false; 11073 } 11074 else if (TargetTypeIsNonStaticMemberFunction) 11075 return false; 11076 11077 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11078 if (S.getLangOpts().CUDA) 11079 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11080 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11081 return false; 11082 if (FunDecl->isMultiVersion()) { 11083 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11084 if (TA && !TA->isDefaultVersion()) 11085 return false; 11086 } 11087 11088 // If any candidate has a placeholder return type, trigger its deduction 11089 // now. 11090 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11091 Complain)) { 11092 HasComplained |= Complain; 11093 return false; 11094 } 11095 11096 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11097 return false; 11098 11099 // If we're in C, we need to support types that aren't exactly identical. 11100 if (!S.getLangOpts().CPlusPlus || 11101 candidateHasExactlyCorrectType(FunDecl)) { 11102 Matches.push_back(std::make_pair( 11103 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11104 FoundNonTemplateFunction = true; 11105 return true; 11106 } 11107 } 11108 11109 return false; 11110 } 11111 11112 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11113 bool Ret = false; 11114 11115 // If the overload expression doesn't have the form of a pointer to 11116 // member, don't try to convert it to a pointer-to-member type. 11117 if (IsInvalidFormOfPointerToMemberFunction()) 11118 return false; 11119 11120 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11121 E = OvlExpr->decls_end(); 11122 I != E; ++I) { 11123 // Look through any using declarations to find the underlying function. 11124 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11125 11126 // C++ [over.over]p3: 11127 // Non-member functions and static member functions match 11128 // targets of type "pointer-to-function" or "reference-to-function." 11129 // Nonstatic member functions match targets of 11130 // type "pointer-to-member-function." 11131 // Note that according to DR 247, the containing class does not matter. 11132 if (FunctionTemplateDecl *FunctionTemplate 11133 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11134 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11135 Ret = true; 11136 } 11137 // If we have explicit template arguments supplied, skip non-templates. 11138 else if (!OvlExpr->hasExplicitTemplateArgs() && 11139 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11140 Ret = true; 11141 } 11142 assert(Ret || Matches.empty()); 11143 return Ret; 11144 } 11145 11146 void EliminateAllExceptMostSpecializedTemplate() { 11147 // [...] and any given function template specialization F1 is 11148 // eliminated if the set contains a second function template 11149 // specialization whose function template is more specialized 11150 // than the function template of F1 according to the partial 11151 // ordering rules of 14.5.5.2. 11152 11153 // The algorithm specified above is quadratic. We instead use a 11154 // two-pass algorithm (similar to the one used to identify the 11155 // best viable function in an overload set) that identifies the 11156 // best function template (if it exists). 11157 11158 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11159 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11160 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11161 11162 // TODO: It looks like FailedCandidates does not serve much purpose 11163 // here, since the no_viable diagnostic has index 0. 11164 UnresolvedSetIterator Result = S.getMostSpecialized( 11165 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11166 SourceExpr->getBeginLoc(), S.PDiag(), 11167 S.PDiag(diag::err_addr_ovl_ambiguous) 11168 << Matches[0].second->getDeclName(), 11169 S.PDiag(diag::note_ovl_candidate) 11170 << (unsigned)oc_function << (unsigned)ocs_described_template, 11171 Complain, TargetFunctionType); 11172 11173 if (Result != MatchesCopy.end()) { 11174 // Make it the first and only element 11175 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11176 Matches[0].second = cast<FunctionDecl>(*Result); 11177 Matches.resize(1); 11178 } else 11179 HasComplained |= Complain; 11180 } 11181 11182 void EliminateAllTemplateMatches() { 11183 // [...] any function template specializations in the set are 11184 // eliminated if the set also contains a non-template function, [...] 11185 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11186 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11187 ++I; 11188 else { 11189 Matches[I] = Matches[--N]; 11190 Matches.resize(N); 11191 } 11192 } 11193 } 11194 11195 void EliminateSuboptimalCudaMatches() { 11196 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11197 } 11198 11199 public: 11200 void ComplainNoMatchesFound() const { 11201 assert(Matches.empty()); 11202 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11203 << OvlExpr->getName() << TargetFunctionType 11204 << OvlExpr->getSourceRange(); 11205 if (FailedCandidates.empty()) 11206 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11207 /*TakingAddress=*/true); 11208 else { 11209 // We have some deduction failure messages. Use them to diagnose 11210 // the function templates, and diagnose the non-template candidates 11211 // normally. 11212 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11213 IEnd = OvlExpr->decls_end(); 11214 I != IEnd; ++I) 11215 if (FunctionDecl *Fun = 11216 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11217 if (!functionHasPassObjectSizeParams(Fun)) 11218 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11219 /*TakingAddress=*/true); 11220 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11221 } 11222 } 11223 11224 bool IsInvalidFormOfPointerToMemberFunction() const { 11225 return TargetTypeIsNonStaticMemberFunction && 11226 !OvlExprInfo.HasFormOfMemberPointer; 11227 } 11228 11229 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11230 // TODO: Should we condition this on whether any functions might 11231 // have matched, or is it more appropriate to do that in callers? 11232 // TODO: a fixit wouldn't hurt. 11233 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11234 << TargetType << OvlExpr->getSourceRange(); 11235 } 11236 11237 bool IsStaticMemberFunctionFromBoundPointer() const { 11238 return StaticMemberFunctionFromBoundPointer; 11239 } 11240 11241 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11242 S.Diag(OvlExpr->getBeginLoc(), 11243 diag::err_invalid_form_pointer_member_function) 11244 << OvlExpr->getSourceRange(); 11245 } 11246 11247 void ComplainOfInvalidConversion() const { 11248 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11249 << OvlExpr->getName() << TargetType; 11250 } 11251 11252 void ComplainMultipleMatchesFound() const { 11253 assert(Matches.size() > 1); 11254 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11255 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11256 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11257 /*TakingAddress=*/true); 11258 } 11259 11260 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11261 11262 int getNumMatches() const { return Matches.size(); } 11263 11264 FunctionDecl* getMatchingFunctionDecl() const { 11265 if (Matches.size() != 1) return nullptr; 11266 return Matches[0].second; 11267 } 11268 11269 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11270 if (Matches.size() != 1) return nullptr; 11271 return &Matches[0].first; 11272 } 11273 }; 11274 } 11275 11276 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11277 /// an overloaded function (C++ [over.over]), where @p From is an 11278 /// expression with overloaded function type and @p ToType is the type 11279 /// we're trying to resolve to. For example: 11280 /// 11281 /// @code 11282 /// int f(double); 11283 /// int f(int); 11284 /// 11285 /// int (*pfd)(double) = f; // selects f(double) 11286 /// @endcode 11287 /// 11288 /// This routine returns the resulting FunctionDecl if it could be 11289 /// resolved, and NULL otherwise. When @p Complain is true, this 11290 /// routine will emit diagnostics if there is an error. 11291 FunctionDecl * 11292 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11293 QualType TargetType, 11294 bool Complain, 11295 DeclAccessPair &FoundResult, 11296 bool *pHadMultipleCandidates) { 11297 assert(AddressOfExpr->getType() == Context.OverloadTy); 11298 11299 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11300 Complain); 11301 int NumMatches = Resolver.getNumMatches(); 11302 FunctionDecl *Fn = nullptr; 11303 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11304 if (NumMatches == 0 && ShouldComplain) { 11305 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11306 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11307 else 11308 Resolver.ComplainNoMatchesFound(); 11309 } 11310 else if (NumMatches > 1 && ShouldComplain) 11311 Resolver.ComplainMultipleMatchesFound(); 11312 else if (NumMatches == 1) { 11313 Fn = Resolver.getMatchingFunctionDecl(); 11314 assert(Fn); 11315 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11316 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11317 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11318 if (Complain) { 11319 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11320 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11321 else 11322 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11323 } 11324 } 11325 11326 if (pHadMultipleCandidates) 11327 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11328 return Fn; 11329 } 11330 11331 /// Given an expression that refers to an overloaded function, try to 11332 /// resolve that function to a single function that can have its address taken. 11333 /// This will modify `Pair` iff it returns non-null. 11334 /// 11335 /// This routine can only realistically succeed if all but one candidates in the 11336 /// overload set for SrcExpr cannot have their addresses taken. 11337 FunctionDecl * 11338 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11339 DeclAccessPair &Pair) { 11340 OverloadExpr::FindResult R = OverloadExpr::find(E); 11341 OverloadExpr *Ovl = R.Expression; 11342 FunctionDecl *Result = nullptr; 11343 DeclAccessPair DAP; 11344 // Don't use the AddressOfResolver because we're specifically looking for 11345 // cases where we have one overload candidate that lacks 11346 // enable_if/pass_object_size/... 11347 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11348 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11349 if (!FD) 11350 return nullptr; 11351 11352 if (!checkAddressOfFunctionIsAvailable(FD)) 11353 continue; 11354 11355 // We have more than one result; quit. 11356 if (Result) 11357 return nullptr; 11358 DAP = I.getPair(); 11359 Result = FD; 11360 } 11361 11362 if (Result) 11363 Pair = DAP; 11364 return Result; 11365 } 11366 11367 /// Given an overloaded function, tries to turn it into a non-overloaded 11368 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11369 /// will perform access checks, diagnose the use of the resultant decl, and, if 11370 /// requested, potentially perform a function-to-pointer decay. 11371 /// 11372 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11373 /// Otherwise, returns true. This may emit diagnostics and return true. 11374 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11375 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11376 Expr *E = SrcExpr.get(); 11377 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11378 11379 DeclAccessPair DAP; 11380 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11381 if (!Found || Found->isCPUDispatchMultiVersion() || 11382 Found->isCPUSpecificMultiVersion()) 11383 return false; 11384 11385 // Emitting multiple diagnostics for a function that is both inaccessible and 11386 // unavailable is consistent with our behavior elsewhere. So, always check 11387 // for both. 11388 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11389 CheckAddressOfMemberAccess(E, DAP); 11390 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11391 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11392 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11393 else 11394 SrcExpr = Fixed; 11395 return true; 11396 } 11397 11398 /// Given an expression that refers to an overloaded function, try to 11399 /// resolve that overloaded function expression down to a single function. 11400 /// 11401 /// This routine can only resolve template-ids that refer to a single function 11402 /// template, where that template-id refers to a single template whose template 11403 /// arguments are either provided by the template-id or have defaults, 11404 /// as described in C++0x [temp.arg.explicit]p3. 11405 /// 11406 /// If no template-ids are found, no diagnostics are emitted and NULL is 11407 /// returned. 11408 FunctionDecl * 11409 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11410 bool Complain, 11411 DeclAccessPair *FoundResult) { 11412 // C++ [over.over]p1: 11413 // [...] [Note: any redundant set of parentheses surrounding the 11414 // overloaded function name is ignored (5.1). ] 11415 // C++ [over.over]p1: 11416 // [...] The overloaded function name can be preceded by the & 11417 // operator. 11418 11419 // If we didn't actually find any template-ids, we're done. 11420 if (!ovl->hasExplicitTemplateArgs()) 11421 return nullptr; 11422 11423 TemplateArgumentListInfo ExplicitTemplateArgs; 11424 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11425 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11426 11427 // Look through all of the overloaded functions, searching for one 11428 // whose type matches exactly. 11429 FunctionDecl *Matched = nullptr; 11430 for (UnresolvedSetIterator I = ovl->decls_begin(), 11431 E = ovl->decls_end(); I != E; ++I) { 11432 // C++0x [temp.arg.explicit]p3: 11433 // [...] In contexts where deduction is done and fails, or in contexts 11434 // where deduction is not done, if a template argument list is 11435 // specified and it, along with any default template arguments, 11436 // identifies a single function template specialization, then the 11437 // template-id is an lvalue for the function template specialization. 11438 FunctionTemplateDecl *FunctionTemplate 11439 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11440 11441 // C++ [over.over]p2: 11442 // If the name is a function template, template argument deduction is 11443 // done (14.8.2.2), and if the argument deduction succeeds, the 11444 // resulting template argument list is used to generate a single 11445 // function template specialization, which is added to the set of 11446 // overloaded functions considered. 11447 FunctionDecl *Specialization = nullptr; 11448 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11449 if (TemplateDeductionResult Result 11450 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11451 Specialization, Info, 11452 /*IsAddressOfFunction*/true)) { 11453 // Make a note of the failed deduction for diagnostics. 11454 // TODO: Actually use the failed-deduction info? 11455 FailedCandidates.addCandidate() 11456 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11457 MakeDeductionFailureInfo(Context, Result, Info)); 11458 continue; 11459 } 11460 11461 assert(Specialization && "no specialization and no error?"); 11462 11463 // Multiple matches; we can't resolve to a single declaration. 11464 if (Matched) { 11465 if (Complain) { 11466 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11467 << ovl->getName(); 11468 NoteAllOverloadCandidates(ovl); 11469 } 11470 return nullptr; 11471 } 11472 11473 Matched = Specialization; 11474 if (FoundResult) *FoundResult = I.getPair(); 11475 } 11476 11477 if (Matched && 11478 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11479 return nullptr; 11480 11481 return Matched; 11482 } 11483 11484 // Resolve and fix an overloaded expression that can be resolved 11485 // because it identifies a single function template specialization. 11486 // 11487 // Last three arguments should only be supplied if Complain = true 11488 // 11489 // Return true if it was logically possible to so resolve the 11490 // expression, regardless of whether or not it succeeded. Always 11491 // returns true if 'complain' is set. 11492 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11493 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11494 bool complain, SourceRange OpRangeForComplaining, 11495 QualType DestTypeForComplaining, 11496 unsigned DiagIDForComplaining) { 11497 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11498 11499 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11500 11501 DeclAccessPair found; 11502 ExprResult SingleFunctionExpression; 11503 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11504 ovl.Expression, /*complain*/ false, &found)) { 11505 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11506 SrcExpr = ExprError(); 11507 return true; 11508 } 11509 11510 // It is only correct to resolve to an instance method if we're 11511 // resolving a form that's permitted to be a pointer to member. 11512 // Otherwise we'll end up making a bound member expression, which 11513 // is illegal in all the contexts we resolve like this. 11514 if (!ovl.HasFormOfMemberPointer && 11515 isa<CXXMethodDecl>(fn) && 11516 cast<CXXMethodDecl>(fn)->isInstance()) { 11517 if (!complain) return false; 11518 11519 Diag(ovl.Expression->getExprLoc(), 11520 diag::err_bound_member_function) 11521 << 0 << ovl.Expression->getSourceRange(); 11522 11523 // TODO: I believe we only end up here if there's a mix of 11524 // static and non-static candidates (otherwise the expression 11525 // would have 'bound member' type, not 'overload' type). 11526 // Ideally we would note which candidate was chosen and why 11527 // the static candidates were rejected. 11528 SrcExpr = ExprError(); 11529 return true; 11530 } 11531 11532 // Fix the expression to refer to 'fn'. 11533 SingleFunctionExpression = 11534 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11535 11536 // If desired, do function-to-pointer decay. 11537 if (doFunctionPointerConverion) { 11538 SingleFunctionExpression = 11539 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11540 if (SingleFunctionExpression.isInvalid()) { 11541 SrcExpr = ExprError(); 11542 return true; 11543 } 11544 } 11545 } 11546 11547 if (!SingleFunctionExpression.isUsable()) { 11548 if (complain) { 11549 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11550 << ovl.Expression->getName() 11551 << DestTypeForComplaining 11552 << OpRangeForComplaining 11553 << ovl.Expression->getQualifierLoc().getSourceRange(); 11554 NoteAllOverloadCandidates(SrcExpr.get()); 11555 11556 SrcExpr = ExprError(); 11557 return true; 11558 } 11559 11560 return false; 11561 } 11562 11563 SrcExpr = SingleFunctionExpression; 11564 return true; 11565 } 11566 11567 /// Add a single candidate to the overload set. 11568 static void AddOverloadedCallCandidate(Sema &S, 11569 DeclAccessPair FoundDecl, 11570 TemplateArgumentListInfo *ExplicitTemplateArgs, 11571 ArrayRef<Expr *> Args, 11572 OverloadCandidateSet &CandidateSet, 11573 bool PartialOverloading, 11574 bool KnownValid) { 11575 NamedDecl *Callee = FoundDecl.getDecl(); 11576 if (isa<UsingShadowDecl>(Callee)) 11577 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11578 11579 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11580 if (ExplicitTemplateArgs) { 11581 assert(!KnownValid && "Explicit template arguments?"); 11582 return; 11583 } 11584 // Prevent ill-formed function decls to be added as overload candidates. 11585 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11586 return; 11587 11588 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11589 /*SuppressUsedConversions=*/false, 11590 PartialOverloading); 11591 return; 11592 } 11593 11594 if (FunctionTemplateDecl *FuncTemplate 11595 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11596 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11597 ExplicitTemplateArgs, Args, CandidateSet, 11598 /*SuppressUsedConversions=*/false, 11599 PartialOverloading); 11600 return; 11601 } 11602 11603 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11604 } 11605 11606 /// Add the overload candidates named by callee and/or found by argument 11607 /// dependent lookup to the given overload set. 11608 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11609 ArrayRef<Expr *> Args, 11610 OverloadCandidateSet &CandidateSet, 11611 bool PartialOverloading) { 11612 11613 #ifndef NDEBUG 11614 // Verify that ArgumentDependentLookup is consistent with the rules 11615 // in C++0x [basic.lookup.argdep]p3: 11616 // 11617 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11618 // and let Y be the lookup set produced by argument dependent 11619 // lookup (defined as follows). If X contains 11620 // 11621 // -- a declaration of a class member, or 11622 // 11623 // -- a block-scope function declaration that is not a 11624 // using-declaration, or 11625 // 11626 // -- a declaration that is neither a function or a function 11627 // template 11628 // 11629 // then Y is empty. 11630 11631 if (ULE->requiresADL()) { 11632 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11633 E = ULE->decls_end(); I != E; ++I) { 11634 assert(!(*I)->getDeclContext()->isRecord()); 11635 assert(isa<UsingShadowDecl>(*I) || 11636 !(*I)->getDeclContext()->isFunctionOrMethod()); 11637 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11638 } 11639 } 11640 #endif 11641 11642 // It would be nice to avoid this copy. 11643 TemplateArgumentListInfo TABuffer; 11644 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11645 if (ULE->hasExplicitTemplateArgs()) { 11646 ULE->copyTemplateArgumentsInto(TABuffer); 11647 ExplicitTemplateArgs = &TABuffer; 11648 } 11649 11650 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11651 E = ULE->decls_end(); I != E; ++I) 11652 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11653 CandidateSet, PartialOverloading, 11654 /*KnownValid*/ true); 11655 11656 if (ULE->requiresADL()) 11657 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11658 Args, ExplicitTemplateArgs, 11659 CandidateSet, PartialOverloading); 11660 } 11661 11662 /// Determine whether a declaration with the specified name could be moved into 11663 /// a different namespace. 11664 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11665 switch (Name.getCXXOverloadedOperator()) { 11666 case OO_New: case OO_Array_New: 11667 case OO_Delete: case OO_Array_Delete: 11668 return false; 11669 11670 default: 11671 return true; 11672 } 11673 } 11674 11675 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11676 /// template, where the non-dependent name was declared after the template 11677 /// was defined. This is common in code written for a compilers which do not 11678 /// correctly implement two-stage name lookup. 11679 /// 11680 /// Returns true if a viable candidate was found and a diagnostic was issued. 11681 static bool 11682 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11683 const CXXScopeSpec &SS, LookupResult &R, 11684 OverloadCandidateSet::CandidateSetKind CSK, 11685 TemplateArgumentListInfo *ExplicitTemplateArgs, 11686 ArrayRef<Expr *> Args, 11687 bool *DoDiagnoseEmptyLookup = nullptr) { 11688 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11689 return false; 11690 11691 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11692 if (DC->isTransparentContext()) 11693 continue; 11694 11695 SemaRef.LookupQualifiedName(R, DC); 11696 11697 if (!R.empty()) { 11698 R.suppressDiagnostics(); 11699 11700 if (isa<CXXRecordDecl>(DC)) { 11701 // Don't diagnose names we find in classes; we get much better 11702 // diagnostics for these from DiagnoseEmptyLookup. 11703 R.clear(); 11704 if (DoDiagnoseEmptyLookup) 11705 *DoDiagnoseEmptyLookup = true; 11706 return false; 11707 } 11708 11709 OverloadCandidateSet Candidates(FnLoc, CSK); 11710 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11711 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11712 ExplicitTemplateArgs, Args, 11713 Candidates, false, /*KnownValid*/ false); 11714 11715 OverloadCandidateSet::iterator Best; 11716 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11717 // No viable functions. Don't bother the user with notes for functions 11718 // which don't work and shouldn't be found anyway. 11719 R.clear(); 11720 return false; 11721 } 11722 11723 // Find the namespaces where ADL would have looked, and suggest 11724 // declaring the function there instead. 11725 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11726 Sema::AssociatedClassSet AssociatedClasses; 11727 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11728 AssociatedNamespaces, 11729 AssociatedClasses); 11730 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11731 if (canBeDeclaredInNamespace(R.getLookupName())) { 11732 DeclContext *Std = SemaRef.getStdNamespace(); 11733 for (Sema::AssociatedNamespaceSet::iterator 11734 it = AssociatedNamespaces.begin(), 11735 end = AssociatedNamespaces.end(); it != end; ++it) { 11736 // Never suggest declaring a function within namespace 'std'. 11737 if (Std && Std->Encloses(*it)) 11738 continue; 11739 11740 // Never suggest declaring a function within a namespace with a 11741 // reserved name, like __gnu_cxx. 11742 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11743 if (NS && 11744 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11745 continue; 11746 11747 SuggestedNamespaces.insert(*it); 11748 } 11749 } 11750 11751 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11752 << R.getLookupName(); 11753 if (SuggestedNamespaces.empty()) { 11754 SemaRef.Diag(Best->Function->getLocation(), 11755 diag::note_not_found_by_two_phase_lookup) 11756 << R.getLookupName() << 0; 11757 } else if (SuggestedNamespaces.size() == 1) { 11758 SemaRef.Diag(Best->Function->getLocation(), 11759 diag::note_not_found_by_two_phase_lookup) 11760 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11761 } else { 11762 // FIXME: It would be useful to list the associated namespaces here, 11763 // but the diagnostics infrastructure doesn't provide a way to produce 11764 // a localized representation of a list of items. 11765 SemaRef.Diag(Best->Function->getLocation(), 11766 diag::note_not_found_by_two_phase_lookup) 11767 << R.getLookupName() << 2; 11768 } 11769 11770 // Try to recover by calling this function. 11771 return true; 11772 } 11773 11774 R.clear(); 11775 } 11776 11777 return false; 11778 } 11779 11780 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11781 /// template, where the non-dependent operator was declared after the template 11782 /// was defined. 11783 /// 11784 /// Returns true if a viable candidate was found and a diagnostic was issued. 11785 static bool 11786 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11787 SourceLocation OpLoc, 11788 ArrayRef<Expr *> Args) { 11789 DeclarationName OpName = 11790 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11791 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11792 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11793 OverloadCandidateSet::CSK_Operator, 11794 /*ExplicitTemplateArgs=*/nullptr, Args); 11795 } 11796 11797 namespace { 11798 class BuildRecoveryCallExprRAII { 11799 Sema &SemaRef; 11800 public: 11801 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11802 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11803 SemaRef.IsBuildingRecoveryCallExpr = true; 11804 } 11805 11806 ~BuildRecoveryCallExprRAII() { 11807 SemaRef.IsBuildingRecoveryCallExpr = false; 11808 } 11809 }; 11810 11811 } 11812 11813 static std::unique_ptr<CorrectionCandidateCallback> 11814 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11815 bool HasTemplateArgs, bool AllowTypoCorrection) { 11816 if (!AllowTypoCorrection) 11817 return llvm::make_unique<NoTypoCorrectionCCC>(); 11818 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11819 HasTemplateArgs, ME); 11820 } 11821 11822 /// Attempts to recover from a call where no functions were found. 11823 /// 11824 /// Returns true if new candidates were found. 11825 static ExprResult 11826 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11827 UnresolvedLookupExpr *ULE, 11828 SourceLocation LParenLoc, 11829 MutableArrayRef<Expr *> Args, 11830 SourceLocation RParenLoc, 11831 bool EmptyLookup, bool AllowTypoCorrection) { 11832 // Do not try to recover if it is already building a recovery call. 11833 // This stops infinite loops for template instantiations like 11834 // 11835 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11836 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11837 // 11838 if (SemaRef.IsBuildingRecoveryCallExpr) 11839 return ExprError(); 11840 BuildRecoveryCallExprRAII RCE(SemaRef); 11841 11842 CXXScopeSpec SS; 11843 SS.Adopt(ULE->getQualifierLoc()); 11844 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11845 11846 TemplateArgumentListInfo TABuffer; 11847 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11848 if (ULE->hasExplicitTemplateArgs()) { 11849 ULE->copyTemplateArgumentsInto(TABuffer); 11850 ExplicitTemplateArgs = &TABuffer; 11851 } 11852 11853 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11854 Sema::LookupOrdinaryName); 11855 bool DoDiagnoseEmptyLookup = EmptyLookup; 11856 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11857 OverloadCandidateSet::CSK_Normal, 11858 ExplicitTemplateArgs, Args, 11859 &DoDiagnoseEmptyLookup) && 11860 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11861 S, SS, R, 11862 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11863 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11864 ExplicitTemplateArgs, Args))) 11865 return ExprError(); 11866 11867 assert(!R.empty() && "lookup results empty despite recovery"); 11868 11869 // If recovery created an ambiguity, just bail out. 11870 if (R.isAmbiguous()) { 11871 R.suppressDiagnostics(); 11872 return ExprError(); 11873 } 11874 11875 // Build an implicit member call if appropriate. Just drop the 11876 // casts and such from the call, we don't really care. 11877 ExprResult NewFn = ExprError(); 11878 if ((*R.begin())->isCXXClassMember()) 11879 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11880 ExplicitTemplateArgs, S); 11881 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11882 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11883 ExplicitTemplateArgs); 11884 else 11885 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11886 11887 if (NewFn.isInvalid()) 11888 return ExprError(); 11889 11890 // This shouldn't cause an infinite loop because we're giving it 11891 // an expression with viable lookup results, which should never 11892 // end up here. 11893 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11894 MultiExprArg(Args.data(), Args.size()), 11895 RParenLoc); 11896 } 11897 11898 /// Constructs and populates an OverloadedCandidateSet from 11899 /// the given function. 11900 /// \returns true when an the ExprResult output parameter has been set. 11901 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11902 UnresolvedLookupExpr *ULE, 11903 MultiExprArg Args, 11904 SourceLocation RParenLoc, 11905 OverloadCandidateSet *CandidateSet, 11906 ExprResult *Result) { 11907 #ifndef NDEBUG 11908 if (ULE->requiresADL()) { 11909 // To do ADL, we must have found an unqualified name. 11910 assert(!ULE->getQualifier() && "qualified name with ADL"); 11911 11912 // We don't perform ADL for implicit declarations of builtins. 11913 // Verify that this was correctly set up. 11914 FunctionDecl *F; 11915 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11916 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11917 F->getBuiltinID() && F->isImplicit()) 11918 llvm_unreachable("performing ADL for builtin"); 11919 11920 // We don't perform ADL in C. 11921 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11922 } 11923 #endif 11924 11925 UnbridgedCastsSet UnbridgedCasts; 11926 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11927 *Result = ExprError(); 11928 return true; 11929 } 11930 11931 // Add the functions denoted by the callee to the set of candidate 11932 // functions, including those from argument-dependent lookup. 11933 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11934 11935 if (getLangOpts().MSVCCompat && 11936 CurContext->isDependentContext() && !isSFINAEContext() && 11937 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11938 11939 OverloadCandidateSet::iterator Best; 11940 if (CandidateSet->empty() || 11941 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 11942 OR_No_Viable_Function) { 11943 // In Microsoft mode, if we are inside a template class member function then 11944 // create a type dependent CallExpr. The goal is to postpone name lookup 11945 // to instantiation time to be able to search into type dependent base 11946 // classes. 11947 CallExpr *CE = new (Context) CallExpr( 11948 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11949 CE->setTypeDependent(true); 11950 CE->setValueDependent(true); 11951 CE->setInstantiationDependent(true); 11952 *Result = CE; 11953 return true; 11954 } 11955 } 11956 11957 if (CandidateSet->empty()) 11958 return false; 11959 11960 UnbridgedCasts.restore(); 11961 return false; 11962 } 11963 11964 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11965 /// the completed call expression. If overload resolution fails, emits 11966 /// diagnostics and returns ExprError() 11967 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11968 UnresolvedLookupExpr *ULE, 11969 SourceLocation LParenLoc, 11970 MultiExprArg Args, 11971 SourceLocation RParenLoc, 11972 Expr *ExecConfig, 11973 OverloadCandidateSet *CandidateSet, 11974 OverloadCandidateSet::iterator *Best, 11975 OverloadingResult OverloadResult, 11976 bool AllowTypoCorrection) { 11977 if (CandidateSet->empty()) 11978 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11979 RParenLoc, /*EmptyLookup=*/true, 11980 AllowTypoCorrection); 11981 11982 switch (OverloadResult) { 11983 case OR_Success: { 11984 FunctionDecl *FDecl = (*Best)->Function; 11985 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11986 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11987 return ExprError(); 11988 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11989 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11990 ExecConfig); 11991 } 11992 11993 case OR_No_Viable_Function: { 11994 // Try to recover by looking for viable functions which the user might 11995 // have meant to call. 11996 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11997 Args, RParenLoc, 11998 /*EmptyLookup=*/false, 11999 AllowTypoCorrection); 12000 if (!Recovery.isInvalid()) 12001 return Recovery; 12002 12003 // If the user passes in a function that we can't take the address of, we 12004 // generally end up emitting really bad error messages. Here, we attempt to 12005 // emit better ones. 12006 for (const Expr *Arg : Args) { 12007 if (!Arg->getType()->isFunctionType()) 12008 continue; 12009 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12010 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12011 if (FD && 12012 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12013 Arg->getExprLoc())) 12014 return ExprError(); 12015 } 12016 } 12017 12018 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call) 12019 << ULE->getName() << Fn->getSourceRange(); 12020 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12021 break; 12022 } 12023 12024 case OR_Ambiguous: 12025 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call) 12026 << ULE->getName() << Fn->getSourceRange(); 12027 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12028 break; 12029 12030 case OR_Deleted: { 12031 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call) 12032 << (*Best)->Function->isDeleted() << ULE->getName() 12033 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12034 << Fn->getSourceRange(); 12035 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12036 12037 // We emitted an error for the unavailable/deleted function call but keep 12038 // the call in the AST. 12039 FunctionDecl *FDecl = (*Best)->Function; 12040 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12041 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12042 ExecConfig); 12043 } 12044 } 12045 12046 // Overload resolution failed. 12047 return ExprError(); 12048 } 12049 12050 static void markUnaddressableCandidatesUnviable(Sema &S, 12051 OverloadCandidateSet &CS) { 12052 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12053 if (I->Viable && 12054 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12055 I->Viable = false; 12056 I->FailureKind = ovl_fail_addr_not_available; 12057 } 12058 } 12059 } 12060 12061 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12062 /// (which eventually refers to the declaration Func) and the call 12063 /// arguments Args/NumArgs, attempt to resolve the function call down 12064 /// to a specific function. If overload resolution succeeds, returns 12065 /// the call expression produced by overload resolution. 12066 /// Otherwise, emits diagnostics and returns ExprError. 12067 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12068 UnresolvedLookupExpr *ULE, 12069 SourceLocation LParenLoc, 12070 MultiExprArg Args, 12071 SourceLocation RParenLoc, 12072 Expr *ExecConfig, 12073 bool AllowTypoCorrection, 12074 bool CalleesAddressIsTaken) { 12075 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12076 OverloadCandidateSet::CSK_Normal); 12077 ExprResult result; 12078 12079 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12080 &result)) 12081 return result; 12082 12083 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12084 // functions that aren't addressible are considered unviable. 12085 if (CalleesAddressIsTaken) 12086 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12087 12088 OverloadCandidateSet::iterator Best; 12089 OverloadingResult OverloadResult = 12090 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12091 12092 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12093 RParenLoc, ExecConfig, &CandidateSet, 12094 &Best, OverloadResult, 12095 AllowTypoCorrection); 12096 } 12097 12098 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12099 return Functions.size() > 1 || 12100 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12101 } 12102 12103 /// Create a unary operation that may resolve to an overloaded 12104 /// operator. 12105 /// 12106 /// \param OpLoc The location of the operator itself (e.g., '*'). 12107 /// 12108 /// \param Opc The UnaryOperatorKind that describes this operator. 12109 /// 12110 /// \param Fns The set of non-member functions that will be 12111 /// considered by overload resolution. The caller needs to build this 12112 /// set based on the context using, e.g., 12113 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12114 /// set should not contain any member functions; those will be added 12115 /// by CreateOverloadedUnaryOp(). 12116 /// 12117 /// \param Input The input argument. 12118 ExprResult 12119 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12120 const UnresolvedSetImpl &Fns, 12121 Expr *Input, bool PerformADL) { 12122 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12123 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12124 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12125 // TODO: provide better source location info. 12126 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12127 12128 if (checkPlaceholderForOverload(*this, Input)) 12129 return ExprError(); 12130 12131 Expr *Args[2] = { Input, nullptr }; 12132 unsigned NumArgs = 1; 12133 12134 // For post-increment and post-decrement, add the implicit '0' as 12135 // the second argument, so that we know this is a post-increment or 12136 // post-decrement. 12137 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12138 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12139 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12140 SourceLocation()); 12141 NumArgs = 2; 12142 } 12143 12144 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12145 12146 if (Input->isTypeDependent()) { 12147 if (Fns.empty()) 12148 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12149 VK_RValue, OK_Ordinary, OpLoc, false); 12150 12151 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12152 UnresolvedLookupExpr *Fn 12153 = UnresolvedLookupExpr::Create(Context, NamingClass, 12154 NestedNameSpecifierLoc(), OpNameInfo, 12155 /*ADL*/ true, IsOverloaded(Fns), 12156 Fns.begin(), Fns.end()); 12157 return new (Context) 12158 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 12159 VK_RValue, OpLoc, FPOptions()); 12160 } 12161 12162 // Build an empty overload set. 12163 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12164 12165 // Add the candidates from the given function set. 12166 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12167 12168 // Add operator candidates that are member functions. 12169 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12170 12171 // Add candidates from ADL. 12172 if (PerformADL) { 12173 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12174 /*ExplicitTemplateArgs*/nullptr, 12175 CandidateSet); 12176 } 12177 12178 // Add builtin operator candidates. 12179 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12180 12181 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12182 12183 // Perform overload resolution. 12184 OverloadCandidateSet::iterator Best; 12185 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12186 case OR_Success: { 12187 // We found a built-in operator or an overloaded operator. 12188 FunctionDecl *FnDecl = Best->Function; 12189 12190 if (FnDecl) { 12191 Expr *Base = nullptr; 12192 // We matched an overloaded operator. Build a call to that 12193 // operator. 12194 12195 // Convert the arguments. 12196 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12197 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12198 12199 ExprResult InputRes = 12200 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12201 Best->FoundDecl, Method); 12202 if (InputRes.isInvalid()) 12203 return ExprError(); 12204 Base = Input = InputRes.get(); 12205 } else { 12206 // Convert the arguments. 12207 ExprResult InputInit 12208 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12209 Context, 12210 FnDecl->getParamDecl(0)), 12211 SourceLocation(), 12212 Input); 12213 if (InputInit.isInvalid()) 12214 return ExprError(); 12215 Input = InputInit.get(); 12216 } 12217 12218 // Build the actual expression node. 12219 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12220 Base, HadMultipleCandidates, 12221 OpLoc); 12222 if (FnExpr.isInvalid()) 12223 return ExprError(); 12224 12225 // Determine the result type. 12226 QualType ResultTy = FnDecl->getReturnType(); 12227 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12228 ResultTy = ResultTy.getNonLValueExprType(Context); 12229 12230 Args[0] = Input; 12231 CallExpr *TheCall = 12232 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12233 ResultTy, VK, OpLoc, FPOptions()); 12234 12235 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12236 return ExprError(); 12237 12238 if (CheckFunctionCall(FnDecl, TheCall, 12239 FnDecl->getType()->castAs<FunctionProtoType>())) 12240 return ExprError(); 12241 12242 return MaybeBindToTemporary(TheCall); 12243 } else { 12244 // We matched a built-in operator. Convert the arguments, then 12245 // break out so that we will build the appropriate built-in 12246 // operator node. 12247 ExprResult InputRes = PerformImplicitConversion( 12248 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12249 CCK_ForBuiltinOverloadedOp); 12250 if (InputRes.isInvalid()) 12251 return ExprError(); 12252 Input = InputRes.get(); 12253 break; 12254 } 12255 } 12256 12257 case OR_No_Viable_Function: 12258 // This is an erroneous use of an operator which can be overloaded by 12259 // a non-member function. Check for non-member operators which were 12260 // defined too late to be candidates. 12261 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12262 // FIXME: Recover by calling the found function. 12263 return ExprError(); 12264 12265 // No viable function; fall through to handling this as a 12266 // built-in operator, which will produce an error message for us. 12267 break; 12268 12269 case OR_Ambiguous: 12270 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12271 << UnaryOperator::getOpcodeStr(Opc) 12272 << Input->getType() 12273 << Input->getSourceRange(); 12274 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12275 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12276 return ExprError(); 12277 12278 case OR_Deleted: 12279 Diag(OpLoc, diag::err_ovl_deleted_oper) 12280 << Best->Function->isDeleted() 12281 << UnaryOperator::getOpcodeStr(Opc) 12282 << getDeletedOrUnavailableSuffix(Best->Function) 12283 << Input->getSourceRange(); 12284 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12285 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12286 return ExprError(); 12287 } 12288 12289 // Either we found no viable overloaded operator or we matched a 12290 // built-in operator. In either case, fall through to trying to 12291 // build a built-in operation. 12292 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12293 } 12294 12295 /// Create a binary operation that may resolve to an overloaded 12296 /// operator. 12297 /// 12298 /// \param OpLoc The location of the operator itself (e.g., '+'). 12299 /// 12300 /// \param Opc The BinaryOperatorKind that describes this operator. 12301 /// 12302 /// \param Fns The set of non-member functions that will be 12303 /// considered by overload resolution. The caller needs to build this 12304 /// set based on the context using, e.g., 12305 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12306 /// set should not contain any member functions; those will be added 12307 /// by CreateOverloadedBinOp(). 12308 /// 12309 /// \param LHS Left-hand argument. 12310 /// \param RHS Right-hand argument. 12311 ExprResult 12312 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12313 BinaryOperatorKind Opc, 12314 const UnresolvedSetImpl &Fns, 12315 Expr *LHS, Expr *RHS, bool PerformADL) { 12316 Expr *Args[2] = { LHS, RHS }; 12317 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12318 12319 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12320 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12321 12322 // If either side is type-dependent, create an appropriate dependent 12323 // expression. 12324 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12325 if (Fns.empty()) { 12326 // If there are no functions to store, just build a dependent 12327 // BinaryOperator or CompoundAssignment. 12328 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12329 return new (Context) BinaryOperator( 12330 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12331 OpLoc, FPFeatures); 12332 12333 return new (Context) CompoundAssignOperator( 12334 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12335 Context.DependentTy, Context.DependentTy, OpLoc, 12336 FPFeatures); 12337 } 12338 12339 // FIXME: save results of ADL from here? 12340 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12341 // TODO: provide better source location info in DNLoc component. 12342 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12343 UnresolvedLookupExpr *Fn 12344 = UnresolvedLookupExpr::Create(Context, NamingClass, 12345 NestedNameSpecifierLoc(), OpNameInfo, 12346 /*ADL*/PerformADL, IsOverloaded(Fns), 12347 Fns.begin(), Fns.end()); 12348 return new (Context) 12349 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12350 VK_RValue, OpLoc, FPFeatures); 12351 } 12352 12353 // Always do placeholder-like conversions on the RHS. 12354 if (checkPlaceholderForOverload(*this, Args[1])) 12355 return ExprError(); 12356 12357 // Do placeholder-like conversion on the LHS; note that we should 12358 // not get here with a PseudoObject LHS. 12359 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12360 if (checkPlaceholderForOverload(*this, Args[0])) 12361 return ExprError(); 12362 12363 // If this is the assignment operator, we only perform overload resolution 12364 // if the left-hand side is a class or enumeration type. This is actually 12365 // a hack. The standard requires that we do overload resolution between the 12366 // various built-in candidates, but as DR507 points out, this can lead to 12367 // problems. So we do it this way, which pretty much follows what GCC does. 12368 // Note that we go the traditional code path for compound assignment forms. 12369 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12370 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12371 12372 // If this is the .* operator, which is not overloadable, just 12373 // create a built-in binary operator. 12374 if (Opc == BO_PtrMemD) 12375 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12376 12377 // Build an empty overload set. 12378 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12379 12380 // Add the candidates from the given function set. 12381 AddFunctionCandidates(Fns, Args, CandidateSet); 12382 12383 // Add operator candidates that are member functions. 12384 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12385 12386 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12387 // performed for an assignment operator (nor for operator[] nor operator->, 12388 // which don't get here). 12389 if (Opc != BO_Assign && PerformADL) 12390 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12391 /*ExplicitTemplateArgs*/ nullptr, 12392 CandidateSet); 12393 12394 // Add builtin operator candidates. 12395 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12396 12397 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12398 12399 // Perform overload resolution. 12400 OverloadCandidateSet::iterator Best; 12401 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12402 case OR_Success: { 12403 // We found a built-in operator or an overloaded operator. 12404 FunctionDecl *FnDecl = Best->Function; 12405 12406 if (FnDecl) { 12407 Expr *Base = nullptr; 12408 // We matched an overloaded operator. Build a call to that 12409 // operator. 12410 12411 // Convert the arguments. 12412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12413 // Best->Access is only meaningful for class members. 12414 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12415 12416 ExprResult Arg1 = 12417 PerformCopyInitialization( 12418 InitializedEntity::InitializeParameter(Context, 12419 FnDecl->getParamDecl(0)), 12420 SourceLocation(), Args[1]); 12421 if (Arg1.isInvalid()) 12422 return ExprError(); 12423 12424 ExprResult Arg0 = 12425 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12426 Best->FoundDecl, Method); 12427 if (Arg0.isInvalid()) 12428 return ExprError(); 12429 Base = Args[0] = Arg0.getAs<Expr>(); 12430 Args[1] = RHS = Arg1.getAs<Expr>(); 12431 } else { 12432 // Convert the arguments. 12433 ExprResult Arg0 = PerformCopyInitialization( 12434 InitializedEntity::InitializeParameter(Context, 12435 FnDecl->getParamDecl(0)), 12436 SourceLocation(), Args[0]); 12437 if (Arg0.isInvalid()) 12438 return ExprError(); 12439 12440 ExprResult Arg1 = 12441 PerformCopyInitialization( 12442 InitializedEntity::InitializeParameter(Context, 12443 FnDecl->getParamDecl(1)), 12444 SourceLocation(), Args[1]); 12445 if (Arg1.isInvalid()) 12446 return ExprError(); 12447 Args[0] = LHS = Arg0.getAs<Expr>(); 12448 Args[1] = RHS = Arg1.getAs<Expr>(); 12449 } 12450 12451 // Build the actual expression node. 12452 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12453 Best->FoundDecl, Base, 12454 HadMultipleCandidates, OpLoc); 12455 if (FnExpr.isInvalid()) 12456 return ExprError(); 12457 12458 // Determine the result type. 12459 QualType ResultTy = FnDecl->getReturnType(); 12460 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12461 ResultTy = ResultTy.getNonLValueExprType(Context); 12462 12463 CXXOperatorCallExpr *TheCall = 12464 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12465 Args, ResultTy, VK, OpLoc, 12466 FPFeatures); 12467 12468 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12469 FnDecl)) 12470 return ExprError(); 12471 12472 ArrayRef<const Expr *> ArgsArray(Args, 2); 12473 const Expr *ImplicitThis = nullptr; 12474 // Cut off the implicit 'this'. 12475 if (isa<CXXMethodDecl>(FnDecl)) { 12476 ImplicitThis = ArgsArray[0]; 12477 ArgsArray = ArgsArray.slice(1); 12478 } 12479 12480 // Check for a self move. 12481 if (Op == OO_Equal) 12482 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12483 12484 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12485 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12486 VariadicDoesNotApply); 12487 12488 return MaybeBindToTemporary(TheCall); 12489 } else { 12490 // We matched a built-in operator. Convert the arguments, then 12491 // break out so that we will build the appropriate built-in 12492 // operator node. 12493 ExprResult ArgsRes0 = PerformImplicitConversion( 12494 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12495 AA_Passing, CCK_ForBuiltinOverloadedOp); 12496 if (ArgsRes0.isInvalid()) 12497 return ExprError(); 12498 Args[0] = ArgsRes0.get(); 12499 12500 ExprResult ArgsRes1 = PerformImplicitConversion( 12501 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12502 AA_Passing, CCK_ForBuiltinOverloadedOp); 12503 if (ArgsRes1.isInvalid()) 12504 return ExprError(); 12505 Args[1] = ArgsRes1.get(); 12506 break; 12507 } 12508 } 12509 12510 case OR_No_Viable_Function: { 12511 // C++ [over.match.oper]p9: 12512 // If the operator is the operator , [...] and there are no 12513 // viable functions, then the operator is assumed to be the 12514 // built-in operator and interpreted according to clause 5. 12515 if (Opc == BO_Comma) 12516 break; 12517 12518 // For class as left operand for assignment or compound assignment 12519 // operator do not fall through to handling in built-in, but report that 12520 // no overloaded assignment operator found 12521 ExprResult Result = ExprError(); 12522 if (Args[0]->getType()->isRecordType() && 12523 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12524 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12525 << BinaryOperator::getOpcodeStr(Opc) 12526 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12527 if (Args[0]->getType()->isIncompleteType()) { 12528 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12529 << Args[0]->getType() 12530 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12531 } 12532 } else { 12533 // This is an erroneous use of an operator which can be overloaded by 12534 // a non-member function. Check for non-member operators which were 12535 // defined too late to be candidates. 12536 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12537 // FIXME: Recover by calling the found function. 12538 return ExprError(); 12539 12540 // No viable function; try to create a built-in operation, which will 12541 // produce an error. Then, show the non-viable candidates. 12542 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12543 } 12544 assert(Result.isInvalid() && 12545 "C++ binary operator overloading is missing candidates!"); 12546 if (Result.isInvalid()) 12547 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12548 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12549 return Result; 12550 } 12551 12552 case OR_Ambiguous: 12553 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12554 << BinaryOperator::getOpcodeStr(Opc) 12555 << Args[0]->getType() << Args[1]->getType() 12556 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12557 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12558 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12559 return ExprError(); 12560 12561 case OR_Deleted: 12562 if (isImplicitlyDeleted(Best->Function)) { 12563 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12564 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12565 << Context.getRecordType(Method->getParent()) 12566 << getSpecialMember(Method); 12567 12568 // The user probably meant to call this special member. Just 12569 // explain why it's deleted. 12570 NoteDeletedFunction(Method); 12571 return ExprError(); 12572 } else { 12573 Diag(OpLoc, diag::err_ovl_deleted_oper) 12574 << Best->Function->isDeleted() 12575 << BinaryOperator::getOpcodeStr(Opc) 12576 << getDeletedOrUnavailableSuffix(Best->Function) 12577 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12578 } 12579 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12580 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12581 return ExprError(); 12582 } 12583 12584 // We matched a built-in operator; build it. 12585 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12586 } 12587 12588 ExprResult 12589 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12590 SourceLocation RLoc, 12591 Expr *Base, Expr *Idx) { 12592 Expr *Args[2] = { Base, Idx }; 12593 DeclarationName OpName = 12594 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12595 12596 // If either side is type-dependent, create an appropriate dependent 12597 // expression. 12598 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12599 12600 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12601 // CHECKME: no 'operator' keyword? 12602 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12603 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12604 UnresolvedLookupExpr *Fn 12605 = UnresolvedLookupExpr::Create(Context, NamingClass, 12606 NestedNameSpecifierLoc(), OpNameInfo, 12607 /*ADL*/ true, /*Overloaded*/ false, 12608 UnresolvedSetIterator(), 12609 UnresolvedSetIterator()); 12610 // Can't add any actual overloads yet 12611 12612 return new (Context) 12613 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12614 Context.DependentTy, VK_RValue, RLoc, FPOptions()); 12615 } 12616 12617 // Handle placeholders on both operands. 12618 if (checkPlaceholderForOverload(*this, Args[0])) 12619 return ExprError(); 12620 if (checkPlaceholderForOverload(*this, Args[1])) 12621 return ExprError(); 12622 12623 // Build an empty overload set. 12624 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12625 12626 // Subscript can only be overloaded as a member function. 12627 12628 // Add operator candidates that are member functions. 12629 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12630 12631 // Add builtin operator candidates. 12632 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12633 12634 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12635 12636 // Perform overload resolution. 12637 OverloadCandidateSet::iterator Best; 12638 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12639 case OR_Success: { 12640 // We found a built-in operator or an overloaded operator. 12641 FunctionDecl *FnDecl = Best->Function; 12642 12643 if (FnDecl) { 12644 // We matched an overloaded operator. Build a call to that 12645 // operator. 12646 12647 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12648 12649 // Convert the arguments. 12650 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12651 ExprResult Arg0 = 12652 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12653 Best->FoundDecl, Method); 12654 if (Arg0.isInvalid()) 12655 return ExprError(); 12656 Args[0] = Arg0.get(); 12657 12658 // Convert the arguments. 12659 ExprResult InputInit 12660 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12661 Context, 12662 FnDecl->getParamDecl(0)), 12663 SourceLocation(), 12664 Args[1]); 12665 if (InputInit.isInvalid()) 12666 return ExprError(); 12667 12668 Args[1] = InputInit.getAs<Expr>(); 12669 12670 // Build the actual expression node. 12671 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12672 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12673 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12674 Best->FoundDecl, 12675 Base, 12676 HadMultipleCandidates, 12677 OpLocInfo.getLoc(), 12678 OpLocInfo.getInfo()); 12679 if (FnExpr.isInvalid()) 12680 return ExprError(); 12681 12682 // Determine the result type 12683 QualType ResultTy = FnDecl->getReturnType(); 12684 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12685 ResultTy = ResultTy.getNonLValueExprType(Context); 12686 12687 CXXOperatorCallExpr *TheCall = 12688 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12689 FnExpr.get(), Args, 12690 ResultTy, VK, RLoc, 12691 FPOptions()); 12692 12693 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12694 return ExprError(); 12695 12696 if (CheckFunctionCall(Method, TheCall, 12697 Method->getType()->castAs<FunctionProtoType>())) 12698 return ExprError(); 12699 12700 return MaybeBindToTemporary(TheCall); 12701 } else { 12702 // We matched a built-in operator. Convert the arguments, then 12703 // break out so that we will build the appropriate built-in 12704 // operator node. 12705 ExprResult ArgsRes0 = PerformImplicitConversion( 12706 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12707 AA_Passing, CCK_ForBuiltinOverloadedOp); 12708 if (ArgsRes0.isInvalid()) 12709 return ExprError(); 12710 Args[0] = ArgsRes0.get(); 12711 12712 ExprResult ArgsRes1 = PerformImplicitConversion( 12713 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12714 AA_Passing, CCK_ForBuiltinOverloadedOp); 12715 if (ArgsRes1.isInvalid()) 12716 return ExprError(); 12717 Args[1] = ArgsRes1.get(); 12718 12719 break; 12720 } 12721 } 12722 12723 case OR_No_Viable_Function: { 12724 if (CandidateSet.empty()) 12725 Diag(LLoc, diag::err_ovl_no_oper) 12726 << Args[0]->getType() << /*subscript*/ 0 12727 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12728 else 12729 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12730 << Args[0]->getType() 12731 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12733 "[]", LLoc); 12734 return ExprError(); 12735 } 12736 12737 case OR_Ambiguous: 12738 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12739 << "[]" 12740 << Args[0]->getType() << Args[1]->getType() 12741 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12742 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12743 "[]", LLoc); 12744 return ExprError(); 12745 12746 case OR_Deleted: 12747 Diag(LLoc, diag::err_ovl_deleted_oper) 12748 << Best->Function->isDeleted() << "[]" 12749 << getDeletedOrUnavailableSuffix(Best->Function) 12750 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12751 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12752 "[]", LLoc); 12753 return ExprError(); 12754 } 12755 12756 // We matched a built-in operator; build it. 12757 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12758 } 12759 12760 /// BuildCallToMemberFunction - Build a call to a member 12761 /// function. MemExpr is the expression that refers to the member 12762 /// function (and includes the object parameter), Args/NumArgs are the 12763 /// arguments to the function call (not including the object 12764 /// parameter). The caller needs to validate that the member 12765 /// expression refers to a non-static member function or an overloaded 12766 /// member function. 12767 ExprResult 12768 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12769 SourceLocation LParenLoc, 12770 MultiExprArg Args, 12771 SourceLocation RParenLoc) { 12772 assert(MemExprE->getType() == Context.BoundMemberTy || 12773 MemExprE->getType() == Context.OverloadTy); 12774 12775 // Dig out the member expression. This holds both the object 12776 // argument and the member function we're referring to. 12777 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12778 12779 // Determine whether this is a call to a pointer-to-member function. 12780 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12781 assert(op->getType() == Context.BoundMemberTy); 12782 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12783 12784 QualType fnType = 12785 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12786 12787 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12788 QualType resultType = proto->getCallResultType(Context); 12789 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12790 12791 // Check that the object type isn't more qualified than the 12792 // member function we're calling. 12793 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12794 12795 QualType objectType = op->getLHS()->getType(); 12796 if (op->getOpcode() == BO_PtrMemI) 12797 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12798 Qualifiers objectQuals = objectType.getQualifiers(); 12799 12800 Qualifiers difference = objectQuals - funcQuals; 12801 difference.removeObjCGCAttr(); 12802 difference.removeAddressSpace(); 12803 if (difference) { 12804 std::string qualsString = difference.getAsString(); 12805 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12806 << fnType.getUnqualifiedType() 12807 << qualsString 12808 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12809 } 12810 12811 CXXMemberCallExpr *call 12812 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12813 resultType, valueKind, RParenLoc); 12814 12815 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12816 call, nullptr)) 12817 return ExprError(); 12818 12819 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12820 return ExprError(); 12821 12822 if (CheckOtherCall(call, proto)) 12823 return ExprError(); 12824 12825 return MaybeBindToTemporary(call); 12826 } 12827 12828 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12829 return new (Context) 12830 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12831 12832 UnbridgedCastsSet UnbridgedCasts; 12833 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12834 return ExprError(); 12835 12836 MemberExpr *MemExpr; 12837 CXXMethodDecl *Method = nullptr; 12838 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12839 NestedNameSpecifier *Qualifier = nullptr; 12840 if (isa<MemberExpr>(NakedMemExpr)) { 12841 MemExpr = cast<MemberExpr>(NakedMemExpr); 12842 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12843 FoundDecl = MemExpr->getFoundDecl(); 12844 Qualifier = MemExpr->getQualifier(); 12845 UnbridgedCasts.restore(); 12846 } else { 12847 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12848 Qualifier = UnresExpr->getQualifier(); 12849 12850 QualType ObjectType = UnresExpr->getBaseType(); 12851 Expr::Classification ObjectClassification 12852 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12853 : UnresExpr->getBase()->Classify(Context); 12854 12855 // Add overload candidates 12856 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12857 OverloadCandidateSet::CSK_Normal); 12858 12859 // FIXME: avoid copy. 12860 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12861 if (UnresExpr->hasExplicitTemplateArgs()) { 12862 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12863 TemplateArgs = &TemplateArgsBuffer; 12864 } 12865 12866 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12867 E = UnresExpr->decls_end(); I != E; ++I) { 12868 12869 NamedDecl *Func = *I; 12870 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12871 if (isa<UsingShadowDecl>(Func)) 12872 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12873 12874 12875 // Microsoft supports direct constructor calls. 12876 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12877 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12878 Args, CandidateSet); 12879 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12880 // If explicit template arguments were provided, we can't call a 12881 // non-template member function. 12882 if (TemplateArgs) 12883 continue; 12884 12885 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12886 ObjectClassification, Args, CandidateSet, 12887 /*SuppressUserConversions=*/false); 12888 } else { 12889 AddMethodTemplateCandidate( 12890 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12891 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12892 /*SuppressUsedConversions=*/false); 12893 } 12894 } 12895 12896 DeclarationName DeclName = UnresExpr->getMemberName(); 12897 12898 UnbridgedCasts.restore(); 12899 12900 OverloadCandidateSet::iterator Best; 12901 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 12902 Best)) { 12903 case OR_Success: 12904 Method = cast<CXXMethodDecl>(Best->Function); 12905 FoundDecl = Best->FoundDecl; 12906 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12907 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12908 return ExprError(); 12909 // If FoundDecl is different from Method (such as if one is a template 12910 // and the other a specialization), make sure DiagnoseUseOfDecl is 12911 // called on both. 12912 // FIXME: This would be more comprehensively addressed by modifying 12913 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12914 // being used. 12915 if (Method != FoundDecl.getDecl() && 12916 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12917 return ExprError(); 12918 break; 12919 12920 case OR_No_Viable_Function: 12921 Diag(UnresExpr->getMemberLoc(), 12922 diag::err_ovl_no_viable_member_function_in_call) 12923 << DeclName << MemExprE->getSourceRange(); 12924 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12925 // FIXME: Leaking incoming expressions! 12926 return ExprError(); 12927 12928 case OR_Ambiguous: 12929 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12930 << DeclName << MemExprE->getSourceRange(); 12931 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12932 // FIXME: Leaking incoming expressions! 12933 return ExprError(); 12934 12935 case OR_Deleted: 12936 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12937 << Best->Function->isDeleted() 12938 << DeclName 12939 << getDeletedOrUnavailableSuffix(Best->Function) 12940 << MemExprE->getSourceRange(); 12941 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12942 // FIXME: Leaking incoming expressions! 12943 return ExprError(); 12944 } 12945 12946 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12947 12948 // If overload resolution picked a static member, build a 12949 // non-member call based on that function. 12950 if (Method->isStatic()) { 12951 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12952 RParenLoc); 12953 } 12954 12955 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12956 } 12957 12958 QualType ResultType = Method->getReturnType(); 12959 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12960 ResultType = ResultType.getNonLValueExprType(Context); 12961 12962 assert(Method && "Member call to something that isn't a method?"); 12963 CXXMemberCallExpr *TheCall = 12964 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12965 ResultType, VK, RParenLoc); 12966 12967 // Check for a valid return type. 12968 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12969 TheCall, Method)) 12970 return ExprError(); 12971 12972 // Convert the object argument (for a non-static member function call). 12973 // We only need to do this if there was actually an overload; otherwise 12974 // it was done at lookup. 12975 if (!Method->isStatic()) { 12976 ExprResult ObjectArg = 12977 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12978 FoundDecl, Method); 12979 if (ObjectArg.isInvalid()) 12980 return ExprError(); 12981 MemExpr->setBase(ObjectArg.get()); 12982 } 12983 12984 // Convert the rest of the arguments 12985 const FunctionProtoType *Proto = 12986 Method->getType()->getAs<FunctionProtoType>(); 12987 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12988 RParenLoc)) 12989 return ExprError(); 12990 12991 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12992 12993 if (CheckFunctionCall(Method, TheCall, Proto)) 12994 return ExprError(); 12995 12996 // In the case the method to call was not selected by the overloading 12997 // resolution process, we still need to handle the enable_if attribute. Do 12998 // that here, so it will not hide previous -- and more relevant -- errors. 12999 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13000 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13001 Diag(MemE->getMemberLoc(), 13002 diag::err_ovl_no_viable_member_function_in_call) 13003 << Method << Method->getSourceRange(); 13004 Diag(Method->getLocation(), 13005 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13006 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13007 return ExprError(); 13008 } 13009 } 13010 13011 if ((isa<CXXConstructorDecl>(CurContext) || 13012 isa<CXXDestructorDecl>(CurContext)) && 13013 TheCall->getMethodDecl()->isPure()) { 13014 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13015 13016 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13017 MemExpr->performsVirtualDispatch(getLangOpts())) { 13018 Diag(MemExpr->getBeginLoc(), 13019 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13020 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13021 << MD->getParent()->getDeclName(); 13022 13023 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13024 if (getLangOpts().AppleKext) 13025 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13026 << MD->getParent()->getDeclName() << MD->getDeclName(); 13027 } 13028 } 13029 13030 if (CXXDestructorDecl *DD = 13031 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13032 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13033 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13034 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13035 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13036 MemExpr->getMemberLoc()); 13037 } 13038 13039 return MaybeBindToTemporary(TheCall); 13040 } 13041 13042 /// BuildCallToObjectOfClassType - Build a call to an object of class 13043 /// type (C++ [over.call.object]), which can end up invoking an 13044 /// overloaded function call operator (@c operator()) or performing a 13045 /// user-defined conversion on the object argument. 13046 ExprResult 13047 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13048 SourceLocation LParenLoc, 13049 MultiExprArg Args, 13050 SourceLocation RParenLoc) { 13051 if (checkPlaceholderForOverload(*this, Obj)) 13052 return ExprError(); 13053 ExprResult Object = Obj; 13054 13055 UnbridgedCastsSet UnbridgedCasts; 13056 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13057 return ExprError(); 13058 13059 assert(Object.get()->getType()->isRecordType() && 13060 "Requires object type argument"); 13061 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13062 13063 // C++ [over.call.object]p1: 13064 // If the primary-expression E in the function call syntax 13065 // evaluates to a class object of type "cv T", then the set of 13066 // candidate functions includes at least the function call 13067 // operators of T. The function call operators of T are obtained by 13068 // ordinary lookup of the name operator() in the context of 13069 // (E).operator(). 13070 OverloadCandidateSet CandidateSet(LParenLoc, 13071 OverloadCandidateSet::CSK_Operator); 13072 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13073 13074 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13075 diag::err_incomplete_object_call, Object.get())) 13076 return true; 13077 13078 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13079 LookupQualifiedName(R, Record->getDecl()); 13080 R.suppressDiagnostics(); 13081 13082 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13083 Oper != OperEnd; ++Oper) { 13084 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13085 Object.get()->Classify(Context), Args, CandidateSet, 13086 /*SuppressUserConversions=*/false); 13087 } 13088 13089 // C++ [over.call.object]p2: 13090 // In addition, for each (non-explicit in C++0x) conversion function 13091 // declared in T of the form 13092 // 13093 // operator conversion-type-id () cv-qualifier; 13094 // 13095 // where cv-qualifier is the same cv-qualification as, or a 13096 // greater cv-qualification than, cv, and where conversion-type-id 13097 // denotes the type "pointer to function of (P1,...,Pn) returning 13098 // R", or the type "reference to pointer to function of 13099 // (P1,...,Pn) returning R", or the type "reference to function 13100 // of (P1,...,Pn) returning R", a surrogate call function [...] 13101 // is also considered as a candidate function. Similarly, 13102 // surrogate call functions are added to the set of candidate 13103 // functions for each conversion function declared in an 13104 // accessible base class provided the function is not hidden 13105 // within T by another intervening declaration. 13106 const auto &Conversions = 13107 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13108 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13109 NamedDecl *D = *I; 13110 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13111 if (isa<UsingShadowDecl>(D)) 13112 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13113 13114 // Skip over templated conversion functions; they aren't 13115 // surrogates. 13116 if (isa<FunctionTemplateDecl>(D)) 13117 continue; 13118 13119 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13120 if (!Conv->isExplicit()) { 13121 // Strip the reference type (if any) and then the pointer type (if 13122 // any) to get down to what might be a function type. 13123 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13124 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13125 ConvType = ConvPtrType->getPointeeType(); 13126 13127 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13128 { 13129 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13130 Object.get(), Args, CandidateSet); 13131 } 13132 } 13133 } 13134 13135 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13136 13137 // Perform overload resolution. 13138 OverloadCandidateSet::iterator Best; 13139 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13140 Best)) { 13141 case OR_Success: 13142 // Overload resolution succeeded; we'll build the appropriate call 13143 // below. 13144 break; 13145 13146 case OR_No_Viable_Function: 13147 if (CandidateSet.empty()) 13148 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper) 13149 << Object.get()->getType() << /*call*/ 1 13150 << Object.get()->getSourceRange(); 13151 else 13152 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call) 13153 << Object.get()->getType() << Object.get()->getSourceRange(); 13154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13155 break; 13156 13157 case OR_Ambiguous: 13158 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call) 13159 << Object.get()->getType() << Object.get()->getSourceRange(); 13160 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13161 break; 13162 13163 case OR_Deleted: 13164 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call) 13165 << Best->Function->isDeleted() << Object.get()->getType() 13166 << getDeletedOrUnavailableSuffix(Best->Function) 13167 << Object.get()->getSourceRange(); 13168 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13169 break; 13170 } 13171 13172 if (Best == CandidateSet.end()) 13173 return true; 13174 13175 UnbridgedCasts.restore(); 13176 13177 if (Best->Function == nullptr) { 13178 // Since there is no function declaration, this is one of the 13179 // surrogate candidates. Dig out the conversion function. 13180 CXXConversionDecl *Conv 13181 = cast<CXXConversionDecl>( 13182 Best->Conversions[0].UserDefined.ConversionFunction); 13183 13184 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13185 Best->FoundDecl); 13186 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13187 return ExprError(); 13188 assert(Conv == Best->FoundDecl.getDecl() && 13189 "Found Decl & conversion-to-functionptr should be same, right?!"); 13190 // We selected one of the surrogate functions that converts the 13191 // object parameter to a function pointer. Perform the conversion 13192 // on the object argument, then let ActOnCallExpr finish the job. 13193 13194 // Create an implicit member expr to refer to the conversion operator. 13195 // and then call it. 13196 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13197 Conv, HadMultipleCandidates); 13198 if (Call.isInvalid()) 13199 return ExprError(); 13200 // Record usage of conversion in an implicit cast. 13201 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13202 CK_UserDefinedConversion, Call.get(), 13203 nullptr, VK_RValue); 13204 13205 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13206 } 13207 13208 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13209 13210 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13211 // that calls this method, using Object for the implicit object 13212 // parameter and passing along the remaining arguments. 13213 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13214 13215 // An error diagnostic has already been printed when parsing the declaration. 13216 if (Method->isInvalidDecl()) 13217 return ExprError(); 13218 13219 const FunctionProtoType *Proto = 13220 Method->getType()->getAs<FunctionProtoType>(); 13221 13222 unsigned NumParams = Proto->getNumParams(); 13223 13224 DeclarationNameInfo OpLocInfo( 13225 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13226 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13227 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13228 Obj, HadMultipleCandidates, 13229 OpLocInfo.getLoc(), 13230 OpLocInfo.getInfo()); 13231 if (NewFn.isInvalid()) 13232 return true; 13233 13234 // Build the full argument list for the method call (the implicit object 13235 // parameter is placed at the beginning of the list). 13236 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13237 MethodArgs[0] = Object.get(); 13238 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13239 13240 // Once we've built TheCall, all of the expressions are properly 13241 // owned. 13242 QualType ResultTy = Method->getReturnType(); 13243 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13244 ResultTy = ResultTy.getNonLValueExprType(Context); 13245 13246 CXXOperatorCallExpr *TheCall = new (Context) 13247 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13248 VK, RParenLoc, FPOptions()); 13249 13250 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13251 return true; 13252 13253 // We may have default arguments. If so, we need to allocate more 13254 // slots in the call for them. 13255 if (Args.size() < NumParams) 13256 TheCall->setNumArgs(Context, NumParams + 1); 13257 13258 bool IsError = false; 13259 13260 // Initialize the implicit object parameter. 13261 ExprResult ObjRes = 13262 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13263 Best->FoundDecl, Method); 13264 if (ObjRes.isInvalid()) 13265 IsError = true; 13266 else 13267 Object = ObjRes; 13268 TheCall->setArg(0, Object.get()); 13269 13270 // Check the argument types. 13271 for (unsigned i = 0; i != NumParams; i++) { 13272 Expr *Arg; 13273 if (i < Args.size()) { 13274 Arg = Args[i]; 13275 13276 // Pass the argument. 13277 13278 ExprResult InputInit 13279 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13280 Context, 13281 Method->getParamDecl(i)), 13282 SourceLocation(), Arg); 13283 13284 IsError |= InputInit.isInvalid(); 13285 Arg = InputInit.getAs<Expr>(); 13286 } else { 13287 ExprResult DefArg 13288 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13289 if (DefArg.isInvalid()) { 13290 IsError = true; 13291 break; 13292 } 13293 13294 Arg = DefArg.getAs<Expr>(); 13295 } 13296 13297 TheCall->setArg(i + 1, Arg); 13298 } 13299 13300 // If this is a variadic call, handle args passed through "...". 13301 if (Proto->isVariadic()) { 13302 // Promote the arguments (C99 6.5.2.2p7). 13303 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13304 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13305 nullptr); 13306 IsError |= Arg.isInvalid(); 13307 TheCall->setArg(i + 1, Arg.get()); 13308 } 13309 } 13310 13311 if (IsError) return true; 13312 13313 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13314 13315 if (CheckFunctionCall(Method, TheCall, Proto)) 13316 return true; 13317 13318 return MaybeBindToTemporary(TheCall); 13319 } 13320 13321 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13322 /// (if one exists), where @c Base is an expression of class type and 13323 /// @c Member is the name of the member we're trying to find. 13324 ExprResult 13325 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13326 bool *NoArrowOperatorFound) { 13327 assert(Base->getType()->isRecordType() && 13328 "left-hand side must have class type"); 13329 13330 if (checkPlaceholderForOverload(*this, Base)) 13331 return ExprError(); 13332 13333 SourceLocation Loc = Base->getExprLoc(); 13334 13335 // C++ [over.ref]p1: 13336 // 13337 // [...] An expression x->m is interpreted as (x.operator->())->m 13338 // for a class object x of type T if T::operator->() exists and if 13339 // the operator is selected as the best match function by the 13340 // overload resolution mechanism (13.3). 13341 DeclarationName OpName = 13342 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13343 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13344 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13345 13346 if (RequireCompleteType(Loc, Base->getType(), 13347 diag::err_typecheck_incomplete_tag, Base)) 13348 return ExprError(); 13349 13350 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13351 LookupQualifiedName(R, BaseRecord->getDecl()); 13352 R.suppressDiagnostics(); 13353 13354 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13355 Oper != OperEnd; ++Oper) { 13356 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13357 None, CandidateSet, /*SuppressUserConversions=*/false); 13358 } 13359 13360 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13361 13362 // Perform overload resolution. 13363 OverloadCandidateSet::iterator Best; 13364 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13365 case OR_Success: 13366 // Overload resolution succeeded; we'll build the call below. 13367 break; 13368 13369 case OR_No_Viable_Function: 13370 if (CandidateSet.empty()) { 13371 QualType BaseType = Base->getType(); 13372 if (NoArrowOperatorFound) { 13373 // Report this specific error to the caller instead of emitting a 13374 // diagnostic, as requested. 13375 *NoArrowOperatorFound = true; 13376 return ExprError(); 13377 } 13378 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13379 << BaseType << Base->getSourceRange(); 13380 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13381 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13382 << FixItHint::CreateReplacement(OpLoc, "."); 13383 } 13384 } else 13385 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13386 << "operator->" << Base->getSourceRange(); 13387 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13388 return ExprError(); 13389 13390 case OR_Ambiguous: 13391 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13392 << "->" << Base->getType() << Base->getSourceRange(); 13393 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13394 return ExprError(); 13395 13396 case OR_Deleted: 13397 Diag(OpLoc, diag::err_ovl_deleted_oper) 13398 << Best->Function->isDeleted() 13399 << "->" 13400 << getDeletedOrUnavailableSuffix(Best->Function) 13401 << Base->getSourceRange(); 13402 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13403 return ExprError(); 13404 } 13405 13406 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13407 13408 // Convert the object parameter. 13409 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13410 ExprResult BaseResult = 13411 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13412 Best->FoundDecl, Method); 13413 if (BaseResult.isInvalid()) 13414 return ExprError(); 13415 Base = BaseResult.get(); 13416 13417 // Build the operator call. 13418 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13419 Base, HadMultipleCandidates, OpLoc); 13420 if (FnExpr.isInvalid()) 13421 return ExprError(); 13422 13423 QualType ResultTy = Method->getReturnType(); 13424 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13425 ResultTy = ResultTy.getNonLValueExprType(Context); 13426 CXXOperatorCallExpr *TheCall = 13427 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13428 Base, ResultTy, VK, OpLoc, FPOptions()); 13429 13430 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13431 return ExprError(); 13432 13433 if (CheckFunctionCall(Method, TheCall, 13434 Method->getType()->castAs<FunctionProtoType>())) 13435 return ExprError(); 13436 13437 return MaybeBindToTemporary(TheCall); 13438 } 13439 13440 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13441 /// a literal operator described by the provided lookup results. 13442 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13443 DeclarationNameInfo &SuffixInfo, 13444 ArrayRef<Expr*> Args, 13445 SourceLocation LitEndLoc, 13446 TemplateArgumentListInfo *TemplateArgs) { 13447 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13448 13449 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13450 OverloadCandidateSet::CSK_Normal); 13451 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13452 /*SuppressUserConversions=*/true); 13453 13454 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13455 13456 // Perform overload resolution. This will usually be trivial, but might need 13457 // to perform substitutions for a literal operator template. 13458 OverloadCandidateSet::iterator Best; 13459 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13460 case OR_Success: 13461 case OR_Deleted: 13462 break; 13463 13464 case OR_No_Viable_Function: 13465 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13466 << R.getLookupName(); 13467 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13468 return ExprError(); 13469 13470 case OR_Ambiguous: 13471 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13472 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13473 return ExprError(); 13474 } 13475 13476 FunctionDecl *FD = Best->Function; 13477 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13478 nullptr, HadMultipleCandidates, 13479 SuffixInfo.getLoc(), 13480 SuffixInfo.getInfo()); 13481 if (Fn.isInvalid()) 13482 return true; 13483 13484 // Check the argument types. This should almost always be a no-op, except 13485 // that array-to-pointer decay is applied to string literals. 13486 Expr *ConvArgs[2]; 13487 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13488 ExprResult InputInit = PerformCopyInitialization( 13489 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13490 SourceLocation(), Args[ArgIdx]); 13491 if (InputInit.isInvalid()) 13492 return true; 13493 ConvArgs[ArgIdx] = InputInit.get(); 13494 } 13495 13496 QualType ResultTy = FD->getReturnType(); 13497 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13498 ResultTy = ResultTy.getNonLValueExprType(Context); 13499 13500 UserDefinedLiteral *UDL = 13501 new (Context) UserDefinedLiteral(Context, Fn.get(), 13502 llvm::makeArrayRef(ConvArgs, Args.size()), 13503 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13504 13505 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13506 return ExprError(); 13507 13508 if (CheckFunctionCall(FD, UDL, nullptr)) 13509 return ExprError(); 13510 13511 return MaybeBindToTemporary(UDL); 13512 } 13513 13514 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13515 /// given LookupResult is non-empty, it is assumed to describe a member which 13516 /// will be invoked. Otherwise, the function will be found via argument 13517 /// dependent lookup. 13518 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13519 /// otherwise CallExpr is set to ExprError() and some non-success value 13520 /// is returned. 13521 Sema::ForRangeStatus 13522 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13523 SourceLocation RangeLoc, 13524 const DeclarationNameInfo &NameInfo, 13525 LookupResult &MemberLookup, 13526 OverloadCandidateSet *CandidateSet, 13527 Expr *Range, ExprResult *CallExpr) { 13528 Scope *S = nullptr; 13529 13530 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13531 if (!MemberLookup.empty()) { 13532 ExprResult MemberRef = 13533 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13534 /*IsPtr=*/false, CXXScopeSpec(), 13535 /*TemplateKWLoc=*/SourceLocation(), 13536 /*FirstQualifierInScope=*/nullptr, 13537 MemberLookup, 13538 /*TemplateArgs=*/nullptr, S); 13539 if (MemberRef.isInvalid()) { 13540 *CallExpr = ExprError(); 13541 return FRS_DiagnosticIssued; 13542 } 13543 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13544 if (CallExpr->isInvalid()) { 13545 *CallExpr = ExprError(); 13546 return FRS_DiagnosticIssued; 13547 } 13548 } else { 13549 UnresolvedSet<0> FoundNames; 13550 UnresolvedLookupExpr *Fn = 13551 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13552 NestedNameSpecifierLoc(), NameInfo, 13553 /*NeedsADL=*/true, /*Overloaded=*/false, 13554 FoundNames.begin(), FoundNames.end()); 13555 13556 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13557 CandidateSet, CallExpr); 13558 if (CandidateSet->empty() || CandidateSetError) { 13559 *CallExpr = ExprError(); 13560 return FRS_NoViableFunction; 13561 } 13562 OverloadCandidateSet::iterator Best; 13563 OverloadingResult OverloadResult = 13564 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13565 13566 if (OverloadResult == OR_No_Viable_Function) { 13567 *CallExpr = ExprError(); 13568 return FRS_NoViableFunction; 13569 } 13570 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13571 Loc, nullptr, CandidateSet, &Best, 13572 OverloadResult, 13573 /*AllowTypoCorrection=*/false); 13574 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13575 *CallExpr = ExprError(); 13576 return FRS_DiagnosticIssued; 13577 } 13578 } 13579 return FRS_Success; 13580 } 13581 13582 13583 /// FixOverloadedFunctionReference - E is an expression that refers to 13584 /// a C++ overloaded function (possibly with some parentheses and 13585 /// perhaps a '&' around it). We have resolved the overloaded function 13586 /// to the function declaration Fn, so patch up the expression E to 13587 /// refer (possibly indirectly) to Fn. Returns the new expr. 13588 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13589 FunctionDecl *Fn) { 13590 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13591 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13592 Found, Fn); 13593 if (SubExpr == PE->getSubExpr()) 13594 return PE; 13595 13596 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13597 } 13598 13599 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13600 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13601 Found, Fn); 13602 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13603 SubExpr->getType()) && 13604 "Implicit cast type cannot be determined from overload"); 13605 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13606 if (SubExpr == ICE->getSubExpr()) 13607 return ICE; 13608 13609 return ImplicitCastExpr::Create(Context, ICE->getType(), 13610 ICE->getCastKind(), 13611 SubExpr, nullptr, 13612 ICE->getValueKind()); 13613 } 13614 13615 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13616 if (!GSE->isResultDependent()) { 13617 Expr *SubExpr = 13618 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13619 if (SubExpr == GSE->getResultExpr()) 13620 return GSE; 13621 13622 // Replace the resulting type information before rebuilding the generic 13623 // selection expression. 13624 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13625 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13626 unsigned ResultIdx = GSE->getResultIndex(); 13627 AssocExprs[ResultIdx] = SubExpr; 13628 13629 return new (Context) GenericSelectionExpr( 13630 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13631 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13632 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13633 ResultIdx); 13634 } 13635 // Rather than fall through to the unreachable, return the original generic 13636 // selection expression. 13637 return GSE; 13638 } 13639 13640 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13641 assert(UnOp->getOpcode() == UO_AddrOf && 13642 "Can only take the address of an overloaded function"); 13643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13644 if (Method->isStatic()) { 13645 // Do nothing: static member functions aren't any different 13646 // from non-member functions. 13647 } else { 13648 // Fix the subexpression, which really has to be an 13649 // UnresolvedLookupExpr holding an overloaded member function 13650 // or template. 13651 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13652 Found, Fn); 13653 if (SubExpr == UnOp->getSubExpr()) 13654 return UnOp; 13655 13656 assert(isa<DeclRefExpr>(SubExpr) 13657 && "fixed to something other than a decl ref"); 13658 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13659 && "fixed to a member ref with no nested name qualifier"); 13660 13661 // We have taken the address of a pointer to member 13662 // function. Perform the computation here so that we get the 13663 // appropriate pointer to member type. 13664 QualType ClassType 13665 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13666 QualType MemPtrType 13667 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13668 // Under the MS ABI, lock down the inheritance model now. 13669 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13670 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13671 13672 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13673 VK_RValue, OK_Ordinary, 13674 UnOp->getOperatorLoc(), false); 13675 } 13676 } 13677 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13678 Found, Fn); 13679 if (SubExpr == UnOp->getSubExpr()) 13680 return UnOp; 13681 13682 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13683 Context.getPointerType(SubExpr->getType()), 13684 VK_RValue, OK_Ordinary, 13685 UnOp->getOperatorLoc(), false); 13686 } 13687 13688 // C++ [except.spec]p17: 13689 // An exception-specification is considered to be needed when: 13690 // - in an expression the function is the unique lookup result or the 13691 // selected member of a set of overloaded functions 13692 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13693 ResolveExceptionSpec(E->getExprLoc(), FPT); 13694 13695 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13696 // FIXME: avoid copy. 13697 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13698 if (ULE->hasExplicitTemplateArgs()) { 13699 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13700 TemplateArgs = &TemplateArgsBuffer; 13701 } 13702 13703 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13704 ULE->getQualifierLoc(), 13705 ULE->getTemplateKeywordLoc(), 13706 Fn, 13707 /*enclosing*/ false, // FIXME? 13708 ULE->getNameLoc(), 13709 Fn->getType(), 13710 VK_LValue, 13711 Found.getDecl(), 13712 TemplateArgs); 13713 MarkDeclRefReferenced(DRE); 13714 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13715 return DRE; 13716 } 13717 13718 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13719 // FIXME: avoid copy. 13720 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13721 if (MemExpr->hasExplicitTemplateArgs()) { 13722 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13723 TemplateArgs = &TemplateArgsBuffer; 13724 } 13725 13726 Expr *Base; 13727 13728 // If we're filling in a static method where we used to have an 13729 // implicit member access, rewrite to a simple decl ref. 13730 if (MemExpr->isImplicitAccess()) { 13731 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13732 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13733 MemExpr->getQualifierLoc(), 13734 MemExpr->getTemplateKeywordLoc(), 13735 Fn, 13736 /*enclosing*/ false, 13737 MemExpr->getMemberLoc(), 13738 Fn->getType(), 13739 VK_LValue, 13740 Found.getDecl(), 13741 TemplateArgs); 13742 MarkDeclRefReferenced(DRE); 13743 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13744 return DRE; 13745 } else { 13746 SourceLocation Loc = MemExpr->getMemberLoc(); 13747 if (MemExpr->getQualifier()) 13748 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13749 CheckCXXThisCapture(Loc); 13750 Base = new (Context) CXXThisExpr(Loc, 13751 MemExpr->getBaseType(), 13752 /*isImplicit=*/true); 13753 } 13754 } else 13755 Base = MemExpr->getBase(); 13756 13757 ExprValueKind valueKind; 13758 QualType type; 13759 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13760 valueKind = VK_LValue; 13761 type = Fn->getType(); 13762 } else { 13763 valueKind = VK_RValue; 13764 type = Context.BoundMemberTy; 13765 } 13766 13767 MemberExpr *ME = MemberExpr::Create( 13768 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13769 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13770 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13771 OK_Ordinary); 13772 ME->setHadMultipleCandidates(true); 13773 MarkMemberReferenced(ME); 13774 return ME; 13775 } 13776 13777 llvm_unreachable("Invalid reference to overloaded function"); 13778 } 13779 13780 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13781 DeclAccessPair Found, 13782 FunctionDecl *Fn) { 13783 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13784 } 13785