1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult 53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 54 const Expr *Base, bool HadMultipleCandidates, 55 SourceLocation Loc = SourceLocation(), 56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 58 return ExprError(); 59 // If FoundDecl is different from Fn (such as if one is a template 60 // and the other a specialization), make sure DiagnoseUseOfDecl is 61 // called on both. 62 // FIXME: This would be more comprehensively addressed by modifying 63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 64 // being used. 65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 66 return ExprError(); 67 DeclRefExpr *DRE = new (S.Context) 68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 69 if (HadMultipleCandidates) 70 DRE->setHadMultipleCandidates(true); 71 72 S.MarkDeclRefReferenced(DRE, Base); 73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 75 S.ResolveExceptionSpec(Loc, FPT); 76 DRE->setType(Fn->getType()); 77 } 78 } 79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 80 CK_FunctionToPointerDecay); 81 } 82 83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle, 87 bool AllowObjCWritebackConversion); 88 89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 90 QualType &ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle); 94 static OverloadingResult 95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 96 UserDefinedConversionSequence& User, 97 OverloadCandidateSet& Conversions, 98 AllowedExplicit AllowExplicit, 99 bool AllowObjCConversionOnExplicit); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 static ImplicitConversionSequence::CompareKind 107 CompareQualificationConversions(Sema &S, 108 const StandardConversionSequence& SCS1, 109 const StandardConversionSequence& SCS2); 110 111 static ImplicitConversionSequence::CompareKind 112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 113 const StandardConversionSequence& SCS1, 114 const StandardConversionSequence& SCS2); 115 116 /// GetConversionRank - Retrieve the implicit conversion rank 117 /// corresponding to the given implicit conversion kind. 118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 119 static const ImplicitConversionRank 120 Rank[(int)ICK_Num_Conversion_Kinds] = { 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Exact_Match, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Promotion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_OCL_Scalar_Widening, 142 ICR_Complex_Real_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Writeback_Conversion, 146 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 147 // it was omitted by the patch that added 148 // ICK_Zero_Event_Conversion 149 ICR_C_Conversion, 150 ICR_C_Conversion_Extension 151 }; 152 return Rank[(int)Kind]; 153 } 154 155 /// GetImplicitConversionName - Return the name of this kind of 156 /// implicit conversion. 157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Function pointer conversion", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "SVE Vector conversion", 179 "Vector splat", 180 "Complex-real conversion", 181 "Block Pointer conversion", 182 "Transparent Union Conversion", 183 "Writeback conversion", 184 "OpenCL Zero Event Conversion", 185 "C specific type conversion", 186 "Incompatible pointer conversion" 187 }; 188 return Name[Kind]; 189 } 190 191 /// StandardConversionSequence - Set the standard conversion 192 /// sequence to the identity conversion. 193 void StandardConversionSequence::setAsIdentityConversion() { 194 First = ICK_Identity; 195 Second = ICK_Identity; 196 Third = ICK_Identity; 197 DeprecatedStringLiteralToCharPtr = false; 198 QualificationIncludesObjCLifetime = false; 199 ReferenceBinding = false; 200 DirectBinding = false; 201 IsLvalueReference = true; 202 BindsToFunctionLvalue = false; 203 BindsToRvalue = false; 204 BindsImplicitObjectArgumentWithoutRefQualifier = false; 205 ObjCLifetimeConversionBinding = false; 206 CopyConstructor = nullptr; 207 } 208 209 /// getRank - Retrieve the rank of this standard conversion sequence 210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 211 /// implicit conversions. 212 ImplicitConversionRank StandardConversionSequence::getRank() const { 213 ImplicitConversionRank Rank = ICR_Exact_Match; 214 if (GetConversionRank(First) > Rank) 215 Rank = GetConversionRank(First); 216 if (GetConversionRank(Second) > Rank) 217 Rank = GetConversionRank(Second); 218 if (GetConversionRank(Third) > Rank) 219 Rank = GetConversionRank(Third); 220 return Rank; 221 } 222 223 /// isPointerConversionToBool - Determines whether this conversion is 224 /// a conversion of a pointer or pointer-to-member to bool. This is 225 /// used as part of the ranking of standard conversion sequences 226 /// (C++ 13.3.3.2p4). 227 bool StandardConversionSequence::isPointerConversionToBool() const { 228 // Note that FromType has not necessarily been transformed by the 229 // array-to-pointer or function-to-pointer implicit conversions, so 230 // check for their presence as well as checking whether FromType is 231 // a pointer. 232 if (getToType(1)->isBooleanType() && 233 (getFromType()->isPointerType() || 234 getFromType()->isMemberPointerType() || 235 getFromType()->isObjCObjectPointerType() || 236 getFromType()->isBlockPointerType() || 237 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 238 return true; 239 240 return false; 241 } 242 243 /// isPointerConversionToVoidPointer - Determines whether this 244 /// conversion is a conversion of a pointer to a void pointer. This is 245 /// used as part of the ranking of standard conversion sequences (C++ 246 /// 13.3.3.2p4). 247 bool 248 StandardConversionSequence:: 249 isPointerConversionToVoidPointer(ASTContext& Context) const { 250 QualType FromType = getFromType(); 251 QualType ToType = getToType(1); 252 253 // Note that FromType has not necessarily been transformed by the 254 // array-to-pointer implicit conversion, so check for its presence 255 // and redo the conversion to get a pointer. 256 if (First == ICK_Array_To_Pointer) 257 FromType = Context.getArrayDecayedType(FromType); 258 259 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 260 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 261 return ToPtrType->getPointeeType()->isVoidType(); 262 263 return false; 264 } 265 266 /// Skip any implicit casts which could be either part of a narrowing conversion 267 /// or after one in an implicit conversion. 268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 269 const Expr *Converted) { 270 // We can have cleanups wrapping the converted expression; these need to be 271 // preserved so that destructors run if necessary. 272 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 273 Expr *Inner = 274 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 275 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 276 EWC->getObjects()); 277 } 278 279 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_BooleanToSignedIntegral: 286 case CK_FloatingToIntegral: 287 case CK_FloatingToBoolean: 288 case CK_FloatingCast: 289 Converted = ICE->getSubExpr(); 290 continue; 291 292 default: 293 return Converted; 294 } 295 } 296 297 return Converted; 298 } 299 300 /// Check if this standard conversion sequence represents a narrowing 301 /// conversion, according to C++11 [dcl.init.list]p7. 302 /// 303 /// \param Ctx The AST context. 304 /// \param Converted The result of applying this standard conversion sequence. 305 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 306 /// value of the expression prior to the narrowing conversion. 307 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 308 /// type of the expression prior to the narrowing conversion. 309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 310 /// from floating point types to integral types should be ignored. 311 NarrowingKind StandardConversionSequence::getNarrowingKind( 312 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 313 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 315 316 // C++11 [dcl.init.list]p7: 317 // A narrowing conversion is an implicit conversion ... 318 QualType FromType = getToType(0); 319 QualType ToType = getToType(1); 320 321 // A conversion to an enumeration type is narrowing if the conversion to 322 // the underlying type is narrowing. This only arises for expressions of 323 // the form 'Enum{init}'. 324 if (auto *ET = ToType->getAs<EnumType>()) 325 ToType = ET->getDecl()->getIntegerType(); 326 327 switch (Second) { 328 // 'bool' is an integral type; dispatch to the right place to handle it. 329 case ICK_Boolean_Conversion: 330 if (FromType->isRealFloatingType()) 331 goto FloatingIntegralConversion; 332 if (FromType->isIntegralOrUnscopedEnumerationType()) 333 goto IntegralConversion; 334 // -- from a pointer type or pointer-to-member type to bool, or 335 return NK_Type_Narrowing; 336 337 // -- from a floating-point type to an integer type, or 338 // 339 // -- from an integer type or unscoped enumeration type to a floating-point 340 // type, except where the source is a constant expression and the actual 341 // value after conversion will fit into the target type and will produce 342 // the original value when converted back to the original type, or 343 case ICK_Floating_Integral: 344 FloatingIntegralConversion: 345 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 346 return NK_Type_Narrowing; 347 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 348 ToType->isRealFloatingType()) { 349 if (IgnoreFloatToIntegralConversion) 350 return NK_Not_Narrowing; 351 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 352 assert(Initializer && "Unknown conversion expression"); 353 354 // If it's value-dependent, we can't tell whether it's narrowing. 355 if (Initializer->isValueDependent()) 356 return NK_Dependent_Narrowing; 357 358 if (Optional<llvm::APSInt> IntConstantValue = 359 Initializer->getIntegerConstantExpr(Ctx)) { 360 // Convert the integer to the floating type. 361 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 362 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 363 llvm::APFloat::rmNearestTiesToEven); 364 // And back. 365 llvm::APSInt ConvertedValue = *IntConstantValue; 366 bool ignored; 367 Result.convertToInteger(ConvertedValue, 368 llvm::APFloat::rmTowardZero, &ignored); 369 // If the resulting value is different, this was a narrowing conversion. 370 if (*IntConstantValue != ConvertedValue) { 371 ConstantValue = APValue(*IntConstantValue); 372 ConstantType = Initializer->getType(); 373 return NK_Constant_Narrowing; 374 } 375 } else { 376 // Variables are always narrowings. 377 return NK_Variable_Narrowing; 378 } 379 } 380 return NK_Not_Narrowing; 381 382 // -- from long double to double or float, or from double to float, except 383 // where the source is a constant expression and the actual value after 384 // conversion is within the range of values that can be represented (even 385 // if it cannot be represented exactly), or 386 case ICK_Floating_Conversion: 387 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 388 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 389 // FromType is larger than ToType. 390 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 391 392 // If it's value-dependent, we can't tell whether it's narrowing. 393 if (Initializer->isValueDependent()) 394 return NK_Dependent_Narrowing; 395 396 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 397 // Constant! 398 assert(ConstantValue.isFloat()); 399 llvm::APFloat FloatVal = ConstantValue.getFloat(); 400 // Convert the source value into the target type. 401 bool ignored; 402 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 403 Ctx.getFloatTypeSemantics(ToType), 404 llvm::APFloat::rmNearestTiesToEven, &ignored); 405 // If there was no overflow, the source value is within the range of 406 // values that can be represented. 407 if (ConvertStatus & llvm::APFloat::opOverflow) { 408 ConstantType = Initializer->getType(); 409 return NK_Constant_Narrowing; 410 } 411 } else { 412 return NK_Variable_Narrowing; 413 } 414 } 415 return NK_Not_Narrowing; 416 417 // -- from an integer type or unscoped enumeration type to an integer type 418 // that cannot represent all the values of the original type, except where 419 // the source is a constant expression and the actual value after 420 // conversion will fit into the target type and will produce the original 421 // value when converted back to the original type. 422 case ICK_Integral_Conversion: 423 IntegralConversion: { 424 assert(FromType->isIntegralOrUnscopedEnumerationType()); 425 assert(ToType->isIntegralOrUnscopedEnumerationType()); 426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 427 const unsigned FromWidth = Ctx.getIntWidth(FromType); 428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 429 const unsigned ToWidth = Ctx.getIntWidth(ToType); 430 431 if (FromWidth > ToWidth || 432 (FromWidth == ToWidth && FromSigned != ToSigned) || 433 (FromSigned && !ToSigned)) { 434 // Not all values of FromType can be represented in ToType. 435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 436 437 // If it's value-dependent, we can't tell whether it's narrowing. 438 if (Initializer->isValueDependent()) 439 return NK_Dependent_Narrowing; 440 441 Optional<llvm::APSInt> OptInitializerValue; 442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 443 // Such conversions on variables are always narrowing. 444 return NK_Variable_Narrowing; 445 } 446 llvm::APSInt &InitializerValue = *OptInitializerValue; 447 bool Narrowing = false; 448 if (FromWidth < ToWidth) { 449 // Negative -> unsigned is narrowing. Otherwise, more bits is never 450 // narrowing. 451 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 452 Narrowing = true; 453 } else { 454 // Add a bit to the InitializerValue so we don't have to worry about 455 // signed vs. unsigned comparisons. 456 InitializerValue = InitializerValue.extend( 457 InitializerValue.getBitWidth() + 1); 458 // Convert the initializer to and from the target width and signed-ness. 459 llvm::APSInt ConvertedValue = InitializerValue; 460 ConvertedValue = ConvertedValue.trunc(ToWidth); 461 ConvertedValue.setIsSigned(ToSigned); 462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 463 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 464 // If the result is different, this was a narrowing conversion. 465 if (ConvertedValue != InitializerValue) 466 Narrowing = true; 467 } 468 if (Narrowing) { 469 ConstantType = Initializer->getType(); 470 ConstantValue = APValue(InitializerValue); 471 return NK_Constant_Narrowing; 472 } 473 } 474 return NK_Not_Narrowing; 475 } 476 477 default: 478 // Other kinds of conversions are not narrowings. 479 return NK_Not_Narrowing; 480 } 481 } 482 483 /// dump - Print this standard conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 bool PrintedSomething = false; 488 if (First != ICK_Identity) { 489 OS << GetImplicitConversionName(First); 490 PrintedSomething = true; 491 } 492 493 if (Second != ICK_Identity) { 494 if (PrintedSomething) { 495 OS << " -> "; 496 } 497 OS << GetImplicitConversionName(Second); 498 499 if (CopyConstructor) { 500 OS << " (by copy constructor)"; 501 } else if (DirectBinding) { 502 OS << " (direct reference binding)"; 503 } else if (ReferenceBinding) { 504 OS << " (reference binding)"; 505 } 506 PrintedSomething = true; 507 } 508 509 if (Third != ICK_Identity) { 510 if (PrintedSomething) { 511 OS << " -> "; 512 } 513 OS << GetImplicitConversionName(Third); 514 PrintedSomething = true; 515 } 516 517 if (!PrintedSomething) { 518 OS << "No conversions required"; 519 } 520 } 521 522 /// dump - Print this user-defined conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void UserDefinedConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (Before.First || Before.Second || Before.Third) { 527 Before.dump(); 528 OS << " -> "; 529 } 530 if (ConversionFunction) 531 OS << '\'' << *ConversionFunction << '\''; 532 else 533 OS << "aggregate initialization"; 534 if (After.First || After.Second || After.Third) { 535 OS << " -> "; 536 After.dump(); 537 } 538 } 539 540 /// dump - Print this implicit conversion sequence to standard 541 /// error. Useful for debugging overloading issues. 542 void ImplicitConversionSequence::dump() const { 543 raw_ostream &OS = llvm::errs(); 544 if (isStdInitializerListElement()) 545 OS << "Worst std::initializer_list element conversion: "; 546 switch (ConversionKind) { 547 case StandardConversion: 548 OS << "Standard conversion: "; 549 Standard.dump(); 550 break; 551 case UserDefinedConversion: 552 OS << "User-defined conversion: "; 553 UserDefined.dump(); 554 break; 555 case EllipsisConversion: 556 OS << "Ellipsis conversion"; 557 break; 558 case AmbiguousConversion: 559 OS << "Ambiguous conversion"; 560 break; 561 case BadConversion: 562 OS << "Bad conversion"; 563 break; 564 } 565 566 OS << "\n"; 567 } 568 569 void AmbiguousConversionSequence::construct() { 570 new (&conversions()) ConversionSet(); 571 } 572 573 void AmbiguousConversionSequence::destruct() { 574 conversions().~ConversionSet(); 575 } 576 577 void 578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 579 FromTypePtr = O.FromTypePtr; 580 ToTypePtr = O.ToTypePtr; 581 new (&conversions()) ConversionSet(O.conversions()); 582 } 583 584 namespace { 585 // Structure used by DeductionFailureInfo to store 586 // template argument information. 587 struct DFIArguments { 588 TemplateArgument FirstArg; 589 TemplateArgument SecondArg; 590 }; 591 // Structure used by DeductionFailureInfo to store 592 // template parameter and template argument information. 593 struct DFIParamWithArguments : DFIArguments { 594 TemplateParameter Param; 595 }; 596 // Structure used by DeductionFailureInfo to store template argument 597 // information and the index of the problematic call argument. 598 struct DFIDeducedMismatchArgs : DFIArguments { 599 TemplateArgumentList *TemplateArgs; 600 unsigned CallArgIndex; 601 }; 602 // Structure used by DeductionFailureInfo to store information about 603 // unsatisfied constraints. 604 struct CNSInfo { 605 TemplateArgumentList *TemplateArgs; 606 ConstraintSatisfaction Satisfaction; 607 }; 608 } 609 610 /// Convert from Sema's representation of template deduction information 611 /// to the form used in overload-candidate information. 612 DeductionFailureInfo 613 clang::MakeDeductionFailureInfo(ASTContext &Context, 614 Sema::TemplateDeductionResult TDK, 615 TemplateDeductionInfo &Info) { 616 DeductionFailureInfo Result; 617 Result.Result = static_cast<unsigned>(TDK); 618 Result.HasDiagnostic = false; 619 switch (TDK) { 620 case Sema::TDK_Invalid: 621 case Sema::TDK_InstantiationDepth: 622 case Sema::TDK_TooManyArguments: 623 case Sema::TDK_TooFewArguments: 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 case Sema::TDK_CUDATargetMismatch: 626 Result.Data = nullptr; 627 break; 628 629 case Sema::TDK_Incomplete: 630 case Sema::TDK_InvalidExplicitArguments: 631 Result.Data = Info.Param.getOpaqueValue(); 632 break; 633 634 case Sema::TDK_DeducedMismatch: 635 case Sema::TDK_DeducedMismatchNested: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 auto *Saved = new (Context) DFIDeducedMismatchArgs; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Saved->TemplateArgs = Info.take(); 641 Saved->CallArgIndex = Info.CallArgIndex; 642 Result.Data = Saved; 643 break; 644 } 645 646 case Sema::TDK_NonDeducedMismatch: { 647 // FIXME: Should allocate from normal heap so that we can free this later. 648 DFIArguments *Saved = new (Context) DFIArguments; 649 Saved->FirstArg = Info.FirstArg; 650 Saved->SecondArg = Info.SecondArg; 651 Result.Data = Saved; 652 break; 653 } 654 655 case Sema::TDK_IncompletePack: 656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 657 case Sema::TDK_Inconsistent: 658 case Sema::TDK_Underqualified: { 659 // FIXME: Should allocate from normal heap so that we can free this later. 660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 661 Saved->Param = Info.Param; 662 Saved->FirstArg = Info.FirstArg; 663 Saved->SecondArg = Info.SecondArg; 664 Result.Data = Saved; 665 break; 666 } 667 668 case Sema::TDK_SubstitutionFailure: 669 Result.Data = Info.take(); 670 if (Info.hasSFINAEDiagnostic()) { 671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 672 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 673 Info.takeSFINAEDiagnostic(*Diag); 674 Result.HasDiagnostic = true; 675 } 676 break; 677 678 case Sema::TDK_ConstraintsNotSatisfied: { 679 CNSInfo *Saved = new (Context) CNSInfo; 680 Saved->TemplateArgs = Info.take(); 681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 682 Result.Data = Saved; 683 break; 684 } 685 686 case Sema::TDK_Success: 687 case Sema::TDK_NonDependentConversionFailure: 688 llvm_unreachable("not a deduction failure"); 689 } 690 691 return Result; 692 } 693 694 void DeductionFailureInfo::Destroy() { 695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 696 case Sema::TDK_Success: 697 case Sema::TDK_Invalid: 698 case Sema::TDK_InstantiationDepth: 699 case Sema::TDK_Incomplete: 700 case Sema::TDK_TooManyArguments: 701 case Sema::TDK_TooFewArguments: 702 case Sema::TDK_InvalidExplicitArguments: 703 case Sema::TDK_CUDATargetMismatch: 704 case Sema::TDK_NonDependentConversionFailure: 705 break; 706 707 case Sema::TDK_IncompletePack: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_DeducedMismatch: 711 case Sema::TDK_DeducedMismatchNested: 712 case Sema::TDK_NonDeducedMismatch: 713 // FIXME: Destroy the data? 714 Data = nullptr; 715 break; 716 717 case Sema::TDK_SubstitutionFailure: 718 // FIXME: Destroy the template argument list? 719 Data = nullptr; 720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 721 Diag->~PartialDiagnosticAt(); 722 HasDiagnostic = false; 723 } 724 break; 725 726 case Sema::TDK_ConstraintsNotSatisfied: 727 // FIXME: Destroy the template argument list? 728 Data = nullptr; 729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 730 Diag->~PartialDiagnosticAt(); 731 HasDiagnostic = false; 732 } 733 break; 734 735 // Unhandled 736 case Sema::TDK_MiscellaneousDeductionFailure: 737 break; 738 } 739 } 740 741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 742 if (HasDiagnostic) 743 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 744 return nullptr; 745 } 746 747 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 749 case Sema::TDK_Success: 750 case Sema::TDK_Invalid: 751 case Sema::TDK_InstantiationDepth: 752 case Sema::TDK_TooManyArguments: 753 case Sema::TDK_TooFewArguments: 754 case Sema::TDK_SubstitutionFailure: 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 case Sema::TDK_NonDeducedMismatch: 758 case Sema::TDK_CUDATargetMismatch: 759 case Sema::TDK_NonDependentConversionFailure: 760 case Sema::TDK_ConstraintsNotSatisfied: 761 return TemplateParameter(); 762 763 case Sema::TDK_Incomplete: 764 case Sema::TDK_InvalidExplicitArguments: 765 return TemplateParameter::getFromOpaqueValue(Data); 766 767 case Sema::TDK_IncompletePack: 768 case Sema::TDK_Inconsistent: 769 case Sema::TDK_Underqualified: 770 return static_cast<DFIParamWithArguments*>(Data)->Param; 771 772 // Unhandled 773 case Sema::TDK_MiscellaneousDeductionFailure: 774 break; 775 } 776 777 return TemplateParameter(); 778 } 779 780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 782 case Sema::TDK_Success: 783 case Sema::TDK_Invalid: 784 case Sema::TDK_InstantiationDepth: 785 case Sema::TDK_TooManyArguments: 786 case Sema::TDK_TooFewArguments: 787 case Sema::TDK_Incomplete: 788 case Sema::TDK_IncompletePack: 789 case Sema::TDK_InvalidExplicitArguments: 790 case Sema::TDK_Inconsistent: 791 case Sema::TDK_Underqualified: 792 case Sema::TDK_NonDeducedMismatch: 793 case Sema::TDK_CUDATargetMismatch: 794 case Sema::TDK_NonDependentConversionFailure: 795 return nullptr; 796 797 case Sema::TDK_DeducedMismatch: 798 case Sema::TDK_DeducedMismatchNested: 799 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 800 801 case Sema::TDK_SubstitutionFailure: 802 return static_cast<TemplateArgumentList*>(Data); 803 804 case Sema::TDK_ConstraintsNotSatisfied: 805 return static_cast<CNSInfo*>(Data)->TemplateArgs; 806 807 // Unhandled 808 case Sema::TDK_MiscellaneousDeductionFailure: 809 break; 810 } 811 812 return nullptr; 813 } 814 815 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 816 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 817 case Sema::TDK_Success: 818 case Sema::TDK_Invalid: 819 case Sema::TDK_InstantiationDepth: 820 case Sema::TDK_Incomplete: 821 case Sema::TDK_TooManyArguments: 822 case Sema::TDK_TooFewArguments: 823 case Sema::TDK_InvalidExplicitArguments: 824 case Sema::TDK_SubstitutionFailure: 825 case Sema::TDK_CUDATargetMismatch: 826 case Sema::TDK_NonDependentConversionFailure: 827 case Sema::TDK_ConstraintsNotSatisfied: 828 return nullptr; 829 830 case Sema::TDK_IncompletePack: 831 case Sema::TDK_Inconsistent: 832 case Sema::TDK_Underqualified: 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 case Sema::TDK_NonDeducedMismatch: 836 return &static_cast<DFIArguments*>(Data)->FirstArg; 837 838 // Unhandled 839 case Sema::TDK_MiscellaneousDeductionFailure: 840 break; 841 } 842 843 return nullptr; 844 } 845 846 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 847 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 848 case Sema::TDK_Success: 849 case Sema::TDK_Invalid: 850 case Sema::TDK_InstantiationDepth: 851 case Sema::TDK_Incomplete: 852 case Sema::TDK_IncompletePack: 853 case Sema::TDK_TooManyArguments: 854 case Sema::TDK_TooFewArguments: 855 case Sema::TDK_InvalidExplicitArguments: 856 case Sema::TDK_SubstitutionFailure: 857 case Sema::TDK_CUDATargetMismatch: 858 case Sema::TDK_NonDependentConversionFailure: 859 case Sema::TDK_ConstraintsNotSatisfied: 860 return nullptr; 861 862 case Sema::TDK_Inconsistent: 863 case Sema::TDK_Underqualified: 864 case Sema::TDK_DeducedMismatch: 865 case Sema::TDK_DeducedMismatchNested: 866 case Sema::TDK_NonDeducedMismatch: 867 return &static_cast<DFIArguments*>(Data)->SecondArg; 868 869 // Unhandled 870 case Sema::TDK_MiscellaneousDeductionFailure: 871 break; 872 } 873 874 return nullptr; 875 } 876 877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 878 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 879 case Sema::TDK_DeducedMismatch: 880 case Sema::TDK_DeducedMismatchNested: 881 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 882 883 default: 884 return llvm::None; 885 } 886 } 887 888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 889 OverloadedOperatorKind Op) { 890 if (!AllowRewrittenCandidates) 891 return false; 892 return Op == OO_EqualEqual || Op == OO_Spaceship; 893 } 894 895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 896 ASTContext &Ctx, const FunctionDecl *FD) { 897 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 898 return false; 899 // Don't bother adding a reversed candidate that can never be a better 900 // match than the non-reversed version. 901 return FD->getNumParams() != 2 || 902 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 903 FD->getParamDecl(1)->getType()) || 904 FD->hasAttr<EnableIfAttr>(); 905 } 906 907 void OverloadCandidateSet::destroyCandidates() { 908 for (iterator i = begin(), e = end(); i != e; ++i) { 909 for (auto &C : i->Conversions) 910 C.~ImplicitConversionSequence(); 911 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 912 i->DeductionFailure.Destroy(); 913 } 914 } 915 916 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 917 destroyCandidates(); 918 SlabAllocator.Reset(); 919 NumInlineBytesUsed = 0; 920 Candidates.clear(); 921 Functions.clear(); 922 Kind = CSK; 923 } 924 925 namespace { 926 class UnbridgedCastsSet { 927 struct Entry { 928 Expr **Addr; 929 Expr *Saved; 930 }; 931 SmallVector<Entry, 2> Entries; 932 933 public: 934 void save(Sema &S, Expr *&E) { 935 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 936 Entry entry = { &E, E }; 937 Entries.push_back(entry); 938 E = S.stripARCUnbridgedCast(E); 939 } 940 941 void restore() { 942 for (SmallVectorImpl<Entry>::iterator 943 i = Entries.begin(), e = Entries.end(); i != e; ++i) 944 *i->Addr = i->Saved; 945 } 946 }; 947 } 948 949 /// checkPlaceholderForOverload - Do any interesting placeholder-like 950 /// preprocessing on the given expression. 951 /// 952 /// \param unbridgedCasts a collection to which to add unbridged casts; 953 /// without this, they will be immediately diagnosed as errors 954 /// 955 /// Return true on unrecoverable error. 956 static bool 957 checkPlaceholderForOverload(Sema &S, Expr *&E, 958 UnbridgedCastsSet *unbridgedCasts = nullptr) { 959 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 960 // We can't handle overloaded expressions here because overload 961 // resolution might reasonably tweak them. 962 if (placeholder->getKind() == BuiltinType::Overload) return false; 963 964 // If the context potentially accepts unbridged ARC casts, strip 965 // the unbridged cast and add it to the collection for later restoration. 966 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 967 unbridgedCasts) { 968 unbridgedCasts->save(S, E); 969 return false; 970 } 971 972 // Go ahead and check everything else. 973 ExprResult result = S.CheckPlaceholderExpr(E); 974 if (result.isInvalid()) 975 return true; 976 977 E = result.get(); 978 return false; 979 } 980 981 // Nothing to do. 982 return false; 983 } 984 985 /// checkArgPlaceholdersForOverload - Check a set of call operands for 986 /// placeholders. 987 static bool checkArgPlaceholdersForOverload(Sema &S, 988 MultiExprArg Args, 989 UnbridgedCastsSet &unbridged) { 990 for (unsigned i = 0, e = Args.size(); i != e; ++i) 991 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 992 return true; 993 994 return false; 995 } 996 997 /// Determine whether the given New declaration is an overload of the 998 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 999 /// New and Old cannot be overloaded, e.g., if New has the same signature as 1000 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 1001 /// functions (or function templates) at all. When it does return Ovl_Match or 1002 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1003 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1004 /// declaration. 1005 /// 1006 /// Example: Given the following input: 1007 /// 1008 /// void f(int, float); // #1 1009 /// void f(int, int); // #2 1010 /// int f(int, int); // #3 1011 /// 1012 /// When we process #1, there is no previous declaration of "f", so IsOverload 1013 /// will not be used. 1014 /// 1015 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1016 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1017 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1018 /// unchanged. 1019 /// 1020 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1021 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1022 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1023 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1024 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1025 /// 1026 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1027 /// by a using declaration. The rules for whether to hide shadow declarations 1028 /// ignore some properties which otherwise figure into a function template's 1029 /// signature. 1030 Sema::OverloadKind 1031 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1032 NamedDecl *&Match, bool NewIsUsingDecl) { 1033 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1034 I != E; ++I) { 1035 NamedDecl *OldD = *I; 1036 1037 bool OldIsUsingDecl = false; 1038 if (isa<UsingShadowDecl>(OldD)) { 1039 OldIsUsingDecl = true; 1040 1041 // We can always introduce two using declarations into the same 1042 // context, even if they have identical signatures. 1043 if (NewIsUsingDecl) continue; 1044 1045 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1046 } 1047 1048 // A using-declaration does not conflict with another declaration 1049 // if one of them is hidden. 1050 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1051 continue; 1052 1053 // If either declaration was introduced by a using declaration, 1054 // we'll need to use slightly different rules for matching. 1055 // Essentially, these rules are the normal rules, except that 1056 // function templates hide function templates with different 1057 // return types or template parameter lists. 1058 bool UseMemberUsingDeclRules = 1059 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1060 !New->getFriendObjectKind(); 1061 1062 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1063 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1064 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1065 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1066 continue; 1067 } 1068 1069 if (!isa<FunctionTemplateDecl>(OldD) && 1070 !shouldLinkPossiblyHiddenDecl(*I, New)) 1071 continue; 1072 1073 Match = *I; 1074 return Ovl_Match; 1075 } 1076 1077 // Builtins that have custom typechecking or have a reference should 1078 // not be overloadable or redeclarable. 1079 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1080 Match = *I; 1081 return Ovl_NonFunction; 1082 } 1083 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1084 // We can overload with these, which can show up when doing 1085 // redeclaration checks for UsingDecls. 1086 assert(Old.getLookupKind() == LookupUsingDeclName); 1087 } else if (isa<TagDecl>(OldD)) { 1088 // We can always overload with tags by hiding them. 1089 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1090 // Optimistically assume that an unresolved using decl will 1091 // overload; if it doesn't, we'll have to diagnose during 1092 // template instantiation. 1093 // 1094 // Exception: if the scope is dependent and this is not a class 1095 // member, the using declaration can only introduce an enumerator. 1096 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1097 Match = *I; 1098 return Ovl_NonFunction; 1099 } 1100 } else { 1101 // (C++ 13p1): 1102 // Only function declarations can be overloaded; object and type 1103 // declarations cannot be overloaded. 1104 Match = *I; 1105 return Ovl_NonFunction; 1106 } 1107 } 1108 1109 // C++ [temp.friend]p1: 1110 // For a friend function declaration that is not a template declaration: 1111 // -- if the name of the friend is a qualified or unqualified template-id, 1112 // [...], otherwise 1113 // -- if the name of the friend is a qualified-id and a matching 1114 // non-template function is found in the specified class or namespace, 1115 // the friend declaration refers to that function, otherwise, 1116 // -- if the name of the friend is a qualified-id and a matching function 1117 // template is found in the specified class or namespace, the friend 1118 // declaration refers to the deduced specialization of that function 1119 // template, otherwise 1120 // -- the name shall be an unqualified-id [...] 1121 // If we get here for a qualified friend declaration, we've just reached the 1122 // third bullet. If the type of the friend is dependent, skip this lookup 1123 // until instantiation. 1124 if (New->getFriendObjectKind() && New->getQualifier() && 1125 !New->getDescribedFunctionTemplate() && 1126 !New->getDependentSpecializationInfo() && 1127 !New->getType()->isDependentType()) { 1128 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1129 TemplateSpecResult.addAllDecls(Old); 1130 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1131 /*QualifiedFriend*/true)) { 1132 New->setInvalidDecl(); 1133 return Ovl_Overload; 1134 } 1135 1136 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1137 return Ovl_Match; 1138 } 1139 1140 return Ovl_Overload; 1141 } 1142 1143 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1145 bool ConsiderRequiresClauses) { 1146 // C++ [basic.start.main]p2: This function shall not be overloaded. 1147 if (New->isMain()) 1148 return false; 1149 1150 // MSVCRT user defined entry points cannot be overloaded. 1151 if (New->isMSVCRTEntryPoint()) 1152 return false; 1153 1154 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1155 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1156 1157 // C++ [temp.fct]p2: 1158 // A function template can be overloaded with other function templates 1159 // and with normal (non-template) functions. 1160 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1161 return true; 1162 1163 // Is the function New an overload of the function Old? 1164 QualType OldQType = Context.getCanonicalType(Old->getType()); 1165 QualType NewQType = Context.getCanonicalType(New->getType()); 1166 1167 // Compare the signatures (C++ 1.3.10) of the two functions to 1168 // determine whether they are overloads. If we find any mismatch 1169 // in the signature, they are overloads. 1170 1171 // If either of these functions is a K&R-style function (no 1172 // prototype), then we consider them to have matching signatures. 1173 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1174 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1175 return false; 1176 1177 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1178 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1179 1180 // The signature of a function includes the types of its 1181 // parameters (C++ 1.3.10), which includes the presence or absence 1182 // of the ellipsis; see C++ DR 357). 1183 if (OldQType != NewQType && 1184 (OldType->getNumParams() != NewType->getNumParams() || 1185 OldType->isVariadic() != NewType->isVariadic() || 1186 !FunctionParamTypesAreEqual(OldType, NewType))) 1187 return true; 1188 1189 // C++ [temp.over.link]p4: 1190 // The signature of a function template consists of its function 1191 // signature, its return type and its template parameter list. The names 1192 // of the template parameters are significant only for establishing the 1193 // relationship between the template parameters and the rest of the 1194 // signature. 1195 // 1196 // We check the return type and template parameter lists for function 1197 // templates first; the remaining checks follow. 1198 // 1199 // However, we don't consider either of these when deciding whether 1200 // a member introduced by a shadow declaration is hidden. 1201 if (!UseMemberUsingDeclRules && NewTemplate && 1202 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1203 OldTemplate->getTemplateParameters(), 1204 false, TPL_TemplateMatch) || 1205 !Context.hasSameType(Old->getDeclaredReturnType(), 1206 New->getDeclaredReturnType()))) 1207 return true; 1208 1209 // If the function is a class member, its signature includes the 1210 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1211 // 1212 // As part of this, also check whether one of the member functions 1213 // is static, in which case they are not overloads (C++ 1214 // 13.1p2). While not part of the definition of the signature, 1215 // this check is important to determine whether these functions 1216 // can be overloaded. 1217 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1218 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1219 if (OldMethod && NewMethod && 1220 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1221 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1222 if (!UseMemberUsingDeclRules && 1223 (OldMethod->getRefQualifier() == RQ_None || 1224 NewMethod->getRefQualifier() == RQ_None)) { 1225 // C++0x [over.load]p2: 1226 // - Member function declarations with the same name and the same 1227 // parameter-type-list as well as member function template 1228 // declarations with the same name, the same parameter-type-list, and 1229 // the same template parameter lists cannot be overloaded if any of 1230 // them, but not all, have a ref-qualifier (8.3.5). 1231 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1232 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1233 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1234 } 1235 return true; 1236 } 1237 1238 // We may not have applied the implicit const for a constexpr member 1239 // function yet (because we haven't yet resolved whether this is a static 1240 // or non-static member function). Add it now, on the assumption that this 1241 // is a redeclaration of OldMethod. 1242 auto OldQuals = OldMethod->getMethodQualifiers(); 1243 auto NewQuals = NewMethod->getMethodQualifiers(); 1244 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1245 !isa<CXXConstructorDecl>(NewMethod)) 1246 NewQuals.addConst(); 1247 // We do not allow overloading based off of '__restrict'. 1248 OldQuals.removeRestrict(); 1249 NewQuals.removeRestrict(); 1250 if (OldQuals != NewQuals) 1251 return true; 1252 } 1253 1254 // Though pass_object_size is placed on parameters and takes an argument, we 1255 // consider it to be a function-level modifier for the sake of function 1256 // identity. Either the function has one or more parameters with 1257 // pass_object_size or it doesn't. 1258 if (functionHasPassObjectSizeParams(New) != 1259 functionHasPassObjectSizeParams(Old)) 1260 return true; 1261 1262 // enable_if attributes are an order-sensitive part of the signature. 1263 for (specific_attr_iterator<EnableIfAttr> 1264 NewI = New->specific_attr_begin<EnableIfAttr>(), 1265 NewE = New->specific_attr_end<EnableIfAttr>(), 1266 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1267 OldE = Old->specific_attr_end<EnableIfAttr>(); 1268 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1269 if (NewI == NewE || OldI == OldE) 1270 return true; 1271 llvm::FoldingSetNodeID NewID, OldID; 1272 NewI->getCond()->Profile(NewID, Context, true); 1273 OldI->getCond()->Profile(OldID, Context, true); 1274 if (NewID != OldID) 1275 return true; 1276 } 1277 1278 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1279 // Don't allow overloading of destructors. (In theory we could, but it 1280 // would be a giant change to clang.) 1281 if (!isa<CXXDestructorDecl>(New)) { 1282 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1283 OldTarget = IdentifyCUDATarget(Old); 1284 if (NewTarget != CFT_InvalidTarget) { 1285 assert((OldTarget != CFT_InvalidTarget) && 1286 "Unexpected invalid target."); 1287 1288 // Allow overloading of functions with same signature and different CUDA 1289 // target attributes. 1290 if (NewTarget != OldTarget) 1291 return true; 1292 } 1293 } 1294 } 1295 1296 if (ConsiderRequiresClauses) { 1297 Expr *NewRC = New->getTrailingRequiresClause(), 1298 *OldRC = Old->getTrailingRequiresClause(); 1299 if ((NewRC != nullptr) != (OldRC != nullptr)) 1300 // RC are most certainly different - these are overloads. 1301 return true; 1302 1303 if (NewRC) { 1304 llvm::FoldingSetNodeID NewID, OldID; 1305 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1306 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1307 if (NewID != OldID) 1308 // RCs are not equivalent - these are overloads. 1309 return true; 1310 } 1311 } 1312 1313 // The signatures match; this is not an overload. 1314 return false; 1315 } 1316 1317 /// Tries a user-defined conversion from From to ToType. 1318 /// 1319 /// Produces an implicit conversion sequence for when a standard conversion 1320 /// is not an option. See TryImplicitConversion for more information. 1321 static ImplicitConversionSequence 1322 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1323 bool SuppressUserConversions, 1324 AllowedExplicit AllowExplicit, 1325 bool InOverloadResolution, 1326 bool CStyle, 1327 bool AllowObjCWritebackConversion, 1328 bool AllowObjCConversionOnExplicit) { 1329 ImplicitConversionSequence ICS; 1330 1331 if (SuppressUserConversions) { 1332 // We're not in the case above, so there is no conversion that 1333 // we can perform. 1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1335 return ICS; 1336 } 1337 1338 // Attempt user-defined conversion. 1339 OverloadCandidateSet Conversions(From->getExprLoc(), 1340 OverloadCandidateSet::CSK_Normal); 1341 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1342 Conversions, AllowExplicit, 1343 AllowObjCConversionOnExplicit)) { 1344 case OR_Success: 1345 case OR_Deleted: 1346 ICS.setUserDefined(); 1347 // C++ [over.ics.user]p4: 1348 // A conversion of an expression of class type to the same class 1349 // type is given Exact Match rank, and a conversion of an 1350 // expression of class type to a base class of that type is 1351 // given Conversion rank, in spite of the fact that a copy 1352 // constructor (i.e., a user-defined conversion function) is 1353 // called for those cases. 1354 if (CXXConstructorDecl *Constructor 1355 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1356 QualType FromCanon 1357 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1358 QualType ToCanon 1359 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1360 if (Constructor->isCopyConstructor() && 1361 (FromCanon == ToCanon || 1362 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1363 // Turn this into a "standard" conversion sequence, so that it 1364 // gets ranked with standard conversion sequences. 1365 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1366 ICS.setStandard(); 1367 ICS.Standard.setAsIdentityConversion(); 1368 ICS.Standard.setFromType(From->getType()); 1369 ICS.Standard.setAllToTypes(ToType); 1370 ICS.Standard.CopyConstructor = Constructor; 1371 ICS.Standard.FoundCopyConstructor = Found; 1372 if (ToCanon != FromCanon) 1373 ICS.Standard.Second = ICK_Derived_To_Base; 1374 } 1375 } 1376 break; 1377 1378 case OR_Ambiguous: 1379 ICS.setAmbiguous(); 1380 ICS.Ambiguous.setFromType(From->getType()); 1381 ICS.Ambiguous.setToType(ToType); 1382 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1383 Cand != Conversions.end(); ++Cand) 1384 if (Cand->Best) 1385 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1386 break; 1387 1388 // Fall through. 1389 case OR_No_Viable_Function: 1390 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1391 break; 1392 } 1393 1394 return ICS; 1395 } 1396 1397 /// TryImplicitConversion - Attempt to perform an implicit conversion 1398 /// from the given expression (Expr) to the given type (ToType). This 1399 /// function returns an implicit conversion sequence that can be used 1400 /// to perform the initialization. Given 1401 /// 1402 /// void f(float f); 1403 /// void g(int i) { f(i); } 1404 /// 1405 /// this routine would produce an implicit conversion sequence to 1406 /// describe the initialization of f from i, which will be a standard 1407 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1408 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1409 // 1410 /// Note that this routine only determines how the conversion can be 1411 /// performed; it does not actually perform the conversion. As such, 1412 /// it will not produce any diagnostics if no conversion is available, 1413 /// but will instead return an implicit conversion sequence of kind 1414 /// "BadConversion". 1415 /// 1416 /// If @p SuppressUserConversions, then user-defined conversions are 1417 /// not permitted. 1418 /// If @p AllowExplicit, then explicit user-defined conversions are 1419 /// permitted. 1420 /// 1421 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1422 /// writeback conversion, which allows __autoreleasing id* parameters to 1423 /// be initialized with __strong id* or __weak id* arguments. 1424 static ImplicitConversionSequence 1425 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1426 bool SuppressUserConversions, 1427 AllowedExplicit AllowExplicit, 1428 bool InOverloadResolution, 1429 bool CStyle, 1430 bool AllowObjCWritebackConversion, 1431 bool AllowObjCConversionOnExplicit) { 1432 ImplicitConversionSequence ICS; 1433 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1434 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1435 ICS.setStandard(); 1436 return ICS; 1437 } 1438 1439 if (!S.getLangOpts().CPlusPlus) { 1440 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1441 return ICS; 1442 } 1443 1444 // C++ [over.ics.user]p4: 1445 // A conversion of an expression of class type to the same class 1446 // type is given Exact Match rank, and a conversion of an 1447 // expression of class type to a base class of that type is 1448 // given Conversion rank, in spite of the fact that a copy/move 1449 // constructor (i.e., a user-defined conversion function) is 1450 // called for those cases. 1451 QualType FromType = From->getType(); 1452 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1453 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1454 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1455 ICS.setStandard(); 1456 ICS.Standard.setAsIdentityConversion(); 1457 ICS.Standard.setFromType(FromType); 1458 ICS.Standard.setAllToTypes(ToType); 1459 1460 // We don't actually check at this point whether there is a valid 1461 // copy/move constructor, since overloading just assumes that it 1462 // exists. When we actually perform initialization, we'll find the 1463 // appropriate constructor to copy the returned object, if needed. 1464 ICS.Standard.CopyConstructor = nullptr; 1465 1466 // Determine whether this is considered a derived-to-base conversion. 1467 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1468 ICS.Standard.Second = ICK_Derived_To_Base; 1469 1470 return ICS; 1471 } 1472 1473 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1474 AllowExplicit, InOverloadResolution, CStyle, 1475 AllowObjCWritebackConversion, 1476 AllowObjCConversionOnExplicit); 1477 } 1478 1479 ImplicitConversionSequence 1480 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1481 bool SuppressUserConversions, 1482 AllowedExplicit AllowExplicit, 1483 bool InOverloadResolution, 1484 bool CStyle, 1485 bool AllowObjCWritebackConversion) { 1486 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1487 AllowExplicit, InOverloadResolution, CStyle, 1488 AllowObjCWritebackConversion, 1489 /*AllowObjCConversionOnExplicit=*/false); 1490 } 1491 1492 /// PerformImplicitConversion - Perform an implicit conversion of the 1493 /// expression From to the type ToType. Returns the 1494 /// converted expression. Flavor is the kind of conversion we're 1495 /// performing, used in the error message. If @p AllowExplicit, 1496 /// explicit user-defined conversions are permitted. 1497 ExprResult 1498 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1499 AssignmentAction Action, bool AllowExplicit) { 1500 ImplicitConversionSequence ICS; 1501 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1502 } 1503 1504 ExprResult 1505 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1506 AssignmentAction Action, bool AllowExplicit, 1507 ImplicitConversionSequence& ICS) { 1508 if (checkPlaceholderForOverload(*this, From)) 1509 return ExprError(); 1510 1511 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1512 bool AllowObjCWritebackConversion 1513 = getLangOpts().ObjCAutoRefCount && 1514 (Action == AA_Passing || Action == AA_Sending); 1515 if (getLangOpts().ObjC) 1516 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1517 From->getType(), From); 1518 ICS = ::TryImplicitConversion(*this, From, ToType, 1519 /*SuppressUserConversions=*/false, 1520 AllowExplicit ? AllowedExplicit::All 1521 : AllowedExplicit::None, 1522 /*InOverloadResolution=*/false, 1523 /*CStyle=*/false, AllowObjCWritebackConversion, 1524 /*AllowObjCConversionOnExplicit=*/false); 1525 return PerformImplicitConversion(From, ToType, ICS, Action); 1526 } 1527 1528 /// Determine whether the conversion from FromType to ToType is a valid 1529 /// conversion that strips "noexcept" or "noreturn" off the nested function 1530 /// type. 1531 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1532 QualType &ResultTy) { 1533 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1534 return false; 1535 1536 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1537 // or F(t noexcept) -> F(t) 1538 // where F adds one of the following at most once: 1539 // - a pointer 1540 // - a member pointer 1541 // - a block pointer 1542 // Changes here need matching changes in FindCompositePointerType. 1543 CanQualType CanTo = Context.getCanonicalType(ToType); 1544 CanQualType CanFrom = Context.getCanonicalType(FromType); 1545 Type::TypeClass TyClass = CanTo->getTypeClass(); 1546 if (TyClass != CanFrom->getTypeClass()) return false; 1547 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1548 if (TyClass == Type::Pointer) { 1549 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1550 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1551 } else if (TyClass == Type::BlockPointer) { 1552 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1553 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1554 } else if (TyClass == Type::MemberPointer) { 1555 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1556 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1557 // A function pointer conversion cannot change the class of the function. 1558 if (ToMPT->getClass() != FromMPT->getClass()) 1559 return false; 1560 CanTo = ToMPT->getPointeeType(); 1561 CanFrom = FromMPT->getPointeeType(); 1562 } else { 1563 return false; 1564 } 1565 1566 TyClass = CanTo->getTypeClass(); 1567 if (TyClass != CanFrom->getTypeClass()) return false; 1568 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1569 return false; 1570 } 1571 1572 const auto *FromFn = cast<FunctionType>(CanFrom); 1573 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1574 1575 const auto *ToFn = cast<FunctionType>(CanTo); 1576 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1577 1578 bool Changed = false; 1579 1580 // Drop 'noreturn' if not present in target type. 1581 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1582 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1583 Changed = true; 1584 } 1585 1586 // Drop 'noexcept' if not present in target type. 1587 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1588 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1589 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1590 FromFn = cast<FunctionType>( 1591 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1592 EST_None) 1593 .getTypePtr()); 1594 Changed = true; 1595 } 1596 1597 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1598 // only if the ExtParameterInfo lists of the two function prototypes can be 1599 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1600 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1601 bool CanUseToFPT, CanUseFromFPT; 1602 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1603 CanUseFromFPT, NewParamInfos) && 1604 CanUseToFPT && !CanUseFromFPT) { 1605 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1606 ExtInfo.ExtParameterInfos = 1607 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1608 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1609 FromFPT->getParamTypes(), ExtInfo); 1610 FromFn = QT->getAs<FunctionType>(); 1611 Changed = true; 1612 } 1613 } 1614 1615 if (!Changed) 1616 return false; 1617 1618 assert(QualType(FromFn, 0).isCanonical()); 1619 if (QualType(FromFn, 0) != CanTo) return false; 1620 1621 ResultTy = ToType; 1622 return true; 1623 } 1624 1625 /// Determine whether the conversion from FromType to ToType is a valid 1626 /// vector conversion. 1627 /// 1628 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1629 /// conversion. 1630 static bool IsVectorConversion(Sema &S, QualType FromType, 1631 QualType ToType, ImplicitConversionKind &ICK) { 1632 // We need at least one of these types to be a vector type to have a vector 1633 // conversion. 1634 if (!ToType->isVectorType() && !FromType->isVectorType()) 1635 return false; 1636 1637 // Identical types require no conversions. 1638 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1639 return false; 1640 1641 // There are no conversions between extended vector types, only identity. 1642 if (ToType->isExtVectorType()) { 1643 // There are no conversions between extended vector types other than the 1644 // identity conversion. 1645 if (FromType->isExtVectorType()) 1646 return false; 1647 1648 // Vector splat from any arithmetic type to a vector. 1649 if (FromType->isArithmeticType()) { 1650 ICK = ICK_Vector_Splat; 1651 return true; 1652 } 1653 } 1654 1655 if ((ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) && 1656 S.Context.areCompatibleSveTypes(FromType, ToType)) { 1657 ICK = ICK_SVE_Vector_Conversion; 1658 return true; 1659 } 1660 1661 // We can perform the conversion between vector types in the following cases: 1662 // 1)vector types are equivalent AltiVec and GCC vector types 1663 // 2)lax vector conversions are permitted and the vector types are of the 1664 // same size 1665 // 3)the destination type does not have the ARM MVE strict-polymorphism 1666 // attribute, which inhibits lax vector conversion for overload resolution 1667 // only 1668 if (ToType->isVectorType() && FromType->isVectorType()) { 1669 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1670 (S.isLaxVectorConversion(FromType, ToType) && 1671 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1672 ICK = ICK_Vector_Conversion; 1673 return true; 1674 } 1675 } 1676 1677 return false; 1678 } 1679 1680 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1681 bool InOverloadResolution, 1682 StandardConversionSequence &SCS, 1683 bool CStyle); 1684 1685 /// IsStandardConversion - Determines whether there is a standard 1686 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1687 /// expression From to the type ToType. Standard conversion sequences 1688 /// only consider non-class types; for conversions that involve class 1689 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1690 /// contain the standard conversion sequence required to perform this 1691 /// conversion and this routine will return true. Otherwise, this 1692 /// routine will return false and the value of SCS is unspecified. 1693 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1694 bool InOverloadResolution, 1695 StandardConversionSequence &SCS, 1696 bool CStyle, 1697 bool AllowObjCWritebackConversion) { 1698 QualType FromType = From->getType(); 1699 1700 // Standard conversions (C++ [conv]) 1701 SCS.setAsIdentityConversion(); 1702 SCS.IncompatibleObjC = false; 1703 SCS.setFromType(FromType); 1704 SCS.CopyConstructor = nullptr; 1705 1706 // There are no standard conversions for class types in C++, so 1707 // abort early. When overloading in C, however, we do permit them. 1708 if (S.getLangOpts().CPlusPlus && 1709 (FromType->isRecordType() || ToType->isRecordType())) 1710 return false; 1711 1712 // The first conversion can be an lvalue-to-rvalue conversion, 1713 // array-to-pointer conversion, or function-to-pointer conversion 1714 // (C++ 4p1). 1715 1716 if (FromType == S.Context.OverloadTy) { 1717 DeclAccessPair AccessPair; 1718 if (FunctionDecl *Fn 1719 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1720 AccessPair)) { 1721 // We were able to resolve the address of the overloaded function, 1722 // so we can convert to the type of that function. 1723 FromType = Fn->getType(); 1724 SCS.setFromType(FromType); 1725 1726 // we can sometimes resolve &foo<int> regardless of ToType, so check 1727 // if the type matches (identity) or we are converting to bool 1728 if (!S.Context.hasSameUnqualifiedType( 1729 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1730 QualType resultTy; 1731 // if the function type matches except for [[noreturn]], it's ok 1732 if (!S.IsFunctionConversion(FromType, 1733 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1734 // otherwise, only a boolean conversion is standard 1735 if (!ToType->isBooleanType()) 1736 return false; 1737 } 1738 1739 // Check if the "from" expression is taking the address of an overloaded 1740 // function and recompute the FromType accordingly. Take advantage of the 1741 // fact that non-static member functions *must* have such an address-of 1742 // expression. 1743 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1744 if (Method && !Method->isStatic()) { 1745 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1746 "Non-unary operator on non-static member address"); 1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1748 == UO_AddrOf && 1749 "Non-address-of operator on non-static member address"); 1750 const Type *ClassType 1751 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1752 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1753 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1754 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1755 UO_AddrOf && 1756 "Non-address-of operator for overloaded function expression"); 1757 FromType = S.Context.getPointerType(FromType); 1758 } 1759 1760 // Check that we've computed the proper type after overload resolution. 1761 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1762 // be calling it from within an NDEBUG block. 1763 assert(S.Context.hasSameType( 1764 FromType, 1765 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1766 } else { 1767 return false; 1768 } 1769 } 1770 // Lvalue-to-rvalue conversion (C++11 4.1): 1771 // A glvalue (3.10) of a non-function, non-array type T can 1772 // be converted to a prvalue. 1773 bool argIsLValue = From->isGLValue(); 1774 if (argIsLValue && 1775 !FromType->isFunctionType() && !FromType->isArrayType() && 1776 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1777 SCS.First = ICK_Lvalue_To_Rvalue; 1778 1779 // C11 6.3.2.1p2: 1780 // ... if the lvalue has atomic type, the value has the non-atomic version 1781 // of the type of the lvalue ... 1782 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1783 FromType = Atomic->getValueType(); 1784 1785 // If T is a non-class type, the type of the rvalue is the 1786 // cv-unqualified version of T. Otherwise, the type of the rvalue 1787 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1788 // just strip the qualifiers because they don't matter. 1789 FromType = FromType.getUnqualifiedType(); 1790 } else if (FromType->isArrayType()) { 1791 // Array-to-pointer conversion (C++ 4.2) 1792 SCS.First = ICK_Array_To_Pointer; 1793 1794 // An lvalue or rvalue of type "array of N T" or "array of unknown 1795 // bound of T" can be converted to an rvalue of type "pointer to 1796 // T" (C++ 4.2p1). 1797 FromType = S.Context.getArrayDecayedType(FromType); 1798 1799 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1800 // This conversion is deprecated in C++03 (D.4) 1801 SCS.DeprecatedStringLiteralToCharPtr = true; 1802 1803 // For the purpose of ranking in overload resolution 1804 // (13.3.3.1.1), this conversion is considered an 1805 // array-to-pointer conversion followed by a qualification 1806 // conversion (4.4). (C++ 4.2p2) 1807 SCS.Second = ICK_Identity; 1808 SCS.Third = ICK_Qualification; 1809 SCS.QualificationIncludesObjCLifetime = false; 1810 SCS.setAllToTypes(FromType); 1811 return true; 1812 } 1813 } else if (FromType->isFunctionType() && argIsLValue) { 1814 // Function-to-pointer conversion (C++ 4.3). 1815 SCS.First = ICK_Function_To_Pointer; 1816 1817 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1818 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1819 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1820 return false; 1821 1822 // An lvalue of function type T can be converted to an rvalue of 1823 // type "pointer to T." The result is a pointer to the 1824 // function. (C++ 4.3p1). 1825 FromType = S.Context.getPointerType(FromType); 1826 } else { 1827 // We don't require any conversions for the first step. 1828 SCS.First = ICK_Identity; 1829 } 1830 SCS.setToType(0, FromType); 1831 1832 // The second conversion can be an integral promotion, floating 1833 // point promotion, integral conversion, floating point conversion, 1834 // floating-integral conversion, pointer conversion, 1835 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1836 // For overloading in C, this can also be a "compatible-type" 1837 // conversion. 1838 bool IncompatibleObjC = false; 1839 ImplicitConversionKind SecondICK = ICK_Identity; 1840 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1841 // The unqualified versions of the types are the same: there's no 1842 // conversion to do. 1843 SCS.Second = ICK_Identity; 1844 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1845 // Integral promotion (C++ 4.5). 1846 SCS.Second = ICK_Integral_Promotion; 1847 FromType = ToType.getUnqualifiedType(); 1848 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1849 // Floating point promotion (C++ 4.6). 1850 SCS.Second = ICK_Floating_Promotion; 1851 FromType = ToType.getUnqualifiedType(); 1852 } else if (S.IsComplexPromotion(FromType, ToType)) { 1853 // Complex promotion (Clang extension) 1854 SCS.Second = ICK_Complex_Promotion; 1855 FromType = ToType.getUnqualifiedType(); 1856 } else if (ToType->isBooleanType() && 1857 (FromType->isArithmeticType() || 1858 FromType->isAnyPointerType() || 1859 FromType->isBlockPointerType() || 1860 FromType->isMemberPointerType())) { 1861 // Boolean conversions (C++ 4.12). 1862 SCS.Second = ICK_Boolean_Conversion; 1863 FromType = S.Context.BoolTy; 1864 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1865 ToType->isIntegralType(S.Context)) { 1866 // Integral conversions (C++ 4.7). 1867 SCS.Second = ICK_Integral_Conversion; 1868 FromType = ToType.getUnqualifiedType(); 1869 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1870 // Complex conversions (C99 6.3.1.6) 1871 SCS.Second = ICK_Complex_Conversion; 1872 FromType = ToType.getUnqualifiedType(); 1873 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1874 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1875 // Complex-real conversions (C99 6.3.1.7) 1876 SCS.Second = ICK_Complex_Real; 1877 FromType = ToType.getUnqualifiedType(); 1878 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1879 // FIXME: disable conversions between long double and __float128 if 1880 // their representation is different until there is back end support 1881 // We of course allow this conversion if long double is really double. 1882 1883 // Conversions between bfloat and other floats are not permitted. 1884 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1885 return false; 1886 if (&S.Context.getFloatTypeSemantics(FromType) != 1887 &S.Context.getFloatTypeSemantics(ToType)) { 1888 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1889 ToType == S.Context.LongDoubleTy) || 1890 (FromType == S.Context.LongDoubleTy && 1891 ToType == S.Context.Float128Ty)); 1892 if (Float128AndLongDouble && 1893 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1894 &llvm::APFloat::PPCDoubleDouble())) 1895 return false; 1896 } 1897 // Floating point conversions (C++ 4.8). 1898 SCS.Second = ICK_Floating_Conversion; 1899 FromType = ToType.getUnqualifiedType(); 1900 } else if ((FromType->isRealFloatingType() && 1901 ToType->isIntegralType(S.Context)) || 1902 (FromType->isIntegralOrUnscopedEnumerationType() && 1903 ToType->isRealFloatingType())) { 1904 // Conversions between bfloat and int are not permitted. 1905 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1906 return false; 1907 1908 // Floating-integral conversions (C++ 4.9). 1909 SCS.Second = ICK_Floating_Integral; 1910 FromType = ToType.getUnqualifiedType(); 1911 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1912 SCS.Second = ICK_Block_Pointer_Conversion; 1913 } else if (AllowObjCWritebackConversion && 1914 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1915 SCS.Second = ICK_Writeback_Conversion; 1916 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1917 FromType, IncompatibleObjC)) { 1918 // Pointer conversions (C++ 4.10). 1919 SCS.Second = ICK_Pointer_Conversion; 1920 SCS.IncompatibleObjC = IncompatibleObjC; 1921 FromType = FromType.getUnqualifiedType(); 1922 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1923 InOverloadResolution, FromType)) { 1924 // Pointer to member conversions (4.11). 1925 SCS.Second = ICK_Pointer_Member; 1926 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1927 SCS.Second = SecondICK; 1928 FromType = ToType.getUnqualifiedType(); 1929 } else if (!S.getLangOpts().CPlusPlus && 1930 S.Context.typesAreCompatible(ToType, FromType)) { 1931 // Compatible conversions (Clang extension for C function overloading) 1932 SCS.Second = ICK_Compatible_Conversion; 1933 FromType = ToType.getUnqualifiedType(); 1934 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1935 InOverloadResolution, 1936 SCS, CStyle)) { 1937 SCS.Second = ICK_TransparentUnionConversion; 1938 FromType = ToType; 1939 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1940 CStyle)) { 1941 // tryAtomicConversion has updated the standard conversion sequence 1942 // appropriately. 1943 return true; 1944 } else if (ToType->isEventT() && 1945 From->isIntegerConstantExpr(S.getASTContext()) && 1946 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1947 SCS.Second = ICK_Zero_Event_Conversion; 1948 FromType = ToType; 1949 } else if (ToType->isQueueT() && 1950 From->isIntegerConstantExpr(S.getASTContext()) && 1951 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1952 SCS.Second = ICK_Zero_Queue_Conversion; 1953 FromType = ToType; 1954 } else if (ToType->isSamplerT() && 1955 From->isIntegerConstantExpr(S.getASTContext())) { 1956 SCS.Second = ICK_Compatible_Conversion; 1957 FromType = ToType; 1958 } else { 1959 // No second conversion required. 1960 SCS.Second = ICK_Identity; 1961 } 1962 SCS.setToType(1, FromType); 1963 1964 // The third conversion can be a function pointer conversion or a 1965 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1966 bool ObjCLifetimeConversion; 1967 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1968 // Function pointer conversions (removing 'noexcept') including removal of 1969 // 'noreturn' (Clang extension). 1970 SCS.Third = ICK_Function_Conversion; 1971 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1972 ObjCLifetimeConversion)) { 1973 SCS.Third = ICK_Qualification; 1974 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1975 FromType = ToType; 1976 } else { 1977 // No conversion required 1978 SCS.Third = ICK_Identity; 1979 } 1980 1981 // C++ [over.best.ics]p6: 1982 // [...] Any difference in top-level cv-qualification is 1983 // subsumed by the initialization itself and does not constitute 1984 // a conversion. [...] 1985 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1986 QualType CanonTo = S.Context.getCanonicalType(ToType); 1987 if (CanonFrom.getLocalUnqualifiedType() 1988 == CanonTo.getLocalUnqualifiedType() && 1989 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1990 FromType = ToType; 1991 CanonFrom = CanonTo; 1992 } 1993 1994 SCS.setToType(2, FromType); 1995 1996 if (CanonFrom == CanonTo) 1997 return true; 1998 1999 // If we have not converted the argument type to the parameter type, 2000 // this is a bad conversion sequence, unless we're resolving an overload in C. 2001 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 2002 return false; 2003 2004 ExprResult ER = ExprResult{From}; 2005 Sema::AssignConvertType Conv = 2006 S.CheckSingleAssignmentConstraints(ToType, ER, 2007 /*Diagnose=*/false, 2008 /*DiagnoseCFAudited=*/false, 2009 /*ConvertRHS=*/false); 2010 ImplicitConversionKind SecondConv; 2011 switch (Conv) { 2012 case Sema::Compatible: 2013 SecondConv = ICK_C_Only_Conversion; 2014 break; 2015 // For our purposes, discarding qualifiers is just as bad as using an 2016 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2017 // qualifiers, as well. 2018 case Sema::CompatiblePointerDiscardsQualifiers: 2019 case Sema::IncompatiblePointer: 2020 case Sema::IncompatiblePointerSign: 2021 SecondConv = ICK_Incompatible_Pointer_Conversion; 2022 break; 2023 default: 2024 return false; 2025 } 2026 2027 // First can only be an lvalue conversion, so we pretend that this was the 2028 // second conversion. First should already be valid from earlier in the 2029 // function. 2030 SCS.Second = SecondConv; 2031 SCS.setToType(1, ToType); 2032 2033 // Third is Identity, because Second should rank us worse than any other 2034 // conversion. This could also be ICK_Qualification, but it's simpler to just 2035 // lump everything in with the second conversion, and we don't gain anything 2036 // from making this ICK_Qualification. 2037 SCS.Third = ICK_Identity; 2038 SCS.setToType(2, ToType); 2039 return true; 2040 } 2041 2042 static bool 2043 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2044 QualType &ToType, 2045 bool InOverloadResolution, 2046 StandardConversionSequence &SCS, 2047 bool CStyle) { 2048 2049 const RecordType *UT = ToType->getAsUnionType(); 2050 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2051 return false; 2052 // The field to initialize within the transparent union. 2053 RecordDecl *UD = UT->getDecl(); 2054 // It's compatible if the expression matches any of the fields. 2055 for (const auto *it : UD->fields()) { 2056 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2057 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2058 ToType = it->getType(); 2059 return true; 2060 } 2061 } 2062 return false; 2063 } 2064 2065 /// IsIntegralPromotion - Determines whether the conversion from the 2066 /// expression From (whose potentially-adjusted type is FromType) to 2067 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2068 /// sets PromotedType to the promoted type. 2069 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2070 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2071 // All integers are built-in. 2072 if (!To) { 2073 return false; 2074 } 2075 2076 // An rvalue of type char, signed char, unsigned char, short int, or 2077 // unsigned short int can be converted to an rvalue of type int if 2078 // int can represent all the values of the source type; otherwise, 2079 // the source rvalue can be converted to an rvalue of type unsigned 2080 // int (C++ 4.5p1). 2081 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2082 !FromType->isEnumeralType()) { 2083 if (// We can promote any signed, promotable integer type to an int 2084 (FromType->isSignedIntegerType() || 2085 // We can promote any unsigned integer type whose size is 2086 // less than int to an int. 2087 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2088 return To->getKind() == BuiltinType::Int; 2089 } 2090 2091 return To->getKind() == BuiltinType::UInt; 2092 } 2093 2094 // C++11 [conv.prom]p3: 2095 // A prvalue of an unscoped enumeration type whose underlying type is not 2096 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2097 // following types that can represent all the values of the enumeration 2098 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2099 // unsigned int, long int, unsigned long int, long long int, or unsigned 2100 // long long int. If none of the types in that list can represent all the 2101 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2102 // type can be converted to an rvalue a prvalue of the extended integer type 2103 // with lowest integer conversion rank (4.13) greater than the rank of long 2104 // long in which all the values of the enumeration can be represented. If 2105 // there are two such extended types, the signed one is chosen. 2106 // C++11 [conv.prom]p4: 2107 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2108 // can be converted to a prvalue of its underlying type. Moreover, if 2109 // integral promotion can be applied to its underlying type, a prvalue of an 2110 // unscoped enumeration type whose underlying type is fixed can also be 2111 // converted to a prvalue of the promoted underlying type. 2112 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2113 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2114 // provided for a scoped enumeration. 2115 if (FromEnumType->getDecl()->isScoped()) 2116 return false; 2117 2118 // We can perform an integral promotion to the underlying type of the enum, 2119 // even if that's not the promoted type. Note that the check for promoting 2120 // the underlying type is based on the type alone, and does not consider 2121 // the bitfield-ness of the actual source expression. 2122 if (FromEnumType->getDecl()->isFixed()) { 2123 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2124 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2125 IsIntegralPromotion(nullptr, Underlying, ToType); 2126 } 2127 2128 // We have already pre-calculated the promotion type, so this is trivial. 2129 if (ToType->isIntegerType() && 2130 isCompleteType(From->getBeginLoc(), FromType)) 2131 return Context.hasSameUnqualifiedType( 2132 ToType, FromEnumType->getDecl()->getPromotionType()); 2133 2134 // C++ [conv.prom]p5: 2135 // If the bit-field has an enumerated type, it is treated as any other 2136 // value of that type for promotion purposes. 2137 // 2138 // ... so do not fall through into the bit-field checks below in C++. 2139 if (getLangOpts().CPlusPlus) 2140 return false; 2141 } 2142 2143 // C++0x [conv.prom]p2: 2144 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2145 // to an rvalue a prvalue of the first of the following types that can 2146 // represent all the values of its underlying type: int, unsigned int, 2147 // long int, unsigned long int, long long int, or unsigned long long int. 2148 // If none of the types in that list can represent all the values of its 2149 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2150 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2151 // type. 2152 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2153 ToType->isIntegerType()) { 2154 // Determine whether the type we're converting from is signed or 2155 // unsigned. 2156 bool FromIsSigned = FromType->isSignedIntegerType(); 2157 uint64_t FromSize = Context.getTypeSize(FromType); 2158 2159 // The types we'll try to promote to, in the appropriate 2160 // order. Try each of these types. 2161 QualType PromoteTypes[6] = { 2162 Context.IntTy, Context.UnsignedIntTy, 2163 Context.LongTy, Context.UnsignedLongTy , 2164 Context.LongLongTy, Context.UnsignedLongLongTy 2165 }; 2166 for (int Idx = 0; Idx < 6; ++Idx) { 2167 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2168 if (FromSize < ToSize || 2169 (FromSize == ToSize && 2170 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2171 // We found the type that we can promote to. If this is the 2172 // type we wanted, we have a promotion. Otherwise, no 2173 // promotion. 2174 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2175 } 2176 } 2177 } 2178 2179 // An rvalue for an integral bit-field (9.6) can be converted to an 2180 // rvalue of type int if int can represent all the values of the 2181 // bit-field; otherwise, it can be converted to unsigned int if 2182 // unsigned int can represent all the values of the bit-field. If 2183 // the bit-field is larger yet, no integral promotion applies to 2184 // it. If the bit-field has an enumerated type, it is treated as any 2185 // other value of that type for promotion purposes (C++ 4.5p3). 2186 // FIXME: We should delay checking of bit-fields until we actually perform the 2187 // conversion. 2188 // 2189 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2190 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2191 // bit-fields and those whose underlying type is larger than int) for GCC 2192 // compatibility. 2193 if (From) { 2194 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2195 Optional<llvm::APSInt> BitWidth; 2196 if (FromType->isIntegralType(Context) && 2197 (BitWidth = 2198 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2199 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2200 ToSize = Context.getTypeSize(ToType); 2201 2202 // Are we promoting to an int from a bitfield that fits in an int? 2203 if (*BitWidth < ToSize || 2204 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2205 return To->getKind() == BuiltinType::Int; 2206 } 2207 2208 // Are we promoting to an unsigned int from an unsigned bitfield 2209 // that fits into an unsigned int? 2210 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2211 return To->getKind() == BuiltinType::UInt; 2212 } 2213 2214 return false; 2215 } 2216 } 2217 } 2218 2219 // An rvalue of type bool can be converted to an rvalue of type int, 2220 // with false becoming zero and true becoming one (C++ 4.5p4). 2221 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2222 return true; 2223 } 2224 2225 return false; 2226 } 2227 2228 /// IsFloatingPointPromotion - Determines whether the conversion from 2229 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2230 /// returns true and sets PromotedType to the promoted type. 2231 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2232 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2233 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2234 /// An rvalue of type float can be converted to an rvalue of type 2235 /// double. (C++ 4.6p1). 2236 if (FromBuiltin->getKind() == BuiltinType::Float && 2237 ToBuiltin->getKind() == BuiltinType::Double) 2238 return true; 2239 2240 // C99 6.3.1.5p1: 2241 // When a float is promoted to double or long double, or a 2242 // double is promoted to long double [...]. 2243 if (!getLangOpts().CPlusPlus && 2244 (FromBuiltin->getKind() == BuiltinType::Float || 2245 FromBuiltin->getKind() == BuiltinType::Double) && 2246 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2247 ToBuiltin->getKind() == BuiltinType::Float128)) 2248 return true; 2249 2250 // Half can be promoted to float. 2251 if (!getLangOpts().NativeHalfType && 2252 FromBuiltin->getKind() == BuiltinType::Half && 2253 ToBuiltin->getKind() == BuiltinType::Float) 2254 return true; 2255 } 2256 2257 return false; 2258 } 2259 2260 /// Determine if a conversion is a complex promotion. 2261 /// 2262 /// A complex promotion is defined as a complex -> complex conversion 2263 /// where the conversion between the underlying real types is a 2264 /// floating-point or integral promotion. 2265 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2266 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2267 if (!FromComplex) 2268 return false; 2269 2270 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2271 if (!ToComplex) 2272 return false; 2273 2274 return IsFloatingPointPromotion(FromComplex->getElementType(), 2275 ToComplex->getElementType()) || 2276 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2277 ToComplex->getElementType()); 2278 } 2279 2280 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2281 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2282 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2283 /// if non-empty, will be a pointer to ToType that may or may not have 2284 /// the right set of qualifiers on its pointee. 2285 /// 2286 static QualType 2287 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2288 QualType ToPointee, QualType ToType, 2289 ASTContext &Context, 2290 bool StripObjCLifetime = false) { 2291 assert((FromPtr->getTypeClass() == Type::Pointer || 2292 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2293 "Invalid similarly-qualified pointer type"); 2294 2295 /// Conversions to 'id' subsume cv-qualifier conversions. 2296 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2297 return ToType.getUnqualifiedType(); 2298 2299 QualType CanonFromPointee 2300 = Context.getCanonicalType(FromPtr->getPointeeType()); 2301 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2302 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2303 2304 if (StripObjCLifetime) 2305 Quals.removeObjCLifetime(); 2306 2307 // Exact qualifier match -> return the pointer type we're converting to. 2308 if (CanonToPointee.getLocalQualifiers() == Quals) { 2309 // ToType is exactly what we need. Return it. 2310 if (!ToType.isNull()) 2311 return ToType.getUnqualifiedType(); 2312 2313 // Build a pointer to ToPointee. It has the right qualifiers 2314 // already. 2315 if (isa<ObjCObjectPointerType>(ToType)) 2316 return Context.getObjCObjectPointerType(ToPointee); 2317 return Context.getPointerType(ToPointee); 2318 } 2319 2320 // Just build a canonical type that has the right qualifiers. 2321 QualType QualifiedCanonToPointee 2322 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2323 2324 if (isa<ObjCObjectPointerType>(ToType)) 2325 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2326 return Context.getPointerType(QualifiedCanonToPointee); 2327 } 2328 2329 static bool isNullPointerConstantForConversion(Expr *Expr, 2330 bool InOverloadResolution, 2331 ASTContext &Context) { 2332 // Handle value-dependent integral null pointer constants correctly. 2333 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2334 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2335 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2336 return !InOverloadResolution; 2337 2338 return Expr->isNullPointerConstant(Context, 2339 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2340 : Expr::NPC_ValueDependentIsNull); 2341 } 2342 2343 /// IsPointerConversion - Determines whether the conversion of the 2344 /// expression From, which has the (possibly adjusted) type FromType, 2345 /// can be converted to the type ToType via a pointer conversion (C++ 2346 /// 4.10). If so, returns true and places the converted type (that 2347 /// might differ from ToType in its cv-qualifiers at some level) into 2348 /// ConvertedType. 2349 /// 2350 /// This routine also supports conversions to and from block pointers 2351 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2352 /// pointers to interfaces. FIXME: Once we've determined the 2353 /// appropriate overloading rules for Objective-C, we may want to 2354 /// split the Objective-C checks into a different routine; however, 2355 /// GCC seems to consider all of these conversions to be pointer 2356 /// conversions, so for now they live here. IncompatibleObjC will be 2357 /// set if the conversion is an allowed Objective-C conversion that 2358 /// should result in a warning. 2359 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2360 bool InOverloadResolution, 2361 QualType& ConvertedType, 2362 bool &IncompatibleObjC) { 2363 IncompatibleObjC = false; 2364 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2365 IncompatibleObjC)) 2366 return true; 2367 2368 // Conversion from a null pointer constant to any Objective-C pointer type. 2369 if (ToType->isObjCObjectPointerType() && 2370 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2371 ConvertedType = ToType; 2372 return true; 2373 } 2374 2375 // Blocks: Block pointers can be converted to void*. 2376 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2377 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2378 ConvertedType = ToType; 2379 return true; 2380 } 2381 // Blocks: A null pointer constant can be converted to a block 2382 // pointer type. 2383 if (ToType->isBlockPointerType() && 2384 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2385 ConvertedType = ToType; 2386 return true; 2387 } 2388 2389 // If the left-hand-side is nullptr_t, the right side can be a null 2390 // pointer constant. 2391 if (ToType->isNullPtrType() && 2392 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2393 ConvertedType = ToType; 2394 return true; 2395 } 2396 2397 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2398 if (!ToTypePtr) 2399 return false; 2400 2401 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2402 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2403 ConvertedType = ToType; 2404 return true; 2405 } 2406 2407 // Beyond this point, both types need to be pointers 2408 // , including objective-c pointers. 2409 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2410 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2411 !getLangOpts().ObjCAutoRefCount) { 2412 ConvertedType = BuildSimilarlyQualifiedPointerType( 2413 FromType->getAs<ObjCObjectPointerType>(), 2414 ToPointeeType, 2415 ToType, Context); 2416 return true; 2417 } 2418 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2419 if (!FromTypePtr) 2420 return false; 2421 2422 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2423 2424 // If the unqualified pointee types are the same, this can't be a 2425 // pointer conversion, so don't do all of the work below. 2426 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2427 return false; 2428 2429 // An rvalue of type "pointer to cv T," where T is an object type, 2430 // can be converted to an rvalue of type "pointer to cv void" (C++ 2431 // 4.10p2). 2432 if (FromPointeeType->isIncompleteOrObjectType() && 2433 ToPointeeType->isVoidType()) { 2434 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2435 ToPointeeType, 2436 ToType, Context, 2437 /*StripObjCLifetime=*/true); 2438 return true; 2439 } 2440 2441 // MSVC allows implicit function to void* type conversion. 2442 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2443 ToPointeeType->isVoidType()) { 2444 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2445 ToPointeeType, 2446 ToType, Context); 2447 return true; 2448 } 2449 2450 // When we're overloading in C, we allow a special kind of pointer 2451 // conversion for compatible-but-not-identical pointee types. 2452 if (!getLangOpts().CPlusPlus && 2453 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2454 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2455 ToPointeeType, 2456 ToType, Context); 2457 return true; 2458 } 2459 2460 // C++ [conv.ptr]p3: 2461 // 2462 // An rvalue of type "pointer to cv D," where D is a class type, 2463 // can be converted to an rvalue of type "pointer to cv B," where 2464 // B is a base class (clause 10) of D. If B is an inaccessible 2465 // (clause 11) or ambiguous (10.2) base class of D, a program that 2466 // necessitates this conversion is ill-formed. The result of the 2467 // conversion is a pointer to the base class sub-object of the 2468 // derived class object. The null pointer value is converted to 2469 // the null pointer value of the destination type. 2470 // 2471 // Note that we do not check for ambiguity or inaccessibility 2472 // here. That is handled by CheckPointerConversion. 2473 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2474 ToPointeeType->isRecordType() && 2475 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2476 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2477 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2478 ToPointeeType, 2479 ToType, Context); 2480 return true; 2481 } 2482 2483 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2484 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2485 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2486 ToPointeeType, 2487 ToType, Context); 2488 return true; 2489 } 2490 2491 return false; 2492 } 2493 2494 /// Adopt the given qualifiers for the given type. 2495 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2496 Qualifiers TQs = T.getQualifiers(); 2497 2498 // Check whether qualifiers already match. 2499 if (TQs == Qs) 2500 return T; 2501 2502 if (Qs.compatiblyIncludes(TQs)) 2503 return Context.getQualifiedType(T, Qs); 2504 2505 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2506 } 2507 2508 /// isObjCPointerConversion - Determines whether this is an 2509 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2510 /// with the same arguments and return values. 2511 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2512 QualType& ConvertedType, 2513 bool &IncompatibleObjC) { 2514 if (!getLangOpts().ObjC) 2515 return false; 2516 2517 // The set of qualifiers on the type we're converting from. 2518 Qualifiers FromQualifiers = FromType.getQualifiers(); 2519 2520 // First, we handle all conversions on ObjC object pointer types. 2521 const ObjCObjectPointerType* ToObjCPtr = 2522 ToType->getAs<ObjCObjectPointerType>(); 2523 const ObjCObjectPointerType *FromObjCPtr = 2524 FromType->getAs<ObjCObjectPointerType>(); 2525 2526 if (ToObjCPtr && FromObjCPtr) { 2527 // If the pointee types are the same (ignoring qualifications), 2528 // then this is not a pointer conversion. 2529 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2530 FromObjCPtr->getPointeeType())) 2531 return false; 2532 2533 // Conversion between Objective-C pointers. 2534 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2535 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2536 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2537 if (getLangOpts().CPlusPlus && LHS && RHS && 2538 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2539 FromObjCPtr->getPointeeType())) 2540 return false; 2541 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2542 ToObjCPtr->getPointeeType(), 2543 ToType, Context); 2544 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2545 return true; 2546 } 2547 2548 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2549 // Okay: this is some kind of implicit downcast of Objective-C 2550 // interfaces, which is permitted. However, we're going to 2551 // complain about it. 2552 IncompatibleObjC = true; 2553 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2554 ToObjCPtr->getPointeeType(), 2555 ToType, Context); 2556 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2557 return true; 2558 } 2559 } 2560 // Beyond this point, both types need to be C pointers or block pointers. 2561 QualType ToPointeeType; 2562 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2563 ToPointeeType = ToCPtr->getPointeeType(); 2564 else if (const BlockPointerType *ToBlockPtr = 2565 ToType->getAs<BlockPointerType>()) { 2566 // Objective C++: We're able to convert from a pointer to any object 2567 // to a block pointer type. 2568 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2569 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2570 return true; 2571 } 2572 ToPointeeType = ToBlockPtr->getPointeeType(); 2573 } 2574 else if (FromType->getAs<BlockPointerType>() && 2575 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2576 // Objective C++: We're able to convert from a block pointer type to a 2577 // pointer to any object. 2578 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2579 return true; 2580 } 2581 else 2582 return false; 2583 2584 QualType FromPointeeType; 2585 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2586 FromPointeeType = FromCPtr->getPointeeType(); 2587 else if (const BlockPointerType *FromBlockPtr = 2588 FromType->getAs<BlockPointerType>()) 2589 FromPointeeType = FromBlockPtr->getPointeeType(); 2590 else 2591 return false; 2592 2593 // If we have pointers to pointers, recursively check whether this 2594 // is an Objective-C conversion. 2595 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2596 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2597 IncompatibleObjC)) { 2598 // We always complain about this conversion. 2599 IncompatibleObjC = true; 2600 ConvertedType = Context.getPointerType(ConvertedType); 2601 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2602 return true; 2603 } 2604 // Allow conversion of pointee being objective-c pointer to another one; 2605 // as in I* to id. 2606 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2607 ToPointeeType->getAs<ObjCObjectPointerType>() && 2608 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2609 IncompatibleObjC)) { 2610 2611 ConvertedType = Context.getPointerType(ConvertedType); 2612 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2613 return true; 2614 } 2615 2616 // If we have pointers to functions or blocks, check whether the only 2617 // differences in the argument and result types are in Objective-C 2618 // pointer conversions. If so, we permit the conversion (but 2619 // complain about it). 2620 const FunctionProtoType *FromFunctionType 2621 = FromPointeeType->getAs<FunctionProtoType>(); 2622 const FunctionProtoType *ToFunctionType 2623 = ToPointeeType->getAs<FunctionProtoType>(); 2624 if (FromFunctionType && ToFunctionType) { 2625 // If the function types are exactly the same, this isn't an 2626 // Objective-C pointer conversion. 2627 if (Context.getCanonicalType(FromPointeeType) 2628 == Context.getCanonicalType(ToPointeeType)) 2629 return false; 2630 2631 // Perform the quick checks that will tell us whether these 2632 // function types are obviously different. 2633 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2634 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2635 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2636 return false; 2637 2638 bool HasObjCConversion = false; 2639 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2640 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2641 // Okay, the types match exactly. Nothing to do. 2642 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2643 ToFunctionType->getReturnType(), 2644 ConvertedType, IncompatibleObjC)) { 2645 // Okay, we have an Objective-C pointer conversion. 2646 HasObjCConversion = true; 2647 } else { 2648 // Function types are too different. Abort. 2649 return false; 2650 } 2651 2652 // Check argument types. 2653 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2654 ArgIdx != NumArgs; ++ArgIdx) { 2655 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2656 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2657 if (Context.getCanonicalType(FromArgType) 2658 == Context.getCanonicalType(ToArgType)) { 2659 // Okay, the types match exactly. Nothing to do. 2660 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2661 ConvertedType, IncompatibleObjC)) { 2662 // Okay, we have an Objective-C pointer conversion. 2663 HasObjCConversion = true; 2664 } else { 2665 // Argument types are too different. Abort. 2666 return false; 2667 } 2668 } 2669 2670 if (HasObjCConversion) { 2671 // We had an Objective-C conversion. Allow this pointer 2672 // conversion, but complain about it. 2673 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2674 IncompatibleObjC = true; 2675 return true; 2676 } 2677 } 2678 2679 return false; 2680 } 2681 2682 /// Determine whether this is an Objective-C writeback conversion, 2683 /// used for parameter passing when performing automatic reference counting. 2684 /// 2685 /// \param FromType The type we're converting form. 2686 /// 2687 /// \param ToType The type we're converting to. 2688 /// 2689 /// \param ConvertedType The type that will be produced after applying 2690 /// this conversion. 2691 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2692 QualType &ConvertedType) { 2693 if (!getLangOpts().ObjCAutoRefCount || 2694 Context.hasSameUnqualifiedType(FromType, ToType)) 2695 return false; 2696 2697 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2698 QualType ToPointee; 2699 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2700 ToPointee = ToPointer->getPointeeType(); 2701 else 2702 return false; 2703 2704 Qualifiers ToQuals = ToPointee.getQualifiers(); 2705 if (!ToPointee->isObjCLifetimeType() || 2706 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2707 !ToQuals.withoutObjCLifetime().empty()) 2708 return false; 2709 2710 // Argument must be a pointer to __strong to __weak. 2711 QualType FromPointee; 2712 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2713 FromPointee = FromPointer->getPointeeType(); 2714 else 2715 return false; 2716 2717 Qualifiers FromQuals = FromPointee.getQualifiers(); 2718 if (!FromPointee->isObjCLifetimeType() || 2719 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2720 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2721 return false; 2722 2723 // Make sure that we have compatible qualifiers. 2724 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2725 if (!ToQuals.compatiblyIncludes(FromQuals)) 2726 return false; 2727 2728 // Remove qualifiers from the pointee type we're converting from; they 2729 // aren't used in the compatibility check belong, and we'll be adding back 2730 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2731 FromPointee = FromPointee.getUnqualifiedType(); 2732 2733 // The unqualified form of the pointee types must be compatible. 2734 ToPointee = ToPointee.getUnqualifiedType(); 2735 bool IncompatibleObjC; 2736 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2737 FromPointee = ToPointee; 2738 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2739 IncompatibleObjC)) 2740 return false; 2741 2742 /// Construct the type we're converting to, which is a pointer to 2743 /// __autoreleasing pointee. 2744 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2745 ConvertedType = Context.getPointerType(FromPointee); 2746 return true; 2747 } 2748 2749 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2750 QualType& ConvertedType) { 2751 QualType ToPointeeType; 2752 if (const BlockPointerType *ToBlockPtr = 2753 ToType->getAs<BlockPointerType>()) 2754 ToPointeeType = ToBlockPtr->getPointeeType(); 2755 else 2756 return false; 2757 2758 QualType FromPointeeType; 2759 if (const BlockPointerType *FromBlockPtr = 2760 FromType->getAs<BlockPointerType>()) 2761 FromPointeeType = FromBlockPtr->getPointeeType(); 2762 else 2763 return false; 2764 // We have pointer to blocks, check whether the only 2765 // differences in the argument and result types are in Objective-C 2766 // pointer conversions. If so, we permit the conversion. 2767 2768 const FunctionProtoType *FromFunctionType 2769 = FromPointeeType->getAs<FunctionProtoType>(); 2770 const FunctionProtoType *ToFunctionType 2771 = ToPointeeType->getAs<FunctionProtoType>(); 2772 2773 if (!FromFunctionType || !ToFunctionType) 2774 return false; 2775 2776 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2777 return true; 2778 2779 // Perform the quick checks that will tell us whether these 2780 // function types are obviously different. 2781 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2782 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2783 return false; 2784 2785 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2786 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2787 if (FromEInfo != ToEInfo) 2788 return false; 2789 2790 bool IncompatibleObjC = false; 2791 if (Context.hasSameType(FromFunctionType->getReturnType(), 2792 ToFunctionType->getReturnType())) { 2793 // Okay, the types match exactly. Nothing to do. 2794 } else { 2795 QualType RHS = FromFunctionType->getReturnType(); 2796 QualType LHS = ToFunctionType->getReturnType(); 2797 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2798 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2799 LHS = LHS.getUnqualifiedType(); 2800 2801 if (Context.hasSameType(RHS,LHS)) { 2802 // OK exact match. 2803 } else if (isObjCPointerConversion(RHS, LHS, 2804 ConvertedType, IncompatibleObjC)) { 2805 if (IncompatibleObjC) 2806 return false; 2807 // Okay, we have an Objective-C pointer conversion. 2808 } 2809 else 2810 return false; 2811 } 2812 2813 // Check argument types. 2814 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2815 ArgIdx != NumArgs; ++ArgIdx) { 2816 IncompatibleObjC = false; 2817 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2818 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2819 if (Context.hasSameType(FromArgType, ToArgType)) { 2820 // Okay, the types match exactly. Nothing to do. 2821 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2822 ConvertedType, IncompatibleObjC)) { 2823 if (IncompatibleObjC) 2824 return false; 2825 // Okay, we have an Objective-C pointer conversion. 2826 } else 2827 // Argument types are too different. Abort. 2828 return false; 2829 } 2830 2831 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2832 bool CanUseToFPT, CanUseFromFPT; 2833 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2834 CanUseToFPT, CanUseFromFPT, 2835 NewParamInfos)) 2836 return false; 2837 2838 ConvertedType = ToType; 2839 return true; 2840 } 2841 2842 enum { 2843 ft_default, 2844 ft_different_class, 2845 ft_parameter_arity, 2846 ft_parameter_mismatch, 2847 ft_return_type, 2848 ft_qualifer_mismatch, 2849 ft_noexcept 2850 }; 2851 2852 /// Attempts to get the FunctionProtoType from a Type. Handles 2853 /// MemberFunctionPointers properly. 2854 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2855 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2856 return FPT; 2857 2858 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2859 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2860 2861 return nullptr; 2862 } 2863 2864 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2865 /// function types. Catches different number of parameter, mismatch in 2866 /// parameter types, and different return types. 2867 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2868 QualType FromType, QualType ToType) { 2869 // If either type is not valid, include no extra info. 2870 if (FromType.isNull() || ToType.isNull()) { 2871 PDiag << ft_default; 2872 return; 2873 } 2874 2875 // Get the function type from the pointers. 2876 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2877 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2878 *ToMember = ToType->castAs<MemberPointerType>(); 2879 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2880 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2881 << QualType(FromMember->getClass(), 0); 2882 return; 2883 } 2884 FromType = FromMember->getPointeeType(); 2885 ToType = ToMember->getPointeeType(); 2886 } 2887 2888 if (FromType->isPointerType()) 2889 FromType = FromType->getPointeeType(); 2890 if (ToType->isPointerType()) 2891 ToType = ToType->getPointeeType(); 2892 2893 // Remove references. 2894 FromType = FromType.getNonReferenceType(); 2895 ToType = ToType.getNonReferenceType(); 2896 2897 // Don't print extra info for non-specialized template functions. 2898 if (FromType->isInstantiationDependentType() && 2899 !FromType->getAs<TemplateSpecializationType>()) { 2900 PDiag << ft_default; 2901 return; 2902 } 2903 2904 // No extra info for same types. 2905 if (Context.hasSameType(FromType, ToType)) { 2906 PDiag << ft_default; 2907 return; 2908 } 2909 2910 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2911 *ToFunction = tryGetFunctionProtoType(ToType); 2912 2913 // Both types need to be function types. 2914 if (!FromFunction || !ToFunction) { 2915 PDiag << ft_default; 2916 return; 2917 } 2918 2919 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2920 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2921 << FromFunction->getNumParams(); 2922 return; 2923 } 2924 2925 // Handle different parameter types. 2926 unsigned ArgPos; 2927 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2928 PDiag << ft_parameter_mismatch << ArgPos + 1 2929 << ToFunction->getParamType(ArgPos) 2930 << FromFunction->getParamType(ArgPos); 2931 return; 2932 } 2933 2934 // Handle different return type. 2935 if (!Context.hasSameType(FromFunction->getReturnType(), 2936 ToFunction->getReturnType())) { 2937 PDiag << ft_return_type << ToFunction->getReturnType() 2938 << FromFunction->getReturnType(); 2939 return; 2940 } 2941 2942 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2943 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2944 << FromFunction->getMethodQuals(); 2945 return; 2946 } 2947 2948 // Handle exception specification differences on canonical type (in C++17 2949 // onwards). 2950 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2951 ->isNothrow() != 2952 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2953 ->isNothrow()) { 2954 PDiag << ft_noexcept; 2955 return; 2956 } 2957 2958 // Unable to find a difference, so add no extra info. 2959 PDiag << ft_default; 2960 } 2961 2962 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2963 /// for equality of their argument types. Caller has already checked that 2964 /// they have same number of arguments. If the parameters are different, 2965 /// ArgPos will have the parameter index of the first different parameter. 2966 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2967 const FunctionProtoType *NewType, 2968 unsigned *ArgPos) { 2969 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2970 N = NewType->param_type_begin(), 2971 E = OldType->param_type_end(); 2972 O && (O != E); ++O, ++N) { 2973 // Ignore address spaces in pointee type. This is to disallow overloading 2974 // on __ptr32/__ptr64 address spaces. 2975 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2976 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2977 2978 if (!Context.hasSameType(Old, New)) { 2979 if (ArgPos) 2980 *ArgPos = O - OldType->param_type_begin(); 2981 return false; 2982 } 2983 } 2984 return true; 2985 } 2986 2987 /// CheckPointerConversion - Check the pointer conversion from the 2988 /// expression From to the type ToType. This routine checks for 2989 /// ambiguous or inaccessible derived-to-base pointer 2990 /// conversions for which IsPointerConversion has already returned 2991 /// true. It returns true and produces a diagnostic if there was an 2992 /// error, or returns false otherwise. 2993 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2994 CastKind &Kind, 2995 CXXCastPath& BasePath, 2996 bool IgnoreBaseAccess, 2997 bool Diagnose) { 2998 QualType FromType = From->getType(); 2999 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3000 3001 Kind = CK_BitCast; 3002 3003 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3004 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3005 Expr::NPCK_ZeroExpression) { 3006 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3007 DiagRuntimeBehavior(From->getExprLoc(), From, 3008 PDiag(diag::warn_impcast_bool_to_null_pointer) 3009 << ToType << From->getSourceRange()); 3010 else if (!isUnevaluatedContext()) 3011 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3012 << ToType << From->getSourceRange(); 3013 } 3014 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3015 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3016 QualType FromPointeeType = FromPtrType->getPointeeType(), 3017 ToPointeeType = ToPtrType->getPointeeType(); 3018 3019 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3020 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3021 // We must have a derived-to-base conversion. Check an 3022 // ambiguous or inaccessible conversion. 3023 unsigned InaccessibleID = 0; 3024 unsigned AmbiguousID = 0; 3025 if (Diagnose) { 3026 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3027 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3028 } 3029 if (CheckDerivedToBaseConversion( 3030 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3031 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3032 &BasePath, IgnoreBaseAccess)) 3033 return true; 3034 3035 // The conversion was successful. 3036 Kind = CK_DerivedToBase; 3037 } 3038 3039 if (Diagnose && !IsCStyleOrFunctionalCast && 3040 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3041 assert(getLangOpts().MSVCCompat && 3042 "this should only be possible with MSVCCompat!"); 3043 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3044 << From->getSourceRange(); 3045 } 3046 } 3047 } else if (const ObjCObjectPointerType *ToPtrType = 3048 ToType->getAs<ObjCObjectPointerType>()) { 3049 if (const ObjCObjectPointerType *FromPtrType = 3050 FromType->getAs<ObjCObjectPointerType>()) { 3051 // Objective-C++ conversions are always okay. 3052 // FIXME: We should have a different class of conversions for the 3053 // Objective-C++ implicit conversions. 3054 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3055 return false; 3056 } else if (FromType->isBlockPointerType()) { 3057 Kind = CK_BlockPointerToObjCPointerCast; 3058 } else { 3059 Kind = CK_CPointerToObjCPointerCast; 3060 } 3061 } else if (ToType->isBlockPointerType()) { 3062 if (!FromType->isBlockPointerType()) 3063 Kind = CK_AnyPointerToBlockPointerCast; 3064 } 3065 3066 // We shouldn't fall into this case unless it's valid for other 3067 // reasons. 3068 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3069 Kind = CK_NullToPointer; 3070 3071 return false; 3072 } 3073 3074 /// IsMemberPointerConversion - Determines whether the conversion of the 3075 /// expression From, which has the (possibly adjusted) type FromType, can be 3076 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3077 /// If so, returns true and places the converted type (that might differ from 3078 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3079 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3080 QualType ToType, 3081 bool InOverloadResolution, 3082 QualType &ConvertedType) { 3083 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3084 if (!ToTypePtr) 3085 return false; 3086 3087 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3088 if (From->isNullPointerConstant(Context, 3089 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3090 : Expr::NPC_ValueDependentIsNull)) { 3091 ConvertedType = ToType; 3092 return true; 3093 } 3094 3095 // Otherwise, both types have to be member pointers. 3096 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3097 if (!FromTypePtr) 3098 return false; 3099 3100 // A pointer to member of B can be converted to a pointer to member of D, 3101 // where D is derived from B (C++ 4.11p2). 3102 QualType FromClass(FromTypePtr->getClass(), 0); 3103 QualType ToClass(ToTypePtr->getClass(), 0); 3104 3105 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3106 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3107 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3108 ToClass.getTypePtr()); 3109 return true; 3110 } 3111 3112 return false; 3113 } 3114 3115 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3116 /// expression From to the type ToType. This routine checks for ambiguous or 3117 /// virtual or inaccessible base-to-derived member pointer conversions 3118 /// for which IsMemberPointerConversion has already returned true. It returns 3119 /// true and produces a diagnostic if there was an error, or returns false 3120 /// otherwise. 3121 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3122 CastKind &Kind, 3123 CXXCastPath &BasePath, 3124 bool IgnoreBaseAccess) { 3125 QualType FromType = From->getType(); 3126 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3127 if (!FromPtrType) { 3128 // This must be a null pointer to member pointer conversion 3129 assert(From->isNullPointerConstant(Context, 3130 Expr::NPC_ValueDependentIsNull) && 3131 "Expr must be null pointer constant!"); 3132 Kind = CK_NullToMemberPointer; 3133 return false; 3134 } 3135 3136 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3137 assert(ToPtrType && "No member pointer cast has a target type " 3138 "that is not a member pointer."); 3139 3140 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3141 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3142 3143 // FIXME: What about dependent types? 3144 assert(FromClass->isRecordType() && "Pointer into non-class."); 3145 assert(ToClass->isRecordType() && "Pointer into non-class."); 3146 3147 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3148 /*DetectVirtual=*/true); 3149 bool DerivationOkay = 3150 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3151 assert(DerivationOkay && 3152 "Should not have been called if derivation isn't OK."); 3153 (void)DerivationOkay; 3154 3155 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3156 getUnqualifiedType())) { 3157 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3158 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3159 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3160 return true; 3161 } 3162 3163 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3164 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3165 << FromClass << ToClass << QualType(VBase, 0) 3166 << From->getSourceRange(); 3167 return true; 3168 } 3169 3170 if (!IgnoreBaseAccess) 3171 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3172 Paths.front(), 3173 diag::err_downcast_from_inaccessible_base); 3174 3175 // Must be a base to derived member conversion. 3176 BuildBasePathArray(Paths, BasePath); 3177 Kind = CK_BaseToDerivedMemberPointer; 3178 return false; 3179 } 3180 3181 /// Determine whether the lifetime conversion between the two given 3182 /// qualifiers sets is nontrivial. 3183 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3184 Qualifiers ToQuals) { 3185 // Converting anything to const __unsafe_unretained is trivial. 3186 if (ToQuals.hasConst() && 3187 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3188 return false; 3189 3190 return true; 3191 } 3192 3193 /// Perform a single iteration of the loop for checking if a qualification 3194 /// conversion is valid. 3195 /// 3196 /// Specifically, check whether any change between the qualifiers of \p 3197 /// FromType and \p ToType is permissible, given knowledge about whether every 3198 /// outer layer is const-qualified. 3199 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3200 bool CStyle, bool IsTopLevel, 3201 bool &PreviousToQualsIncludeConst, 3202 bool &ObjCLifetimeConversion) { 3203 Qualifiers FromQuals = FromType.getQualifiers(); 3204 Qualifiers ToQuals = ToType.getQualifiers(); 3205 3206 // Ignore __unaligned qualifier if this type is void. 3207 if (ToType.getUnqualifiedType()->isVoidType()) 3208 FromQuals.removeUnaligned(); 3209 3210 // Objective-C ARC: 3211 // Check Objective-C lifetime conversions. 3212 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3213 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3214 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3215 ObjCLifetimeConversion = true; 3216 FromQuals.removeObjCLifetime(); 3217 ToQuals.removeObjCLifetime(); 3218 } else { 3219 // Qualification conversions cannot cast between different 3220 // Objective-C lifetime qualifiers. 3221 return false; 3222 } 3223 } 3224 3225 // Allow addition/removal of GC attributes but not changing GC attributes. 3226 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3227 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3228 FromQuals.removeObjCGCAttr(); 3229 ToQuals.removeObjCGCAttr(); 3230 } 3231 3232 // -- for every j > 0, if const is in cv 1,j then const is in cv 3233 // 2,j, and similarly for volatile. 3234 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3235 return false; 3236 3237 // If address spaces mismatch: 3238 // - in top level it is only valid to convert to addr space that is a 3239 // superset in all cases apart from C-style casts where we allow 3240 // conversions between overlapping address spaces. 3241 // - in non-top levels it is not a valid conversion. 3242 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3243 (!IsTopLevel || 3244 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3245 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3246 return false; 3247 3248 // -- if the cv 1,j and cv 2,j are different, then const is in 3249 // every cv for 0 < k < j. 3250 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3251 !PreviousToQualsIncludeConst) 3252 return false; 3253 3254 // Keep track of whether all prior cv-qualifiers in the "to" type 3255 // include const. 3256 PreviousToQualsIncludeConst = 3257 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3258 return true; 3259 } 3260 3261 /// IsQualificationConversion - Determines whether the conversion from 3262 /// an rvalue of type FromType to ToType is a qualification conversion 3263 /// (C++ 4.4). 3264 /// 3265 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3266 /// when the qualification conversion involves a change in the Objective-C 3267 /// object lifetime. 3268 bool 3269 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3270 bool CStyle, bool &ObjCLifetimeConversion) { 3271 FromType = Context.getCanonicalType(FromType); 3272 ToType = Context.getCanonicalType(ToType); 3273 ObjCLifetimeConversion = false; 3274 3275 // If FromType and ToType are the same type, this is not a 3276 // qualification conversion. 3277 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3278 return false; 3279 3280 // (C++ 4.4p4): 3281 // A conversion can add cv-qualifiers at levels other than the first 3282 // in multi-level pointers, subject to the following rules: [...] 3283 bool PreviousToQualsIncludeConst = true; 3284 bool UnwrappedAnyPointer = false; 3285 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3286 if (!isQualificationConversionStep( 3287 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3288 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3289 return false; 3290 UnwrappedAnyPointer = true; 3291 } 3292 3293 // We are left with FromType and ToType being the pointee types 3294 // after unwrapping the original FromType and ToType the same number 3295 // of times. If we unwrapped any pointers, and if FromType and 3296 // ToType have the same unqualified type (since we checked 3297 // qualifiers above), then this is a qualification conversion. 3298 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3299 } 3300 3301 /// - Determine whether this is a conversion from a scalar type to an 3302 /// atomic type. 3303 /// 3304 /// If successful, updates \c SCS's second and third steps in the conversion 3305 /// sequence to finish the conversion. 3306 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3307 bool InOverloadResolution, 3308 StandardConversionSequence &SCS, 3309 bool CStyle) { 3310 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3311 if (!ToAtomic) 3312 return false; 3313 3314 StandardConversionSequence InnerSCS; 3315 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3316 InOverloadResolution, InnerSCS, 3317 CStyle, /*AllowObjCWritebackConversion=*/false)) 3318 return false; 3319 3320 SCS.Second = InnerSCS.Second; 3321 SCS.setToType(1, InnerSCS.getToType(1)); 3322 SCS.Third = InnerSCS.Third; 3323 SCS.QualificationIncludesObjCLifetime 3324 = InnerSCS.QualificationIncludesObjCLifetime; 3325 SCS.setToType(2, InnerSCS.getToType(2)); 3326 return true; 3327 } 3328 3329 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3330 CXXConstructorDecl *Constructor, 3331 QualType Type) { 3332 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3333 if (CtorType->getNumParams() > 0) { 3334 QualType FirstArg = CtorType->getParamType(0); 3335 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3336 return true; 3337 } 3338 return false; 3339 } 3340 3341 static OverloadingResult 3342 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3343 CXXRecordDecl *To, 3344 UserDefinedConversionSequence &User, 3345 OverloadCandidateSet &CandidateSet, 3346 bool AllowExplicit) { 3347 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3348 for (auto *D : S.LookupConstructors(To)) { 3349 auto Info = getConstructorInfo(D); 3350 if (!Info) 3351 continue; 3352 3353 bool Usable = !Info.Constructor->isInvalidDecl() && 3354 S.isInitListConstructor(Info.Constructor); 3355 if (Usable) { 3356 // If the first argument is (a reference to) the target type, 3357 // suppress conversions. 3358 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3359 S.Context, Info.Constructor, ToType); 3360 if (Info.ConstructorTmpl) 3361 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3362 /*ExplicitArgs*/ nullptr, From, 3363 CandidateSet, SuppressUserConversions, 3364 /*PartialOverloading*/ false, 3365 AllowExplicit); 3366 else 3367 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3368 CandidateSet, SuppressUserConversions, 3369 /*PartialOverloading*/ false, AllowExplicit); 3370 } 3371 } 3372 3373 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3374 3375 OverloadCandidateSet::iterator Best; 3376 switch (auto Result = 3377 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3378 case OR_Deleted: 3379 case OR_Success: { 3380 // Record the standard conversion we used and the conversion function. 3381 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3382 QualType ThisType = Constructor->getThisType(); 3383 // Initializer lists don't have conversions as such. 3384 User.Before.setAsIdentityConversion(); 3385 User.HadMultipleCandidates = HadMultipleCandidates; 3386 User.ConversionFunction = Constructor; 3387 User.FoundConversionFunction = Best->FoundDecl; 3388 User.After.setAsIdentityConversion(); 3389 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3390 User.After.setAllToTypes(ToType); 3391 return Result; 3392 } 3393 3394 case OR_No_Viable_Function: 3395 return OR_No_Viable_Function; 3396 case OR_Ambiguous: 3397 return OR_Ambiguous; 3398 } 3399 3400 llvm_unreachable("Invalid OverloadResult!"); 3401 } 3402 3403 /// Determines whether there is a user-defined conversion sequence 3404 /// (C++ [over.ics.user]) that converts expression From to the type 3405 /// ToType. If such a conversion exists, User will contain the 3406 /// user-defined conversion sequence that performs such a conversion 3407 /// and this routine will return true. Otherwise, this routine returns 3408 /// false and User is unspecified. 3409 /// 3410 /// \param AllowExplicit true if the conversion should consider C++0x 3411 /// "explicit" conversion functions as well as non-explicit conversion 3412 /// functions (C++0x [class.conv.fct]p2). 3413 /// 3414 /// \param AllowObjCConversionOnExplicit true if the conversion should 3415 /// allow an extra Objective-C pointer conversion on uses of explicit 3416 /// constructors. Requires \c AllowExplicit to also be set. 3417 static OverloadingResult 3418 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3419 UserDefinedConversionSequence &User, 3420 OverloadCandidateSet &CandidateSet, 3421 AllowedExplicit AllowExplicit, 3422 bool AllowObjCConversionOnExplicit) { 3423 assert(AllowExplicit != AllowedExplicit::None || 3424 !AllowObjCConversionOnExplicit); 3425 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3426 3427 // Whether we will only visit constructors. 3428 bool ConstructorsOnly = false; 3429 3430 // If the type we are conversion to is a class type, enumerate its 3431 // constructors. 3432 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3433 // C++ [over.match.ctor]p1: 3434 // When objects of class type are direct-initialized (8.5), or 3435 // copy-initialized from an expression of the same or a 3436 // derived class type (8.5), overload resolution selects the 3437 // constructor. [...] For copy-initialization, the candidate 3438 // functions are all the converting constructors (12.3.1) of 3439 // that class. The argument list is the expression-list within 3440 // the parentheses of the initializer. 3441 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3442 (From->getType()->getAs<RecordType>() && 3443 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3444 ConstructorsOnly = true; 3445 3446 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3447 // We're not going to find any constructors. 3448 } else if (CXXRecordDecl *ToRecordDecl 3449 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3450 3451 Expr **Args = &From; 3452 unsigned NumArgs = 1; 3453 bool ListInitializing = false; 3454 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3455 // But first, see if there is an init-list-constructor that will work. 3456 OverloadingResult Result = IsInitializerListConstructorConversion( 3457 S, From, ToType, ToRecordDecl, User, CandidateSet, 3458 AllowExplicit == AllowedExplicit::All); 3459 if (Result != OR_No_Viable_Function) 3460 return Result; 3461 // Never mind. 3462 CandidateSet.clear( 3463 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3464 3465 // If we're list-initializing, we pass the individual elements as 3466 // arguments, not the entire list. 3467 Args = InitList->getInits(); 3468 NumArgs = InitList->getNumInits(); 3469 ListInitializing = true; 3470 } 3471 3472 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3473 auto Info = getConstructorInfo(D); 3474 if (!Info) 3475 continue; 3476 3477 bool Usable = !Info.Constructor->isInvalidDecl(); 3478 if (!ListInitializing) 3479 Usable = Usable && Info.Constructor->isConvertingConstructor( 3480 /*AllowExplicit*/ true); 3481 if (Usable) { 3482 bool SuppressUserConversions = !ConstructorsOnly; 3483 if (SuppressUserConversions && ListInitializing) { 3484 SuppressUserConversions = false; 3485 if (NumArgs == 1) { 3486 // If the first argument is (a reference to) the target type, 3487 // suppress conversions. 3488 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3489 S.Context, Info.Constructor, ToType); 3490 } 3491 } 3492 if (Info.ConstructorTmpl) 3493 S.AddTemplateOverloadCandidate( 3494 Info.ConstructorTmpl, Info.FoundDecl, 3495 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3496 CandidateSet, SuppressUserConversions, 3497 /*PartialOverloading*/ false, 3498 AllowExplicit == AllowedExplicit::All); 3499 else 3500 // Allow one user-defined conversion when user specifies a 3501 // From->ToType conversion via an static cast (c-style, etc). 3502 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3503 llvm::makeArrayRef(Args, NumArgs), 3504 CandidateSet, SuppressUserConversions, 3505 /*PartialOverloading*/ false, 3506 AllowExplicit == AllowedExplicit::All); 3507 } 3508 } 3509 } 3510 } 3511 3512 // Enumerate conversion functions, if we're allowed to. 3513 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3514 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3515 // No conversion functions from incomplete types. 3516 } else if (const RecordType *FromRecordType = 3517 From->getType()->getAs<RecordType>()) { 3518 if (CXXRecordDecl *FromRecordDecl 3519 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3520 // Add all of the conversion functions as candidates. 3521 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3522 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3523 DeclAccessPair FoundDecl = I.getPair(); 3524 NamedDecl *D = FoundDecl.getDecl(); 3525 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3526 if (isa<UsingShadowDecl>(D)) 3527 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3528 3529 CXXConversionDecl *Conv; 3530 FunctionTemplateDecl *ConvTemplate; 3531 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3532 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3533 else 3534 Conv = cast<CXXConversionDecl>(D); 3535 3536 if (ConvTemplate) 3537 S.AddTemplateConversionCandidate( 3538 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3539 CandidateSet, AllowObjCConversionOnExplicit, 3540 AllowExplicit != AllowedExplicit::None); 3541 else 3542 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3543 CandidateSet, AllowObjCConversionOnExplicit, 3544 AllowExplicit != AllowedExplicit::None); 3545 } 3546 } 3547 } 3548 3549 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3550 3551 OverloadCandidateSet::iterator Best; 3552 switch (auto Result = 3553 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3554 case OR_Success: 3555 case OR_Deleted: 3556 // Record the standard conversion we used and the conversion function. 3557 if (CXXConstructorDecl *Constructor 3558 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3559 // C++ [over.ics.user]p1: 3560 // If the user-defined conversion is specified by a 3561 // constructor (12.3.1), the initial standard conversion 3562 // sequence converts the source type to the type required by 3563 // the argument of the constructor. 3564 // 3565 QualType ThisType = Constructor->getThisType(); 3566 if (isa<InitListExpr>(From)) { 3567 // Initializer lists don't have conversions as such. 3568 User.Before.setAsIdentityConversion(); 3569 } else { 3570 if (Best->Conversions[0].isEllipsis()) 3571 User.EllipsisConversion = true; 3572 else { 3573 User.Before = Best->Conversions[0].Standard; 3574 User.EllipsisConversion = false; 3575 } 3576 } 3577 User.HadMultipleCandidates = HadMultipleCandidates; 3578 User.ConversionFunction = Constructor; 3579 User.FoundConversionFunction = Best->FoundDecl; 3580 User.After.setAsIdentityConversion(); 3581 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3582 User.After.setAllToTypes(ToType); 3583 return Result; 3584 } 3585 if (CXXConversionDecl *Conversion 3586 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3587 // C++ [over.ics.user]p1: 3588 // 3589 // [...] If the user-defined conversion is specified by a 3590 // conversion function (12.3.2), the initial standard 3591 // conversion sequence converts the source type to the 3592 // implicit object parameter of the conversion function. 3593 User.Before = Best->Conversions[0].Standard; 3594 User.HadMultipleCandidates = HadMultipleCandidates; 3595 User.ConversionFunction = Conversion; 3596 User.FoundConversionFunction = Best->FoundDecl; 3597 User.EllipsisConversion = false; 3598 3599 // C++ [over.ics.user]p2: 3600 // The second standard conversion sequence converts the 3601 // result of the user-defined conversion to the target type 3602 // for the sequence. Since an implicit conversion sequence 3603 // is an initialization, the special rules for 3604 // initialization by user-defined conversion apply when 3605 // selecting the best user-defined conversion for a 3606 // user-defined conversion sequence (see 13.3.3 and 3607 // 13.3.3.1). 3608 User.After = Best->FinalConversion; 3609 return Result; 3610 } 3611 llvm_unreachable("Not a constructor or conversion function?"); 3612 3613 case OR_No_Viable_Function: 3614 return OR_No_Viable_Function; 3615 3616 case OR_Ambiguous: 3617 return OR_Ambiguous; 3618 } 3619 3620 llvm_unreachable("Invalid OverloadResult!"); 3621 } 3622 3623 bool 3624 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3625 ImplicitConversionSequence ICS; 3626 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3627 OverloadCandidateSet::CSK_Normal); 3628 OverloadingResult OvResult = 3629 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3630 CandidateSet, AllowedExplicit::None, false); 3631 3632 if (!(OvResult == OR_Ambiguous || 3633 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3634 return false; 3635 3636 auto Cands = CandidateSet.CompleteCandidates( 3637 *this, 3638 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3639 From); 3640 if (OvResult == OR_Ambiguous) 3641 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3642 << From->getType() << ToType << From->getSourceRange(); 3643 else { // OR_No_Viable_Function && !CandidateSet.empty() 3644 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3645 diag::err_typecheck_nonviable_condition_incomplete, 3646 From->getType(), From->getSourceRange())) 3647 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3648 << false << From->getType() << From->getSourceRange() << ToType; 3649 } 3650 3651 CandidateSet.NoteCandidates( 3652 *this, From, Cands); 3653 return true; 3654 } 3655 3656 /// Compare the user-defined conversion functions or constructors 3657 /// of two user-defined conversion sequences to determine whether any ordering 3658 /// is possible. 3659 static ImplicitConversionSequence::CompareKind 3660 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3661 FunctionDecl *Function2) { 3662 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3663 return ImplicitConversionSequence::Indistinguishable; 3664 3665 // Objective-C++: 3666 // If both conversion functions are implicitly-declared conversions from 3667 // a lambda closure type to a function pointer and a block pointer, 3668 // respectively, always prefer the conversion to a function pointer, 3669 // because the function pointer is more lightweight and is more likely 3670 // to keep code working. 3671 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3672 if (!Conv1) 3673 return ImplicitConversionSequence::Indistinguishable; 3674 3675 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3676 if (!Conv2) 3677 return ImplicitConversionSequence::Indistinguishable; 3678 3679 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3680 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3681 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3682 if (Block1 != Block2) 3683 return Block1 ? ImplicitConversionSequence::Worse 3684 : ImplicitConversionSequence::Better; 3685 } 3686 3687 return ImplicitConversionSequence::Indistinguishable; 3688 } 3689 3690 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3691 const ImplicitConversionSequence &ICS) { 3692 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3693 (ICS.isUserDefined() && 3694 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3695 } 3696 3697 /// CompareImplicitConversionSequences - Compare two implicit 3698 /// conversion sequences to determine whether one is better than the 3699 /// other or if they are indistinguishable (C++ 13.3.3.2). 3700 static ImplicitConversionSequence::CompareKind 3701 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3702 const ImplicitConversionSequence& ICS1, 3703 const ImplicitConversionSequence& ICS2) 3704 { 3705 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3706 // conversion sequences (as defined in 13.3.3.1) 3707 // -- a standard conversion sequence (13.3.3.1.1) is a better 3708 // conversion sequence than a user-defined conversion sequence or 3709 // an ellipsis conversion sequence, and 3710 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3711 // conversion sequence than an ellipsis conversion sequence 3712 // (13.3.3.1.3). 3713 // 3714 // C++0x [over.best.ics]p10: 3715 // For the purpose of ranking implicit conversion sequences as 3716 // described in 13.3.3.2, the ambiguous conversion sequence is 3717 // treated as a user-defined sequence that is indistinguishable 3718 // from any other user-defined conversion sequence. 3719 3720 // String literal to 'char *' conversion has been deprecated in C++03. It has 3721 // been removed from C++11. We still accept this conversion, if it happens at 3722 // the best viable function. Otherwise, this conversion is considered worse 3723 // than ellipsis conversion. Consider this as an extension; this is not in the 3724 // standard. For example: 3725 // 3726 // int &f(...); // #1 3727 // void f(char*); // #2 3728 // void g() { int &r = f("foo"); } 3729 // 3730 // In C++03, we pick #2 as the best viable function. 3731 // In C++11, we pick #1 as the best viable function, because ellipsis 3732 // conversion is better than string-literal to char* conversion (since there 3733 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3734 // convert arguments, #2 would be the best viable function in C++11. 3735 // If the best viable function has this conversion, a warning will be issued 3736 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3737 3738 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3739 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3740 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3741 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3742 ? ImplicitConversionSequence::Worse 3743 : ImplicitConversionSequence::Better; 3744 3745 if (ICS1.getKindRank() < ICS2.getKindRank()) 3746 return ImplicitConversionSequence::Better; 3747 if (ICS2.getKindRank() < ICS1.getKindRank()) 3748 return ImplicitConversionSequence::Worse; 3749 3750 // The following checks require both conversion sequences to be of 3751 // the same kind. 3752 if (ICS1.getKind() != ICS2.getKind()) 3753 return ImplicitConversionSequence::Indistinguishable; 3754 3755 ImplicitConversionSequence::CompareKind Result = 3756 ImplicitConversionSequence::Indistinguishable; 3757 3758 // Two implicit conversion sequences of the same form are 3759 // indistinguishable conversion sequences unless one of the 3760 // following rules apply: (C++ 13.3.3.2p3): 3761 3762 // List-initialization sequence L1 is a better conversion sequence than 3763 // list-initialization sequence L2 if: 3764 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3765 // if not that, 3766 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3767 // and N1 is smaller than N2., 3768 // even if one of the other rules in this paragraph would otherwise apply. 3769 if (!ICS1.isBad()) { 3770 if (ICS1.isStdInitializerListElement() && 3771 !ICS2.isStdInitializerListElement()) 3772 return ImplicitConversionSequence::Better; 3773 if (!ICS1.isStdInitializerListElement() && 3774 ICS2.isStdInitializerListElement()) 3775 return ImplicitConversionSequence::Worse; 3776 } 3777 3778 if (ICS1.isStandard()) 3779 // Standard conversion sequence S1 is a better conversion sequence than 3780 // standard conversion sequence S2 if [...] 3781 Result = CompareStandardConversionSequences(S, Loc, 3782 ICS1.Standard, ICS2.Standard); 3783 else if (ICS1.isUserDefined()) { 3784 // User-defined conversion sequence U1 is a better conversion 3785 // sequence than another user-defined conversion sequence U2 if 3786 // they contain the same user-defined conversion function or 3787 // constructor and if the second standard conversion sequence of 3788 // U1 is better than the second standard conversion sequence of 3789 // U2 (C++ 13.3.3.2p3). 3790 if (ICS1.UserDefined.ConversionFunction == 3791 ICS2.UserDefined.ConversionFunction) 3792 Result = CompareStandardConversionSequences(S, Loc, 3793 ICS1.UserDefined.After, 3794 ICS2.UserDefined.After); 3795 else 3796 Result = compareConversionFunctions(S, 3797 ICS1.UserDefined.ConversionFunction, 3798 ICS2.UserDefined.ConversionFunction); 3799 } 3800 3801 return Result; 3802 } 3803 3804 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3805 // determine if one is a proper subset of the other. 3806 static ImplicitConversionSequence::CompareKind 3807 compareStandardConversionSubsets(ASTContext &Context, 3808 const StandardConversionSequence& SCS1, 3809 const StandardConversionSequence& SCS2) { 3810 ImplicitConversionSequence::CompareKind Result 3811 = ImplicitConversionSequence::Indistinguishable; 3812 3813 // the identity conversion sequence is considered to be a subsequence of 3814 // any non-identity conversion sequence 3815 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3816 return ImplicitConversionSequence::Better; 3817 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3818 return ImplicitConversionSequence::Worse; 3819 3820 if (SCS1.Second != SCS2.Second) { 3821 if (SCS1.Second == ICK_Identity) 3822 Result = ImplicitConversionSequence::Better; 3823 else if (SCS2.Second == ICK_Identity) 3824 Result = ImplicitConversionSequence::Worse; 3825 else 3826 return ImplicitConversionSequence::Indistinguishable; 3827 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3828 return ImplicitConversionSequence::Indistinguishable; 3829 3830 if (SCS1.Third == SCS2.Third) { 3831 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3832 : ImplicitConversionSequence::Indistinguishable; 3833 } 3834 3835 if (SCS1.Third == ICK_Identity) 3836 return Result == ImplicitConversionSequence::Worse 3837 ? ImplicitConversionSequence::Indistinguishable 3838 : ImplicitConversionSequence::Better; 3839 3840 if (SCS2.Third == ICK_Identity) 3841 return Result == ImplicitConversionSequence::Better 3842 ? ImplicitConversionSequence::Indistinguishable 3843 : ImplicitConversionSequence::Worse; 3844 3845 return ImplicitConversionSequence::Indistinguishable; 3846 } 3847 3848 /// Determine whether one of the given reference bindings is better 3849 /// than the other based on what kind of bindings they are. 3850 static bool 3851 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3852 const StandardConversionSequence &SCS2) { 3853 // C++0x [over.ics.rank]p3b4: 3854 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3855 // implicit object parameter of a non-static member function declared 3856 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3857 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3858 // lvalue reference to a function lvalue and S2 binds an rvalue 3859 // reference*. 3860 // 3861 // FIXME: Rvalue references. We're going rogue with the above edits, 3862 // because the semantics in the current C++0x working paper (N3225 at the 3863 // time of this writing) break the standard definition of std::forward 3864 // and std::reference_wrapper when dealing with references to functions. 3865 // Proposed wording changes submitted to CWG for consideration. 3866 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3867 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3868 return false; 3869 3870 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3871 SCS2.IsLvalueReference) || 3872 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3873 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3874 } 3875 3876 enum class FixedEnumPromotion { 3877 None, 3878 ToUnderlyingType, 3879 ToPromotedUnderlyingType 3880 }; 3881 3882 /// Returns kind of fixed enum promotion the \a SCS uses. 3883 static FixedEnumPromotion 3884 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3885 3886 if (SCS.Second != ICK_Integral_Promotion) 3887 return FixedEnumPromotion::None; 3888 3889 QualType FromType = SCS.getFromType(); 3890 if (!FromType->isEnumeralType()) 3891 return FixedEnumPromotion::None; 3892 3893 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3894 if (!Enum->isFixed()) 3895 return FixedEnumPromotion::None; 3896 3897 QualType UnderlyingType = Enum->getIntegerType(); 3898 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3899 return FixedEnumPromotion::ToUnderlyingType; 3900 3901 return FixedEnumPromotion::ToPromotedUnderlyingType; 3902 } 3903 3904 /// CompareStandardConversionSequences - Compare two standard 3905 /// conversion sequences to determine whether one is better than the 3906 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3907 static ImplicitConversionSequence::CompareKind 3908 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3909 const StandardConversionSequence& SCS1, 3910 const StandardConversionSequence& SCS2) 3911 { 3912 // Standard conversion sequence S1 is a better conversion sequence 3913 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3914 3915 // -- S1 is a proper subsequence of S2 (comparing the conversion 3916 // sequences in the canonical form defined by 13.3.3.1.1, 3917 // excluding any Lvalue Transformation; the identity conversion 3918 // sequence is considered to be a subsequence of any 3919 // non-identity conversion sequence) or, if not that, 3920 if (ImplicitConversionSequence::CompareKind CK 3921 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3922 return CK; 3923 3924 // -- the rank of S1 is better than the rank of S2 (by the rules 3925 // defined below), or, if not that, 3926 ImplicitConversionRank Rank1 = SCS1.getRank(); 3927 ImplicitConversionRank Rank2 = SCS2.getRank(); 3928 if (Rank1 < Rank2) 3929 return ImplicitConversionSequence::Better; 3930 else if (Rank2 < Rank1) 3931 return ImplicitConversionSequence::Worse; 3932 3933 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3934 // are indistinguishable unless one of the following rules 3935 // applies: 3936 3937 // A conversion that is not a conversion of a pointer, or 3938 // pointer to member, to bool is better than another conversion 3939 // that is such a conversion. 3940 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3941 return SCS2.isPointerConversionToBool() 3942 ? ImplicitConversionSequence::Better 3943 : ImplicitConversionSequence::Worse; 3944 3945 // C++14 [over.ics.rank]p4b2: 3946 // This is retroactively applied to C++11 by CWG 1601. 3947 // 3948 // A conversion that promotes an enumeration whose underlying type is fixed 3949 // to its underlying type is better than one that promotes to the promoted 3950 // underlying type, if the two are different. 3951 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3952 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3953 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3954 FEP1 != FEP2) 3955 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3956 ? ImplicitConversionSequence::Better 3957 : ImplicitConversionSequence::Worse; 3958 3959 // C++ [over.ics.rank]p4b2: 3960 // 3961 // If class B is derived directly or indirectly from class A, 3962 // conversion of B* to A* is better than conversion of B* to 3963 // void*, and conversion of A* to void* is better than conversion 3964 // of B* to void*. 3965 bool SCS1ConvertsToVoid 3966 = SCS1.isPointerConversionToVoidPointer(S.Context); 3967 bool SCS2ConvertsToVoid 3968 = SCS2.isPointerConversionToVoidPointer(S.Context); 3969 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3970 // Exactly one of the conversion sequences is a conversion to 3971 // a void pointer; it's the worse conversion. 3972 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3973 : ImplicitConversionSequence::Worse; 3974 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3975 // Neither conversion sequence converts to a void pointer; compare 3976 // their derived-to-base conversions. 3977 if (ImplicitConversionSequence::CompareKind DerivedCK 3978 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3979 return DerivedCK; 3980 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3981 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3982 // Both conversion sequences are conversions to void 3983 // pointers. Compare the source types to determine if there's an 3984 // inheritance relationship in their sources. 3985 QualType FromType1 = SCS1.getFromType(); 3986 QualType FromType2 = SCS2.getFromType(); 3987 3988 // Adjust the types we're converting from via the array-to-pointer 3989 // conversion, if we need to. 3990 if (SCS1.First == ICK_Array_To_Pointer) 3991 FromType1 = S.Context.getArrayDecayedType(FromType1); 3992 if (SCS2.First == ICK_Array_To_Pointer) 3993 FromType2 = S.Context.getArrayDecayedType(FromType2); 3994 3995 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3996 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3997 3998 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3999 return ImplicitConversionSequence::Better; 4000 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4001 return ImplicitConversionSequence::Worse; 4002 4003 // Objective-C++: If one interface is more specific than the 4004 // other, it is the better one. 4005 const ObjCObjectPointerType* FromObjCPtr1 4006 = FromType1->getAs<ObjCObjectPointerType>(); 4007 const ObjCObjectPointerType* FromObjCPtr2 4008 = FromType2->getAs<ObjCObjectPointerType>(); 4009 if (FromObjCPtr1 && FromObjCPtr2) { 4010 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4011 FromObjCPtr2); 4012 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4013 FromObjCPtr1); 4014 if (AssignLeft != AssignRight) { 4015 return AssignLeft? ImplicitConversionSequence::Better 4016 : ImplicitConversionSequence::Worse; 4017 } 4018 } 4019 } 4020 4021 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4022 // Check for a better reference binding based on the kind of bindings. 4023 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4024 return ImplicitConversionSequence::Better; 4025 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4026 return ImplicitConversionSequence::Worse; 4027 } 4028 4029 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4030 // bullet 3). 4031 if (ImplicitConversionSequence::CompareKind QualCK 4032 = CompareQualificationConversions(S, SCS1, SCS2)) 4033 return QualCK; 4034 4035 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4036 // C++ [over.ics.rank]p3b4: 4037 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4038 // which the references refer are the same type except for 4039 // top-level cv-qualifiers, and the type to which the reference 4040 // initialized by S2 refers is more cv-qualified than the type 4041 // to which the reference initialized by S1 refers. 4042 QualType T1 = SCS1.getToType(2); 4043 QualType T2 = SCS2.getToType(2); 4044 T1 = S.Context.getCanonicalType(T1); 4045 T2 = S.Context.getCanonicalType(T2); 4046 Qualifiers T1Quals, T2Quals; 4047 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4048 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4049 if (UnqualT1 == UnqualT2) { 4050 // Objective-C++ ARC: If the references refer to objects with different 4051 // lifetimes, prefer bindings that don't change lifetime. 4052 if (SCS1.ObjCLifetimeConversionBinding != 4053 SCS2.ObjCLifetimeConversionBinding) { 4054 return SCS1.ObjCLifetimeConversionBinding 4055 ? ImplicitConversionSequence::Worse 4056 : ImplicitConversionSequence::Better; 4057 } 4058 4059 // If the type is an array type, promote the element qualifiers to the 4060 // type for comparison. 4061 if (isa<ArrayType>(T1) && T1Quals) 4062 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4063 if (isa<ArrayType>(T2) && T2Quals) 4064 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4065 if (T2.isMoreQualifiedThan(T1)) 4066 return ImplicitConversionSequence::Better; 4067 if (T1.isMoreQualifiedThan(T2)) 4068 return ImplicitConversionSequence::Worse; 4069 } 4070 } 4071 4072 // In Microsoft mode, prefer an integral conversion to a 4073 // floating-to-integral conversion if the integral conversion 4074 // is between types of the same size. 4075 // For example: 4076 // void f(float); 4077 // void f(int); 4078 // int main { 4079 // long a; 4080 // f(a); 4081 // } 4082 // Here, MSVC will call f(int) instead of generating a compile error 4083 // as clang will do in standard mode. 4084 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4085 SCS2.Second == ICK_Floating_Integral && 4086 S.Context.getTypeSize(SCS1.getFromType()) == 4087 S.Context.getTypeSize(SCS1.getToType(2))) 4088 return ImplicitConversionSequence::Better; 4089 4090 // Prefer a compatible vector conversion over a lax vector conversion 4091 // For example: 4092 // 4093 // typedef float __v4sf __attribute__((__vector_size__(16))); 4094 // void f(vector float); 4095 // void f(vector signed int); 4096 // int main() { 4097 // __v4sf a; 4098 // f(a); 4099 // } 4100 // Here, we'd like to choose f(vector float) and not 4101 // report an ambiguous call error 4102 if (SCS1.Second == ICK_Vector_Conversion && 4103 SCS2.Second == ICK_Vector_Conversion) { 4104 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4105 SCS1.getFromType(), SCS1.getToType(2)); 4106 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4107 SCS2.getFromType(), SCS2.getToType(2)); 4108 4109 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4110 return SCS1IsCompatibleVectorConversion 4111 ? ImplicitConversionSequence::Better 4112 : ImplicitConversionSequence::Worse; 4113 } 4114 4115 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4116 SCS2.Second == ICK_SVE_Vector_Conversion) { 4117 bool SCS1IsCompatibleSVEVectorConversion = 4118 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4119 bool SCS2IsCompatibleSVEVectorConversion = 4120 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4121 4122 if (SCS1IsCompatibleSVEVectorConversion != 4123 SCS2IsCompatibleSVEVectorConversion) 4124 return SCS1IsCompatibleSVEVectorConversion 4125 ? ImplicitConversionSequence::Better 4126 : ImplicitConversionSequence::Worse; 4127 } 4128 4129 return ImplicitConversionSequence::Indistinguishable; 4130 } 4131 4132 /// CompareQualificationConversions - Compares two standard conversion 4133 /// sequences to determine whether they can be ranked based on their 4134 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4135 static ImplicitConversionSequence::CompareKind 4136 CompareQualificationConversions(Sema &S, 4137 const StandardConversionSequence& SCS1, 4138 const StandardConversionSequence& SCS2) { 4139 // C++ 13.3.3.2p3: 4140 // -- S1 and S2 differ only in their qualification conversion and 4141 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4142 // cv-qualification signature of type T1 is a proper subset of 4143 // the cv-qualification signature of type T2, and S1 is not the 4144 // deprecated string literal array-to-pointer conversion (4.2). 4145 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4146 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4147 return ImplicitConversionSequence::Indistinguishable; 4148 4149 // FIXME: the example in the standard doesn't use a qualification 4150 // conversion (!) 4151 QualType T1 = SCS1.getToType(2); 4152 QualType T2 = SCS2.getToType(2); 4153 T1 = S.Context.getCanonicalType(T1); 4154 T2 = S.Context.getCanonicalType(T2); 4155 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4156 Qualifiers T1Quals, T2Quals; 4157 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4158 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4159 4160 // If the types are the same, we won't learn anything by unwrapping 4161 // them. 4162 if (UnqualT1 == UnqualT2) 4163 return ImplicitConversionSequence::Indistinguishable; 4164 4165 ImplicitConversionSequence::CompareKind Result 4166 = ImplicitConversionSequence::Indistinguishable; 4167 4168 // Objective-C++ ARC: 4169 // Prefer qualification conversions not involving a change in lifetime 4170 // to qualification conversions that do not change lifetime. 4171 if (SCS1.QualificationIncludesObjCLifetime != 4172 SCS2.QualificationIncludesObjCLifetime) { 4173 Result = SCS1.QualificationIncludesObjCLifetime 4174 ? ImplicitConversionSequence::Worse 4175 : ImplicitConversionSequence::Better; 4176 } 4177 4178 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4179 // Within each iteration of the loop, we check the qualifiers to 4180 // determine if this still looks like a qualification 4181 // conversion. Then, if all is well, we unwrap one more level of 4182 // pointers or pointers-to-members and do it all again 4183 // until there are no more pointers or pointers-to-members left 4184 // to unwrap. This essentially mimics what 4185 // IsQualificationConversion does, but here we're checking for a 4186 // strict subset of qualifiers. 4187 if (T1.getQualifiers().withoutObjCLifetime() == 4188 T2.getQualifiers().withoutObjCLifetime()) 4189 // The qualifiers are the same, so this doesn't tell us anything 4190 // about how the sequences rank. 4191 // ObjC ownership quals are omitted above as they interfere with 4192 // the ARC overload rule. 4193 ; 4194 else if (T2.isMoreQualifiedThan(T1)) { 4195 // T1 has fewer qualifiers, so it could be the better sequence. 4196 if (Result == ImplicitConversionSequence::Worse) 4197 // Neither has qualifiers that are a subset of the other's 4198 // qualifiers. 4199 return ImplicitConversionSequence::Indistinguishable; 4200 4201 Result = ImplicitConversionSequence::Better; 4202 } else if (T1.isMoreQualifiedThan(T2)) { 4203 // T2 has fewer qualifiers, so it could be the better sequence. 4204 if (Result == ImplicitConversionSequence::Better) 4205 // Neither has qualifiers that are a subset of the other's 4206 // qualifiers. 4207 return ImplicitConversionSequence::Indistinguishable; 4208 4209 Result = ImplicitConversionSequence::Worse; 4210 } else { 4211 // Qualifiers are disjoint. 4212 return ImplicitConversionSequence::Indistinguishable; 4213 } 4214 4215 // If the types after this point are equivalent, we're done. 4216 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4217 break; 4218 } 4219 4220 // Check that the winning standard conversion sequence isn't using 4221 // the deprecated string literal array to pointer conversion. 4222 switch (Result) { 4223 case ImplicitConversionSequence::Better: 4224 if (SCS1.DeprecatedStringLiteralToCharPtr) 4225 Result = ImplicitConversionSequence::Indistinguishable; 4226 break; 4227 4228 case ImplicitConversionSequence::Indistinguishable: 4229 break; 4230 4231 case ImplicitConversionSequence::Worse: 4232 if (SCS2.DeprecatedStringLiteralToCharPtr) 4233 Result = ImplicitConversionSequence::Indistinguishable; 4234 break; 4235 } 4236 4237 return Result; 4238 } 4239 4240 /// CompareDerivedToBaseConversions - Compares two standard conversion 4241 /// sequences to determine whether they can be ranked based on their 4242 /// various kinds of derived-to-base conversions (C++ 4243 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4244 /// conversions between Objective-C interface types. 4245 static ImplicitConversionSequence::CompareKind 4246 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4247 const StandardConversionSequence& SCS1, 4248 const StandardConversionSequence& SCS2) { 4249 QualType FromType1 = SCS1.getFromType(); 4250 QualType ToType1 = SCS1.getToType(1); 4251 QualType FromType2 = SCS2.getFromType(); 4252 QualType ToType2 = SCS2.getToType(1); 4253 4254 // Adjust the types we're converting from via the array-to-pointer 4255 // conversion, if we need to. 4256 if (SCS1.First == ICK_Array_To_Pointer) 4257 FromType1 = S.Context.getArrayDecayedType(FromType1); 4258 if (SCS2.First == ICK_Array_To_Pointer) 4259 FromType2 = S.Context.getArrayDecayedType(FromType2); 4260 4261 // Canonicalize all of the types. 4262 FromType1 = S.Context.getCanonicalType(FromType1); 4263 ToType1 = S.Context.getCanonicalType(ToType1); 4264 FromType2 = S.Context.getCanonicalType(FromType2); 4265 ToType2 = S.Context.getCanonicalType(ToType2); 4266 4267 // C++ [over.ics.rank]p4b3: 4268 // 4269 // If class B is derived directly or indirectly from class A and 4270 // class C is derived directly or indirectly from B, 4271 // 4272 // Compare based on pointer conversions. 4273 if (SCS1.Second == ICK_Pointer_Conversion && 4274 SCS2.Second == ICK_Pointer_Conversion && 4275 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4276 FromType1->isPointerType() && FromType2->isPointerType() && 4277 ToType1->isPointerType() && ToType2->isPointerType()) { 4278 QualType FromPointee1 = 4279 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4280 QualType ToPointee1 = 4281 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4282 QualType FromPointee2 = 4283 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4284 QualType ToPointee2 = 4285 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4286 4287 // -- conversion of C* to B* is better than conversion of C* to A*, 4288 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4289 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4290 return ImplicitConversionSequence::Better; 4291 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4292 return ImplicitConversionSequence::Worse; 4293 } 4294 4295 // -- conversion of B* to A* is better than conversion of C* to A*, 4296 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4297 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4298 return ImplicitConversionSequence::Better; 4299 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4300 return ImplicitConversionSequence::Worse; 4301 } 4302 } else if (SCS1.Second == ICK_Pointer_Conversion && 4303 SCS2.Second == ICK_Pointer_Conversion) { 4304 const ObjCObjectPointerType *FromPtr1 4305 = FromType1->getAs<ObjCObjectPointerType>(); 4306 const ObjCObjectPointerType *FromPtr2 4307 = FromType2->getAs<ObjCObjectPointerType>(); 4308 const ObjCObjectPointerType *ToPtr1 4309 = ToType1->getAs<ObjCObjectPointerType>(); 4310 const ObjCObjectPointerType *ToPtr2 4311 = ToType2->getAs<ObjCObjectPointerType>(); 4312 4313 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4314 // Apply the same conversion ranking rules for Objective-C pointer types 4315 // that we do for C++ pointers to class types. However, we employ the 4316 // Objective-C pseudo-subtyping relationship used for assignment of 4317 // Objective-C pointer types. 4318 bool FromAssignLeft 4319 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4320 bool FromAssignRight 4321 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4322 bool ToAssignLeft 4323 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4324 bool ToAssignRight 4325 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4326 4327 // A conversion to an a non-id object pointer type or qualified 'id' 4328 // type is better than a conversion to 'id'. 4329 if (ToPtr1->isObjCIdType() && 4330 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4331 return ImplicitConversionSequence::Worse; 4332 if (ToPtr2->isObjCIdType() && 4333 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4334 return ImplicitConversionSequence::Better; 4335 4336 // A conversion to a non-id object pointer type is better than a 4337 // conversion to a qualified 'id' type 4338 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4339 return ImplicitConversionSequence::Worse; 4340 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4341 return ImplicitConversionSequence::Better; 4342 4343 // A conversion to an a non-Class object pointer type or qualified 'Class' 4344 // type is better than a conversion to 'Class'. 4345 if (ToPtr1->isObjCClassType() && 4346 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4347 return ImplicitConversionSequence::Worse; 4348 if (ToPtr2->isObjCClassType() && 4349 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4350 return ImplicitConversionSequence::Better; 4351 4352 // A conversion to a non-Class object pointer type is better than a 4353 // conversion to a qualified 'Class' type. 4354 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4355 return ImplicitConversionSequence::Worse; 4356 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4357 return ImplicitConversionSequence::Better; 4358 4359 // -- "conversion of C* to B* is better than conversion of C* to A*," 4360 if (S.Context.hasSameType(FromType1, FromType2) && 4361 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4362 (ToAssignLeft != ToAssignRight)) { 4363 if (FromPtr1->isSpecialized()) { 4364 // "conversion of B<A> * to B * is better than conversion of B * to 4365 // C *. 4366 bool IsFirstSame = 4367 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4368 bool IsSecondSame = 4369 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4370 if (IsFirstSame) { 4371 if (!IsSecondSame) 4372 return ImplicitConversionSequence::Better; 4373 } else if (IsSecondSame) 4374 return ImplicitConversionSequence::Worse; 4375 } 4376 return ToAssignLeft? ImplicitConversionSequence::Worse 4377 : ImplicitConversionSequence::Better; 4378 } 4379 4380 // -- "conversion of B* to A* is better than conversion of C* to A*," 4381 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4382 (FromAssignLeft != FromAssignRight)) 4383 return FromAssignLeft? ImplicitConversionSequence::Better 4384 : ImplicitConversionSequence::Worse; 4385 } 4386 } 4387 4388 // Ranking of member-pointer types. 4389 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4390 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4391 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4392 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4393 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4394 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4395 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4396 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4397 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4398 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4399 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4400 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4401 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4402 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4403 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4404 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4405 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4406 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4407 return ImplicitConversionSequence::Worse; 4408 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4409 return ImplicitConversionSequence::Better; 4410 } 4411 // conversion of B::* to C::* is better than conversion of A::* to C::* 4412 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4413 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4414 return ImplicitConversionSequence::Better; 4415 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4416 return ImplicitConversionSequence::Worse; 4417 } 4418 } 4419 4420 if (SCS1.Second == ICK_Derived_To_Base) { 4421 // -- conversion of C to B is better than conversion of C to A, 4422 // -- binding of an expression of type C to a reference of type 4423 // B& is better than binding an expression of type C to a 4424 // reference of type A&, 4425 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4426 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4427 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4428 return ImplicitConversionSequence::Better; 4429 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4430 return ImplicitConversionSequence::Worse; 4431 } 4432 4433 // -- conversion of B to A is better than conversion of C to A. 4434 // -- binding of an expression of type B to a reference of type 4435 // A& is better than binding an expression of type C to a 4436 // reference of type A&, 4437 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4438 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4439 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4440 return ImplicitConversionSequence::Better; 4441 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4442 return ImplicitConversionSequence::Worse; 4443 } 4444 } 4445 4446 return ImplicitConversionSequence::Indistinguishable; 4447 } 4448 4449 /// Determine whether the given type is valid, e.g., it is not an invalid 4450 /// C++ class. 4451 static bool isTypeValid(QualType T) { 4452 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4453 return !Record->isInvalidDecl(); 4454 4455 return true; 4456 } 4457 4458 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4459 if (!T.getQualifiers().hasUnaligned()) 4460 return T; 4461 4462 Qualifiers Q; 4463 T = Ctx.getUnqualifiedArrayType(T, Q); 4464 Q.removeUnaligned(); 4465 return Ctx.getQualifiedType(T, Q); 4466 } 4467 4468 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4469 /// determine whether they are reference-compatible, 4470 /// reference-related, or incompatible, for use in C++ initialization by 4471 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4472 /// type, and the first type (T1) is the pointee type of the reference 4473 /// type being initialized. 4474 Sema::ReferenceCompareResult 4475 Sema::CompareReferenceRelationship(SourceLocation Loc, 4476 QualType OrigT1, QualType OrigT2, 4477 ReferenceConversions *ConvOut) { 4478 assert(!OrigT1->isReferenceType() && 4479 "T1 must be the pointee type of the reference type"); 4480 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4481 4482 QualType T1 = Context.getCanonicalType(OrigT1); 4483 QualType T2 = Context.getCanonicalType(OrigT2); 4484 Qualifiers T1Quals, T2Quals; 4485 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4486 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4487 4488 ReferenceConversions ConvTmp; 4489 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4490 Conv = ReferenceConversions(); 4491 4492 // C++2a [dcl.init.ref]p4: 4493 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4494 // reference-related to "cv2 T2" if T1 is similar to T2, or 4495 // T1 is a base class of T2. 4496 // "cv1 T1" is reference-compatible with "cv2 T2" if 4497 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4498 // "pointer to cv1 T1" via a standard conversion sequence. 4499 4500 // Check for standard conversions we can apply to pointers: derived-to-base 4501 // conversions, ObjC pointer conversions, and function pointer conversions. 4502 // (Qualification conversions are checked last.) 4503 QualType ConvertedT2; 4504 if (UnqualT1 == UnqualT2) { 4505 // Nothing to do. 4506 } else if (isCompleteType(Loc, OrigT2) && 4507 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4508 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4509 Conv |= ReferenceConversions::DerivedToBase; 4510 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4511 UnqualT2->isObjCObjectOrInterfaceType() && 4512 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4513 Conv |= ReferenceConversions::ObjC; 4514 else if (UnqualT2->isFunctionType() && 4515 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4516 Conv |= ReferenceConversions::Function; 4517 // No need to check qualifiers; function types don't have them. 4518 return Ref_Compatible; 4519 } 4520 bool ConvertedReferent = Conv != 0; 4521 4522 // We can have a qualification conversion. Compute whether the types are 4523 // similar at the same time. 4524 bool PreviousToQualsIncludeConst = true; 4525 bool TopLevel = true; 4526 do { 4527 if (T1 == T2) 4528 break; 4529 4530 // We will need a qualification conversion. 4531 Conv |= ReferenceConversions::Qualification; 4532 4533 // Track whether we performed a qualification conversion anywhere other 4534 // than the top level. This matters for ranking reference bindings in 4535 // overload resolution. 4536 if (!TopLevel) 4537 Conv |= ReferenceConversions::NestedQualification; 4538 4539 // MS compiler ignores __unaligned qualifier for references; do the same. 4540 T1 = withoutUnaligned(Context, T1); 4541 T2 = withoutUnaligned(Context, T2); 4542 4543 // If we find a qualifier mismatch, the types are not reference-compatible, 4544 // but are still be reference-related if they're similar. 4545 bool ObjCLifetimeConversion = false; 4546 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4547 PreviousToQualsIncludeConst, 4548 ObjCLifetimeConversion)) 4549 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4550 ? Ref_Related 4551 : Ref_Incompatible; 4552 4553 // FIXME: Should we track this for any level other than the first? 4554 if (ObjCLifetimeConversion) 4555 Conv |= ReferenceConversions::ObjCLifetime; 4556 4557 TopLevel = false; 4558 } while (Context.UnwrapSimilarTypes(T1, T2)); 4559 4560 // At this point, if the types are reference-related, we must either have the 4561 // same inner type (ignoring qualifiers), or must have already worked out how 4562 // to convert the referent. 4563 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4564 ? Ref_Compatible 4565 : Ref_Incompatible; 4566 } 4567 4568 /// Look for a user-defined conversion to a value reference-compatible 4569 /// with DeclType. Return true if something definite is found. 4570 static bool 4571 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4572 QualType DeclType, SourceLocation DeclLoc, 4573 Expr *Init, QualType T2, bool AllowRvalues, 4574 bool AllowExplicit) { 4575 assert(T2->isRecordType() && "Can only find conversions of record types."); 4576 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4577 4578 OverloadCandidateSet CandidateSet( 4579 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4580 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4581 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4582 NamedDecl *D = *I; 4583 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4584 if (isa<UsingShadowDecl>(D)) 4585 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4586 4587 FunctionTemplateDecl *ConvTemplate 4588 = dyn_cast<FunctionTemplateDecl>(D); 4589 CXXConversionDecl *Conv; 4590 if (ConvTemplate) 4591 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4592 else 4593 Conv = cast<CXXConversionDecl>(D); 4594 4595 if (AllowRvalues) { 4596 // If we are initializing an rvalue reference, don't permit conversion 4597 // functions that return lvalues. 4598 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4599 const ReferenceType *RefType 4600 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4601 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4602 continue; 4603 } 4604 4605 if (!ConvTemplate && 4606 S.CompareReferenceRelationship( 4607 DeclLoc, 4608 Conv->getConversionType() 4609 .getNonReferenceType() 4610 .getUnqualifiedType(), 4611 DeclType.getNonReferenceType().getUnqualifiedType()) == 4612 Sema::Ref_Incompatible) 4613 continue; 4614 } else { 4615 // If the conversion function doesn't return a reference type, 4616 // it can't be considered for this conversion. An rvalue reference 4617 // is only acceptable if its referencee is a function type. 4618 4619 const ReferenceType *RefType = 4620 Conv->getConversionType()->getAs<ReferenceType>(); 4621 if (!RefType || 4622 (!RefType->isLValueReferenceType() && 4623 !RefType->getPointeeType()->isFunctionType())) 4624 continue; 4625 } 4626 4627 if (ConvTemplate) 4628 S.AddTemplateConversionCandidate( 4629 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4630 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4631 else 4632 S.AddConversionCandidate( 4633 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4634 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4635 } 4636 4637 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4638 4639 OverloadCandidateSet::iterator Best; 4640 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4641 case OR_Success: 4642 // C++ [over.ics.ref]p1: 4643 // 4644 // [...] If the parameter binds directly to the result of 4645 // applying a conversion function to the argument 4646 // expression, the implicit conversion sequence is a 4647 // user-defined conversion sequence (13.3.3.1.2), with the 4648 // second standard conversion sequence either an identity 4649 // conversion or, if the conversion function returns an 4650 // entity of a type that is a derived class of the parameter 4651 // type, a derived-to-base Conversion. 4652 if (!Best->FinalConversion.DirectBinding) 4653 return false; 4654 4655 ICS.setUserDefined(); 4656 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4657 ICS.UserDefined.After = Best->FinalConversion; 4658 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4659 ICS.UserDefined.ConversionFunction = Best->Function; 4660 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4661 ICS.UserDefined.EllipsisConversion = false; 4662 assert(ICS.UserDefined.After.ReferenceBinding && 4663 ICS.UserDefined.After.DirectBinding && 4664 "Expected a direct reference binding!"); 4665 return true; 4666 4667 case OR_Ambiguous: 4668 ICS.setAmbiguous(); 4669 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4670 Cand != CandidateSet.end(); ++Cand) 4671 if (Cand->Best) 4672 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4673 return true; 4674 4675 case OR_No_Viable_Function: 4676 case OR_Deleted: 4677 // There was no suitable conversion, or we found a deleted 4678 // conversion; continue with other checks. 4679 return false; 4680 } 4681 4682 llvm_unreachable("Invalid OverloadResult!"); 4683 } 4684 4685 /// Compute an implicit conversion sequence for reference 4686 /// initialization. 4687 static ImplicitConversionSequence 4688 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4689 SourceLocation DeclLoc, 4690 bool SuppressUserConversions, 4691 bool AllowExplicit) { 4692 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4693 4694 // Most paths end in a failed conversion. 4695 ImplicitConversionSequence ICS; 4696 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4697 4698 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4699 QualType T2 = Init->getType(); 4700 4701 // If the initializer is the address of an overloaded function, try 4702 // to resolve the overloaded function. If all goes well, T2 is the 4703 // type of the resulting function. 4704 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4705 DeclAccessPair Found; 4706 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4707 false, Found)) 4708 T2 = Fn->getType(); 4709 } 4710 4711 // Compute some basic properties of the types and the initializer. 4712 bool isRValRef = DeclType->isRValueReferenceType(); 4713 Expr::Classification InitCategory = Init->Classify(S.Context); 4714 4715 Sema::ReferenceConversions RefConv; 4716 Sema::ReferenceCompareResult RefRelationship = 4717 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4718 4719 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4720 ICS.setStandard(); 4721 ICS.Standard.First = ICK_Identity; 4722 // FIXME: A reference binding can be a function conversion too. We should 4723 // consider that when ordering reference-to-function bindings. 4724 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4725 ? ICK_Derived_To_Base 4726 : (RefConv & Sema::ReferenceConversions::ObjC) 4727 ? ICK_Compatible_Conversion 4728 : ICK_Identity; 4729 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4730 // a reference binding that performs a non-top-level qualification 4731 // conversion as a qualification conversion, not as an identity conversion. 4732 ICS.Standard.Third = (RefConv & 4733 Sema::ReferenceConversions::NestedQualification) 4734 ? ICK_Qualification 4735 : ICK_Identity; 4736 ICS.Standard.setFromType(T2); 4737 ICS.Standard.setToType(0, T2); 4738 ICS.Standard.setToType(1, T1); 4739 ICS.Standard.setToType(2, T1); 4740 ICS.Standard.ReferenceBinding = true; 4741 ICS.Standard.DirectBinding = BindsDirectly; 4742 ICS.Standard.IsLvalueReference = !isRValRef; 4743 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4744 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4745 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4746 ICS.Standard.ObjCLifetimeConversionBinding = 4747 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4748 ICS.Standard.CopyConstructor = nullptr; 4749 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4750 }; 4751 4752 // C++0x [dcl.init.ref]p5: 4753 // A reference to type "cv1 T1" is initialized by an expression 4754 // of type "cv2 T2" as follows: 4755 4756 // -- If reference is an lvalue reference and the initializer expression 4757 if (!isRValRef) { 4758 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4759 // reference-compatible with "cv2 T2," or 4760 // 4761 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4762 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4763 // C++ [over.ics.ref]p1: 4764 // When a parameter of reference type binds directly (8.5.3) 4765 // to an argument expression, the implicit conversion sequence 4766 // is the identity conversion, unless the argument expression 4767 // has a type that is a derived class of the parameter type, 4768 // in which case the implicit conversion sequence is a 4769 // derived-to-base Conversion (13.3.3.1). 4770 SetAsReferenceBinding(/*BindsDirectly=*/true); 4771 4772 // Nothing more to do: the inaccessibility/ambiguity check for 4773 // derived-to-base conversions is suppressed when we're 4774 // computing the implicit conversion sequence (C++ 4775 // [over.best.ics]p2). 4776 return ICS; 4777 } 4778 4779 // -- has a class type (i.e., T2 is a class type), where T1 is 4780 // not reference-related to T2, and can be implicitly 4781 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4782 // is reference-compatible with "cv3 T3" 92) (this 4783 // conversion is selected by enumerating the applicable 4784 // conversion functions (13.3.1.6) and choosing the best 4785 // one through overload resolution (13.3)), 4786 if (!SuppressUserConversions && T2->isRecordType() && 4787 S.isCompleteType(DeclLoc, T2) && 4788 RefRelationship == Sema::Ref_Incompatible) { 4789 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4790 Init, T2, /*AllowRvalues=*/false, 4791 AllowExplicit)) 4792 return ICS; 4793 } 4794 } 4795 4796 // -- Otherwise, the reference shall be an lvalue reference to a 4797 // non-volatile const type (i.e., cv1 shall be const), or the reference 4798 // shall be an rvalue reference. 4799 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4800 return ICS; 4801 4802 // -- If the initializer expression 4803 // 4804 // -- is an xvalue, class prvalue, array prvalue or function 4805 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4806 if (RefRelationship == Sema::Ref_Compatible && 4807 (InitCategory.isXValue() || 4808 (InitCategory.isPRValue() && 4809 (T2->isRecordType() || T2->isArrayType())) || 4810 (InitCategory.isLValue() && T2->isFunctionType()))) { 4811 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4812 // binding unless we're binding to a class prvalue. 4813 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4814 // allow the use of rvalue references in C++98/03 for the benefit of 4815 // standard library implementors; therefore, we need the xvalue check here. 4816 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4817 !(InitCategory.isPRValue() || T2->isRecordType())); 4818 return ICS; 4819 } 4820 4821 // -- has a class type (i.e., T2 is a class type), where T1 is not 4822 // reference-related to T2, and can be implicitly converted to 4823 // an xvalue, class prvalue, or function lvalue of type 4824 // "cv3 T3", where "cv1 T1" is reference-compatible with 4825 // "cv3 T3", 4826 // 4827 // then the reference is bound to the value of the initializer 4828 // expression in the first case and to the result of the conversion 4829 // in the second case (or, in either case, to an appropriate base 4830 // class subobject). 4831 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4832 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4833 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4834 Init, T2, /*AllowRvalues=*/true, 4835 AllowExplicit)) { 4836 // In the second case, if the reference is an rvalue reference 4837 // and the second standard conversion sequence of the 4838 // user-defined conversion sequence includes an lvalue-to-rvalue 4839 // conversion, the program is ill-formed. 4840 if (ICS.isUserDefined() && isRValRef && 4841 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4842 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4843 4844 return ICS; 4845 } 4846 4847 // A temporary of function type cannot be created; don't even try. 4848 if (T1->isFunctionType()) 4849 return ICS; 4850 4851 // -- Otherwise, a temporary of type "cv1 T1" is created and 4852 // initialized from the initializer expression using the 4853 // rules for a non-reference copy initialization (8.5). The 4854 // reference is then bound to the temporary. If T1 is 4855 // reference-related to T2, cv1 must be the same 4856 // cv-qualification as, or greater cv-qualification than, 4857 // cv2; otherwise, the program is ill-formed. 4858 if (RefRelationship == Sema::Ref_Related) { 4859 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4860 // we would be reference-compatible or reference-compatible with 4861 // added qualification. But that wasn't the case, so the reference 4862 // initialization fails. 4863 // 4864 // Note that we only want to check address spaces and cvr-qualifiers here. 4865 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4866 Qualifiers T1Quals = T1.getQualifiers(); 4867 Qualifiers T2Quals = T2.getQualifiers(); 4868 T1Quals.removeObjCGCAttr(); 4869 T1Quals.removeObjCLifetime(); 4870 T2Quals.removeObjCGCAttr(); 4871 T2Quals.removeObjCLifetime(); 4872 // MS compiler ignores __unaligned qualifier for references; do the same. 4873 T1Quals.removeUnaligned(); 4874 T2Quals.removeUnaligned(); 4875 if (!T1Quals.compatiblyIncludes(T2Quals)) 4876 return ICS; 4877 } 4878 4879 // If at least one of the types is a class type, the types are not 4880 // related, and we aren't allowed any user conversions, the 4881 // reference binding fails. This case is important for breaking 4882 // recursion, since TryImplicitConversion below will attempt to 4883 // create a temporary through the use of a copy constructor. 4884 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4885 (T1->isRecordType() || T2->isRecordType())) 4886 return ICS; 4887 4888 // If T1 is reference-related to T2 and the reference is an rvalue 4889 // reference, the initializer expression shall not be an lvalue. 4890 if (RefRelationship >= Sema::Ref_Related && 4891 isRValRef && Init->Classify(S.Context).isLValue()) 4892 return ICS; 4893 4894 // C++ [over.ics.ref]p2: 4895 // When a parameter of reference type is not bound directly to 4896 // an argument expression, the conversion sequence is the one 4897 // required to convert the argument expression to the 4898 // underlying type of the reference according to 4899 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4900 // to copy-initializing a temporary of the underlying type with 4901 // the argument expression. Any difference in top-level 4902 // cv-qualification is subsumed by the initialization itself 4903 // and does not constitute a conversion. 4904 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4905 AllowedExplicit::None, 4906 /*InOverloadResolution=*/false, 4907 /*CStyle=*/false, 4908 /*AllowObjCWritebackConversion=*/false, 4909 /*AllowObjCConversionOnExplicit=*/false); 4910 4911 // Of course, that's still a reference binding. 4912 if (ICS.isStandard()) { 4913 ICS.Standard.ReferenceBinding = true; 4914 ICS.Standard.IsLvalueReference = !isRValRef; 4915 ICS.Standard.BindsToFunctionLvalue = false; 4916 ICS.Standard.BindsToRvalue = true; 4917 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4918 ICS.Standard.ObjCLifetimeConversionBinding = false; 4919 } else if (ICS.isUserDefined()) { 4920 const ReferenceType *LValRefType = 4921 ICS.UserDefined.ConversionFunction->getReturnType() 4922 ->getAs<LValueReferenceType>(); 4923 4924 // C++ [over.ics.ref]p3: 4925 // Except for an implicit object parameter, for which see 13.3.1, a 4926 // standard conversion sequence cannot be formed if it requires [...] 4927 // binding an rvalue reference to an lvalue other than a function 4928 // lvalue. 4929 // Note that the function case is not possible here. 4930 if (DeclType->isRValueReferenceType() && LValRefType) { 4931 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4932 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4933 // reference to an rvalue! 4934 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4935 return ICS; 4936 } 4937 4938 ICS.UserDefined.After.ReferenceBinding = true; 4939 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4940 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4941 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4942 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4943 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4944 } 4945 4946 return ICS; 4947 } 4948 4949 static ImplicitConversionSequence 4950 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4951 bool SuppressUserConversions, 4952 bool InOverloadResolution, 4953 bool AllowObjCWritebackConversion, 4954 bool AllowExplicit = false); 4955 4956 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4957 /// initializer list From. 4958 static ImplicitConversionSequence 4959 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4960 bool SuppressUserConversions, 4961 bool InOverloadResolution, 4962 bool AllowObjCWritebackConversion) { 4963 // C++11 [over.ics.list]p1: 4964 // When an argument is an initializer list, it is not an expression and 4965 // special rules apply for converting it to a parameter type. 4966 4967 ImplicitConversionSequence Result; 4968 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4969 4970 // We need a complete type for what follows. Incomplete types can never be 4971 // initialized from init lists. 4972 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4973 return Result; 4974 4975 // Per DR1467: 4976 // If the parameter type is a class X and the initializer list has a single 4977 // element of type cv U, where U is X or a class derived from X, the 4978 // implicit conversion sequence is the one required to convert the element 4979 // to the parameter type. 4980 // 4981 // Otherwise, if the parameter type is a character array [... ] 4982 // and the initializer list has a single element that is an 4983 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4984 // implicit conversion sequence is the identity conversion. 4985 if (From->getNumInits() == 1) { 4986 if (ToType->isRecordType()) { 4987 QualType InitType = From->getInit(0)->getType(); 4988 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4989 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4990 return TryCopyInitialization(S, From->getInit(0), ToType, 4991 SuppressUserConversions, 4992 InOverloadResolution, 4993 AllowObjCWritebackConversion); 4994 } 4995 // FIXME: Check the other conditions here: array of character type, 4996 // initializer is a string literal. 4997 if (ToType->isArrayType()) { 4998 InitializedEntity Entity = 4999 InitializedEntity::InitializeParameter(S.Context, ToType, 5000 /*Consumed=*/false); 5001 if (S.CanPerformCopyInitialization(Entity, From)) { 5002 Result.setStandard(); 5003 Result.Standard.setAsIdentityConversion(); 5004 Result.Standard.setFromType(ToType); 5005 Result.Standard.setAllToTypes(ToType); 5006 return Result; 5007 } 5008 } 5009 } 5010 5011 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5012 // C++11 [over.ics.list]p2: 5013 // If the parameter type is std::initializer_list<X> or "array of X" and 5014 // all the elements can be implicitly converted to X, the implicit 5015 // conversion sequence is the worst conversion necessary to convert an 5016 // element of the list to X. 5017 // 5018 // C++14 [over.ics.list]p3: 5019 // Otherwise, if the parameter type is "array of N X", if the initializer 5020 // list has exactly N elements or if it has fewer than N elements and X is 5021 // default-constructible, and if all the elements of the initializer list 5022 // can be implicitly converted to X, the implicit conversion sequence is 5023 // the worst conversion necessary to convert an element of the list to X. 5024 // 5025 // FIXME: We're missing a lot of these checks. 5026 bool toStdInitializerList = false; 5027 QualType X; 5028 if (ToType->isArrayType()) 5029 X = S.Context.getAsArrayType(ToType)->getElementType(); 5030 else 5031 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5032 if (!X.isNull()) { 5033 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5034 Expr *Init = From->getInit(i); 5035 ImplicitConversionSequence ICS = 5036 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5037 InOverloadResolution, 5038 AllowObjCWritebackConversion); 5039 // If a single element isn't convertible, fail. 5040 if (ICS.isBad()) { 5041 Result = ICS; 5042 break; 5043 } 5044 // Otherwise, look for the worst conversion. 5045 if (Result.isBad() || CompareImplicitConversionSequences( 5046 S, From->getBeginLoc(), ICS, Result) == 5047 ImplicitConversionSequence::Worse) 5048 Result = ICS; 5049 } 5050 5051 // For an empty list, we won't have computed any conversion sequence. 5052 // Introduce the identity conversion sequence. 5053 if (From->getNumInits() == 0) { 5054 Result.setStandard(); 5055 Result.Standard.setAsIdentityConversion(); 5056 Result.Standard.setFromType(ToType); 5057 Result.Standard.setAllToTypes(ToType); 5058 } 5059 5060 Result.setStdInitializerListElement(toStdInitializerList); 5061 return Result; 5062 } 5063 5064 // C++14 [over.ics.list]p4: 5065 // C++11 [over.ics.list]p3: 5066 // Otherwise, if the parameter is a non-aggregate class X and overload 5067 // resolution chooses a single best constructor [...] the implicit 5068 // conversion sequence is a user-defined conversion sequence. If multiple 5069 // constructors are viable but none is better than the others, the 5070 // implicit conversion sequence is a user-defined conversion sequence. 5071 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5072 // This function can deal with initializer lists. 5073 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5074 AllowedExplicit::None, 5075 InOverloadResolution, /*CStyle=*/false, 5076 AllowObjCWritebackConversion, 5077 /*AllowObjCConversionOnExplicit=*/false); 5078 } 5079 5080 // C++14 [over.ics.list]p5: 5081 // C++11 [over.ics.list]p4: 5082 // Otherwise, if the parameter has an aggregate type which can be 5083 // initialized from the initializer list [...] the implicit conversion 5084 // sequence is a user-defined conversion sequence. 5085 if (ToType->isAggregateType()) { 5086 // Type is an aggregate, argument is an init list. At this point it comes 5087 // down to checking whether the initialization works. 5088 // FIXME: Find out whether this parameter is consumed or not. 5089 InitializedEntity Entity = 5090 InitializedEntity::InitializeParameter(S.Context, ToType, 5091 /*Consumed=*/false); 5092 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5093 From)) { 5094 Result.setUserDefined(); 5095 Result.UserDefined.Before.setAsIdentityConversion(); 5096 // Initializer lists don't have a type. 5097 Result.UserDefined.Before.setFromType(QualType()); 5098 Result.UserDefined.Before.setAllToTypes(QualType()); 5099 5100 Result.UserDefined.After.setAsIdentityConversion(); 5101 Result.UserDefined.After.setFromType(ToType); 5102 Result.UserDefined.After.setAllToTypes(ToType); 5103 Result.UserDefined.ConversionFunction = nullptr; 5104 } 5105 return Result; 5106 } 5107 5108 // C++14 [over.ics.list]p6: 5109 // C++11 [over.ics.list]p5: 5110 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5111 if (ToType->isReferenceType()) { 5112 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5113 // mention initializer lists in any way. So we go by what list- 5114 // initialization would do and try to extrapolate from that. 5115 5116 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5117 5118 // If the initializer list has a single element that is reference-related 5119 // to the parameter type, we initialize the reference from that. 5120 if (From->getNumInits() == 1) { 5121 Expr *Init = From->getInit(0); 5122 5123 QualType T2 = Init->getType(); 5124 5125 // If the initializer is the address of an overloaded function, try 5126 // to resolve the overloaded function. If all goes well, T2 is the 5127 // type of the resulting function. 5128 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5129 DeclAccessPair Found; 5130 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5131 Init, ToType, false, Found)) 5132 T2 = Fn->getType(); 5133 } 5134 5135 // Compute some basic properties of the types and the initializer. 5136 Sema::ReferenceCompareResult RefRelationship = 5137 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5138 5139 if (RefRelationship >= Sema::Ref_Related) { 5140 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5141 SuppressUserConversions, 5142 /*AllowExplicit=*/false); 5143 } 5144 } 5145 5146 // Otherwise, we bind the reference to a temporary created from the 5147 // initializer list. 5148 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5149 InOverloadResolution, 5150 AllowObjCWritebackConversion); 5151 if (Result.isFailure()) 5152 return Result; 5153 assert(!Result.isEllipsis() && 5154 "Sub-initialization cannot result in ellipsis conversion."); 5155 5156 // Can we even bind to a temporary? 5157 if (ToType->isRValueReferenceType() || 5158 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5159 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5160 Result.UserDefined.After; 5161 SCS.ReferenceBinding = true; 5162 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5163 SCS.BindsToRvalue = true; 5164 SCS.BindsToFunctionLvalue = false; 5165 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5166 SCS.ObjCLifetimeConversionBinding = false; 5167 } else 5168 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5169 From, ToType); 5170 return Result; 5171 } 5172 5173 // C++14 [over.ics.list]p7: 5174 // C++11 [over.ics.list]p6: 5175 // Otherwise, if the parameter type is not a class: 5176 if (!ToType->isRecordType()) { 5177 // - if the initializer list has one element that is not itself an 5178 // initializer list, the implicit conversion sequence is the one 5179 // required to convert the element to the parameter type. 5180 unsigned NumInits = From->getNumInits(); 5181 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5182 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5183 SuppressUserConversions, 5184 InOverloadResolution, 5185 AllowObjCWritebackConversion); 5186 // - if the initializer list has no elements, the implicit conversion 5187 // sequence is the identity conversion. 5188 else if (NumInits == 0) { 5189 Result.setStandard(); 5190 Result.Standard.setAsIdentityConversion(); 5191 Result.Standard.setFromType(ToType); 5192 Result.Standard.setAllToTypes(ToType); 5193 } 5194 return Result; 5195 } 5196 5197 // C++14 [over.ics.list]p8: 5198 // C++11 [over.ics.list]p7: 5199 // In all cases other than those enumerated above, no conversion is possible 5200 return Result; 5201 } 5202 5203 /// TryCopyInitialization - Try to copy-initialize a value of type 5204 /// ToType from the expression From. Return the implicit conversion 5205 /// sequence required to pass this argument, which may be a bad 5206 /// conversion sequence (meaning that the argument cannot be passed to 5207 /// a parameter of this type). If @p SuppressUserConversions, then we 5208 /// do not permit any user-defined conversion sequences. 5209 static ImplicitConversionSequence 5210 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5211 bool SuppressUserConversions, 5212 bool InOverloadResolution, 5213 bool AllowObjCWritebackConversion, 5214 bool AllowExplicit) { 5215 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5216 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5217 InOverloadResolution,AllowObjCWritebackConversion); 5218 5219 if (ToType->isReferenceType()) 5220 return TryReferenceInit(S, From, ToType, 5221 /*FIXME:*/ From->getBeginLoc(), 5222 SuppressUserConversions, AllowExplicit); 5223 5224 return TryImplicitConversion(S, From, ToType, 5225 SuppressUserConversions, 5226 AllowedExplicit::None, 5227 InOverloadResolution, 5228 /*CStyle=*/false, 5229 AllowObjCWritebackConversion, 5230 /*AllowObjCConversionOnExplicit=*/false); 5231 } 5232 5233 static bool TryCopyInitialization(const CanQualType FromQTy, 5234 const CanQualType ToQTy, 5235 Sema &S, 5236 SourceLocation Loc, 5237 ExprValueKind FromVK) { 5238 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5239 ImplicitConversionSequence ICS = 5240 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5241 5242 return !ICS.isBad(); 5243 } 5244 5245 /// TryObjectArgumentInitialization - Try to initialize the object 5246 /// parameter of the given member function (@c Method) from the 5247 /// expression @p From. 5248 static ImplicitConversionSequence 5249 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5250 Expr::Classification FromClassification, 5251 CXXMethodDecl *Method, 5252 CXXRecordDecl *ActingContext) { 5253 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5254 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5255 // const volatile object. 5256 Qualifiers Quals = Method->getMethodQualifiers(); 5257 if (isa<CXXDestructorDecl>(Method)) { 5258 Quals.addConst(); 5259 Quals.addVolatile(); 5260 } 5261 5262 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5263 5264 // Set up the conversion sequence as a "bad" conversion, to allow us 5265 // to exit early. 5266 ImplicitConversionSequence ICS; 5267 5268 // We need to have an object of class type. 5269 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5270 FromType = PT->getPointeeType(); 5271 5272 // When we had a pointer, it's implicitly dereferenced, so we 5273 // better have an lvalue. 5274 assert(FromClassification.isLValue()); 5275 } 5276 5277 assert(FromType->isRecordType()); 5278 5279 // C++0x [over.match.funcs]p4: 5280 // For non-static member functions, the type of the implicit object 5281 // parameter is 5282 // 5283 // - "lvalue reference to cv X" for functions declared without a 5284 // ref-qualifier or with the & ref-qualifier 5285 // - "rvalue reference to cv X" for functions declared with the && 5286 // ref-qualifier 5287 // 5288 // where X is the class of which the function is a member and cv is the 5289 // cv-qualification on the member function declaration. 5290 // 5291 // However, when finding an implicit conversion sequence for the argument, we 5292 // are not allowed to perform user-defined conversions 5293 // (C++ [over.match.funcs]p5). We perform a simplified version of 5294 // reference binding here, that allows class rvalues to bind to 5295 // non-constant references. 5296 5297 // First check the qualifiers. 5298 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5299 if (ImplicitParamType.getCVRQualifiers() 5300 != FromTypeCanon.getLocalCVRQualifiers() && 5301 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5302 ICS.setBad(BadConversionSequence::bad_qualifiers, 5303 FromType, ImplicitParamType); 5304 return ICS; 5305 } 5306 5307 if (FromTypeCanon.hasAddressSpace()) { 5308 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5309 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5310 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5311 ICS.setBad(BadConversionSequence::bad_qualifiers, 5312 FromType, ImplicitParamType); 5313 return ICS; 5314 } 5315 } 5316 5317 // Check that we have either the same type or a derived type. It 5318 // affects the conversion rank. 5319 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5320 ImplicitConversionKind SecondKind; 5321 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5322 SecondKind = ICK_Identity; 5323 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5324 SecondKind = ICK_Derived_To_Base; 5325 else { 5326 ICS.setBad(BadConversionSequence::unrelated_class, 5327 FromType, ImplicitParamType); 5328 return ICS; 5329 } 5330 5331 // Check the ref-qualifier. 5332 switch (Method->getRefQualifier()) { 5333 case RQ_None: 5334 // Do nothing; we don't care about lvalueness or rvalueness. 5335 break; 5336 5337 case RQ_LValue: 5338 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5339 // non-const lvalue reference cannot bind to an rvalue 5340 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5341 ImplicitParamType); 5342 return ICS; 5343 } 5344 break; 5345 5346 case RQ_RValue: 5347 if (!FromClassification.isRValue()) { 5348 // rvalue reference cannot bind to an lvalue 5349 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5350 ImplicitParamType); 5351 return ICS; 5352 } 5353 break; 5354 } 5355 5356 // Success. Mark this as a reference binding. 5357 ICS.setStandard(); 5358 ICS.Standard.setAsIdentityConversion(); 5359 ICS.Standard.Second = SecondKind; 5360 ICS.Standard.setFromType(FromType); 5361 ICS.Standard.setAllToTypes(ImplicitParamType); 5362 ICS.Standard.ReferenceBinding = true; 5363 ICS.Standard.DirectBinding = true; 5364 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5365 ICS.Standard.BindsToFunctionLvalue = false; 5366 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5367 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5368 = (Method->getRefQualifier() == RQ_None); 5369 return ICS; 5370 } 5371 5372 /// PerformObjectArgumentInitialization - Perform initialization of 5373 /// the implicit object parameter for the given Method with the given 5374 /// expression. 5375 ExprResult 5376 Sema::PerformObjectArgumentInitialization(Expr *From, 5377 NestedNameSpecifier *Qualifier, 5378 NamedDecl *FoundDecl, 5379 CXXMethodDecl *Method) { 5380 QualType FromRecordType, DestType; 5381 QualType ImplicitParamRecordType = 5382 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5383 5384 Expr::Classification FromClassification; 5385 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5386 FromRecordType = PT->getPointeeType(); 5387 DestType = Method->getThisType(); 5388 FromClassification = Expr::Classification::makeSimpleLValue(); 5389 } else { 5390 FromRecordType = From->getType(); 5391 DestType = ImplicitParamRecordType; 5392 FromClassification = From->Classify(Context); 5393 5394 // When performing member access on an rvalue, materialize a temporary. 5395 if (From->isRValue()) { 5396 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5397 Method->getRefQualifier() != 5398 RefQualifierKind::RQ_RValue); 5399 } 5400 } 5401 5402 // Note that we always use the true parent context when performing 5403 // the actual argument initialization. 5404 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5405 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5406 Method->getParent()); 5407 if (ICS.isBad()) { 5408 switch (ICS.Bad.Kind) { 5409 case BadConversionSequence::bad_qualifiers: { 5410 Qualifiers FromQs = FromRecordType.getQualifiers(); 5411 Qualifiers ToQs = DestType.getQualifiers(); 5412 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5413 if (CVR) { 5414 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5415 << Method->getDeclName() << FromRecordType << (CVR - 1) 5416 << From->getSourceRange(); 5417 Diag(Method->getLocation(), diag::note_previous_decl) 5418 << Method->getDeclName(); 5419 return ExprError(); 5420 } 5421 break; 5422 } 5423 5424 case BadConversionSequence::lvalue_ref_to_rvalue: 5425 case BadConversionSequence::rvalue_ref_to_lvalue: { 5426 bool IsRValueQualified = 5427 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5428 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5429 << Method->getDeclName() << FromClassification.isRValue() 5430 << IsRValueQualified; 5431 Diag(Method->getLocation(), diag::note_previous_decl) 5432 << Method->getDeclName(); 5433 return ExprError(); 5434 } 5435 5436 case BadConversionSequence::no_conversion: 5437 case BadConversionSequence::unrelated_class: 5438 break; 5439 } 5440 5441 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5442 << ImplicitParamRecordType << FromRecordType 5443 << From->getSourceRange(); 5444 } 5445 5446 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5447 ExprResult FromRes = 5448 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5449 if (FromRes.isInvalid()) 5450 return ExprError(); 5451 From = FromRes.get(); 5452 } 5453 5454 if (!Context.hasSameType(From->getType(), DestType)) { 5455 CastKind CK; 5456 QualType PteeTy = DestType->getPointeeType(); 5457 LangAS DestAS = 5458 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5459 if (FromRecordType.getAddressSpace() != DestAS) 5460 CK = CK_AddressSpaceConversion; 5461 else 5462 CK = CK_NoOp; 5463 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5464 } 5465 return From; 5466 } 5467 5468 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5469 /// expression From to bool (C++0x [conv]p3). 5470 static ImplicitConversionSequence 5471 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5472 // C++ [dcl.init]/17.8: 5473 // - Otherwise, if the initialization is direct-initialization, the source 5474 // type is std::nullptr_t, and the destination type is bool, the initial 5475 // value of the object being initialized is false. 5476 if (From->getType()->isNullPtrType()) 5477 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5478 S.Context.BoolTy, 5479 From->isGLValue()); 5480 5481 // All other direct-initialization of bool is equivalent to an implicit 5482 // conversion to bool in which explicit conversions are permitted. 5483 return TryImplicitConversion(S, From, S.Context.BoolTy, 5484 /*SuppressUserConversions=*/false, 5485 AllowedExplicit::Conversions, 5486 /*InOverloadResolution=*/false, 5487 /*CStyle=*/false, 5488 /*AllowObjCWritebackConversion=*/false, 5489 /*AllowObjCConversionOnExplicit=*/false); 5490 } 5491 5492 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5493 /// of the expression From to bool (C++0x [conv]p3). 5494 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5495 if (checkPlaceholderForOverload(*this, From)) 5496 return ExprError(); 5497 5498 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5499 if (!ICS.isBad()) 5500 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5501 5502 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5503 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5504 << From->getType() << From->getSourceRange(); 5505 return ExprError(); 5506 } 5507 5508 /// Check that the specified conversion is permitted in a converted constant 5509 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5510 /// is acceptable. 5511 static bool CheckConvertedConstantConversions(Sema &S, 5512 StandardConversionSequence &SCS) { 5513 // Since we know that the target type is an integral or unscoped enumeration 5514 // type, most conversion kinds are impossible. All possible First and Third 5515 // conversions are fine. 5516 switch (SCS.Second) { 5517 case ICK_Identity: 5518 case ICK_Function_Conversion: 5519 case ICK_Integral_Promotion: 5520 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5521 case ICK_Zero_Queue_Conversion: 5522 return true; 5523 5524 case ICK_Boolean_Conversion: 5525 // Conversion from an integral or unscoped enumeration type to bool is 5526 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5527 // conversion, so we allow it in a converted constant expression. 5528 // 5529 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5530 // a lot of popular code. We should at least add a warning for this 5531 // (non-conforming) extension. 5532 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5533 SCS.getToType(2)->isBooleanType(); 5534 5535 case ICK_Pointer_Conversion: 5536 case ICK_Pointer_Member: 5537 // C++1z: null pointer conversions and null member pointer conversions are 5538 // only permitted if the source type is std::nullptr_t. 5539 return SCS.getFromType()->isNullPtrType(); 5540 5541 case ICK_Floating_Promotion: 5542 case ICK_Complex_Promotion: 5543 case ICK_Floating_Conversion: 5544 case ICK_Complex_Conversion: 5545 case ICK_Floating_Integral: 5546 case ICK_Compatible_Conversion: 5547 case ICK_Derived_To_Base: 5548 case ICK_Vector_Conversion: 5549 case ICK_SVE_Vector_Conversion: 5550 case ICK_Vector_Splat: 5551 case ICK_Complex_Real: 5552 case ICK_Block_Pointer_Conversion: 5553 case ICK_TransparentUnionConversion: 5554 case ICK_Writeback_Conversion: 5555 case ICK_Zero_Event_Conversion: 5556 case ICK_C_Only_Conversion: 5557 case ICK_Incompatible_Pointer_Conversion: 5558 return false; 5559 5560 case ICK_Lvalue_To_Rvalue: 5561 case ICK_Array_To_Pointer: 5562 case ICK_Function_To_Pointer: 5563 llvm_unreachable("found a first conversion kind in Second"); 5564 5565 case ICK_Qualification: 5566 llvm_unreachable("found a third conversion kind in Second"); 5567 5568 case ICK_Num_Conversion_Kinds: 5569 break; 5570 } 5571 5572 llvm_unreachable("unknown conversion kind"); 5573 } 5574 5575 /// CheckConvertedConstantExpression - Check that the expression From is a 5576 /// converted constant expression of type T, perform the conversion and produce 5577 /// the converted expression, per C++11 [expr.const]p3. 5578 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5579 QualType T, APValue &Value, 5580 Sema::CCEKind CCE, 5581 bool RequireInt) { 5582 assert(S.getLangOpts().CPlusPlus11 && 5583 "converted constant expression outside C++11"); 5584 5585 if (checkPlaceholderForOverload(S, From)) 5586 return ExprError(); 5587 5588 // C++1z [expr.const]p3: 5589 // A converted constant expression of type T is an expression, 5590 // implicitly converted to type T, where the converted 5591 // expression is a constant expression and the implicit conversion 5592 // sequence contains only [... list of conversions ...]. 5593 // C++1z [stmt.if]p2: 5594 // If the if statement is of the form if constexpr, the value of the 5595 // condition shall be a contextually converted constant expression of type 5596 // bool. 5597 ImplicitConversionSequence ICS = 5598 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5599 ? TryContextuallyConvertToBool(S, From) 5600 : TryCopyInitialization(S, From, T, 5601 /*SuppressUserConversions=*/false, 5602 /*InOverloadResolution=*/false, 5603 /*AllowObjCWritebackConversion=*/false, 5604 /*AllowExplicit=*/false); 5605 StandardConversionSequence *SCS = nullptr; 5606 switch (ICS.getKind()) { 5607 case ImplicitConversionSequence::StandardConversion: 5608 SCS = &ICS.Standard; 5609 break; 5610 case ImplicitConversionSequence::UserDefinedConversion: 5611 // We are converting to a non-class type, so the Before sequence 5612 // must be trivial. 5613 SCS = &ICS.UserDefined.After; 5614 break; 5615 case ImplicitConversionSequence::AmbiguousConversion: 5616 case ImplicitConversionSequence::BadConversion: 5617 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5618 return S.Diag(From->getBeginLoc(), 5619 diag::err_typecheck_converted_constant_expression) 5620 << From->getType() << From->getSourceRange() << T; 5621 return ExprError(); 5622 5623 case ImplicitConversionSequence::EllipsisConversion: 5624 llvm_unreachable("ellipsis conversion in converted constant expression"); 5625 } 5626 5627 // Check that we would only use permitted conversions. 5628 if (!CheckConvertedConstantConversions(S, *SCS)) { 5629 return S.Diag(From->getBeginLoc(), 5630 diag::err_typecheck_converted_constant_expression_disallowed) 5631 << From->getType() << From->getSourceRange() << T; 5632 } 5633 // [...] and where the reference binding (if any) binds directly. 5634 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5635 return S.Diag(From->getBeginLoc(), 5636 diag::err_typecheck_converted_constant_expression_indirect) 5637 << From->getType() << From->getSourceRange() << T; 5638 } 5639 5640 ExprResult Result = 5641 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5642 if (Result.isInvalid()) 5643 return Result; 5644 5645 // C++2a [intro.execution]p5: 5646 // A full-expression is [...] a constant-expression [...] 5647 Result = 5648 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5649 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5650 if (Result.isInvalid()) 5651 return Result; 5652 5653 // Check for a narrowing implicit conversion. 5654 bool ReturnPreNarrowingValue = false; 5655 APValue PreNarrowingValue; 5656 QualType PreNarrowingType; 5657 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5658 PreNarrowingType)) { 5659 case NK_Dependent_Narrowing: 5660 // Implicit conversion to a narrower type, but the expression is 5661 // value-dependent so we can't tell whether it's actually narrowing. 5662 case NK_Variable_Narrowing: 5663 // Implicit conversion to a narrower type, and the value is not a constant 5664 // expression. We'll diagnose this in a moment. 5665 case NK_Not_Narrowing: 5666 break; 5667 5668 case NK_Constant_Narrowing: 5669 if (CCE == Sema::CCEK_ArrayBound && 5670 PreNarrowingType->isIntegralOrEnumerationType() && 5671 PreNarrowingValue.isInt()) { 5672 // Don't diagnose array bound narrowing here; we produce more precise 5673 // errors by allowing the un-narrowed value through. 5674 ReturnPreNarrowingValue = true; 5675 break; 5676 } 5677 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5678 << CCE << /*Constant*/ 1 5679 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5680 break; 5681 5682 case NK_Type_Narrowing: 5683 // FIXME: It would be better to diagnose that the expression is not a 5684 // constant expression. 5685 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5686 << CCE << /*Constant*/ 0 << From->getType() << T; 5687 break; 5688 } 5689 5690 if (Result.get()->isValueDependent()) { 5691 Value = APValue(); 5692 return Result; 5693 } 5694 5695 // Check the expression is a constant expression. 5696 SmallVector<PartialDiagnosticAt, 8> Notes; 5697 Expr::EvalResult Eval; 5698 Eval.Diag = &Notes; 5699 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5700 ? Expr::EvaluateForMangling 5701 : Expr::EvaluateForCodeGen; 5702 5703 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5704 (RequireInt && !Eval.Val.isInt())) { 5705 // The expression can't be folded, so we can't keep it at this position in 5706 // the AST. 5707 Result = ExprError(); 5708 } else { 5709 Value = Eval.Val; 5710 5711 if (Notes.empty()) { 5712 // It's a constant expression. 5713 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5714 if (ReturnPreNarrowingValue) 5715 Value = std::move(PreNarrowingValue); 5716 return E; 5717 } 5718 } 5719 5720 // It's not a constant expression. Produce an appropriate diagnostic. 5721 if (Notes.size() == 1 && 5722 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5723 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5724 else { 5725 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5726 << CCE << From->getSourceRange(); 5727 for (unsigned I = 0; I < Notes.size(); ++I) 5728 S.Diag(Notes[I].first, Notes[I].second); 5729 } 5730 return ExprError(); 5731 } 5732 5733 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5734 APValue &Value, CCEKind CCE) { 5735 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5736 } 5737 5738 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5739 llvm::APSInt &Value, 5740 CCEKind CCE) { 5741 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5742 5743 APValue V; 5744 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5745 if (!R.isInvalid() && !R.get()->isValueDependent()) 5746 Value = V.getInt(); 5747 return R; 5748 } 5749 5750 5751 /// dropPointerConversions - If the given standard conversion sequence 5752 /// involves any pointer conversions, remove them. This may change 5753 /// the result type of the conversion sequence. 5754 static void dropPointerConversion(StandardConversionSequence &SCS) { 5755 if (SCS.Second == ICK_Pointer_Conversion) { 5756 SCS.Second = ICK_Identity; 5757 SCS.Third = ICK_Identity; 5758 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5759 } 5760 } 5761 5762 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5763 /// convert the expression From to an Objective-C pointer type. 5764 static ImplicitConversionSequence 5765 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5766 // Do an implicit conversion to 'id'. 5767 QualType Ty = S.Context.getObjCIdType(); 5768 ImplicitConversionSequence ICS 5769 = TryImplicitConversion(S, From, Ty, 5770 // FIXME: Are these flags correct? 5771 /*SuppressUserConversions=*/false, 5772 AllowedExplicit::Conversions, 5773 /*InOverloadResolution=*/false, 5774 /*CStyle=*/false, 5775 /*AllowObjCWritebackConversion=*/false, 5776 /*AllowObjCConversionOnExplicit=*/true); 5777 5778 // Strip off any final conversions to 'id'. 5779 switch (ICS.getKind()) { 5780 case ImplicitConversionSequence::BadConversion: 5781 case ImplicitConversionSequence::AmbiguousConversion: 5782 case ImplicitConversionSequence::EllipsisConversion: 5783 break; 5784 5785 case ImplicitConversionSequence::UserDefinedConversion: 5786 dropPointerConversion(ICS.UserDefined.After); 5787 break; 5788 5789 case ImplicitConversionSequence::StandardConversion: 5790 dropPointerConversion(ICS.Standard); 5791 break; 5792 } 5793 5794 return ICS; 5795 } 5796 5797 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5798 /// conversion of the expression From to an Objective-C pointer type. 5799 /// Returns a valid but null ExprResult if no conversion sequence exists. 5800 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5801 if (checkPlaceholderForOverload(*this, From)) 5802 return ExprError(); 5803 5804 QualType Ty = Context.getObjCIdType(); 5805 ImplicitConversionSequence ICS = 5806 TryContextuallyConvertToObjCPointer(*this, From); 5807 if (!ICS.isBad()) 5808 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5809 return ExprResult(); 5810 } 5811 5812 /// Determine whether the provided type is an integral type, or an enumeration 5813 /// type of a permitted flavor. 5814 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5815 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5816 : T->isIntegralOrUnscopedEnumerationType(); 5817 } 5818 5819 static ExprResult 5820 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5821 Sema::ContextualImplicitConverter &Converter, 5822 QualType T, UnresolvedSetImpl &ViableConversions) { 5823 5824 if (Converter.Suppress) 5825 return ExprError(); 5826 5827 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5828 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5829 CXXConversionDecl *Conv = 5830 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5831 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5832 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5833 } 5834 return From; 5835 } 5836 5837 static bool 5838 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5839 Sema::ContextualImplicitConverter &Converter, 5840 QualType T, bool HadMultipleCandidates, 5841 UnresolvedSetImpl &ExplicitConversions) { 5842 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5843 DeclAccessPair Found = ExplicitConversions[0]; 5844 CXXConversionDecl *Conversion = 5845 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5846 5847 // The user probably meant to invoke the given explicit 5848 // conversion; use it. 5849 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5850 std::string TypeStr; 5851 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5852 5853 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5854 << FixItHint::CreateInsertion(From->getBeginLoc(), 5855 "static_cast<" + TypeStr + ">(") 5856 << FixItHint::CreateInsertion( 5857 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5858 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5859 5860 // If we aren't in a SFINAE context, build a call to the 5861 // explicit conversion function. 5862 if (SemaRef.isSFINAEContext()) 5863 return true; 5864 5865 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5866 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5867 HadMultipleCandidates); 5868 if (Result.isInvalid()) 5869 return true; 5870 // Record usage of conversion in an implicit cast. 5871 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5872 CK_UserDefinedConversion, Result.get(), 5873 nullptr, Result.get()->getValueKind()); 5874 } 5875 return false; 5876 } 5877 5878 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5879 Sema::ContextualImplicitConverter &Converter, 5880 QualType T, bool HadMultipleCandidates, 5881 DeclAccessPair &Found) { 5882 CXXConversionDecl *Conversion = 5883 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5884 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5885 5886 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5887 if (!Converter.SuppressConversion) { 5888 if (SemaRef.isSFINAEContext()) 5889 return true; 5890 5891 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5892 << From->getSourceRange(); 5893 } 5894 5895 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5896 HadMultipleCandidates); 5897 if (Result.isInvalid()) 5898 return true; 5899 // Record usage of conversion in an implicit cast. 5900 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5901 CK_UserDefinedConversion, Result.get(), 5902 nullptr, Result.get()->getValueKind()); 5903 return false; 5904 } 5905 5906 static ExprResult finishContextualImplicitConversion( 5907 Sema &SemaRef, SourceLocation Loc, Expr *From, 5908 Sema::ContextualImplicitConverter &Converter) { 5909 if (!Converter.match(From->getType()) && !Converter.Suppress) 5910 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5911 << From->getSourceRange(); 5912 5913 return SemaRef.DefaultLvalueConversion(From); 5914 } 5915 5916 static void 5917 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5918 UnresolvedSetImpl &ViableConversions, 5919 OverloadCandidateSet &CandidateSet) { 5920 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5921 DeclAccessPair FoundDecl = ViableConversions[I]; 5922 NamedDecl *D = FoundDecl.getDecl(); 5923 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5924 if (isa<UsingShadowDecl>(D)) 5925 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5926 5927 CXXConversionDecl *Conv; 5928 FunctionTemplateDecl *ConvTemplate; 5929 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5930 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5931 else 5932 Conv = cast<CXXConversionDecl>(D); 5933 5934 if (ConvTemplate) 5935 SemaRef.AddTemplateConversionCandidate( 5936 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5937 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5938 else 5939 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5940 ToType, CandidateSet, 5941 /*AllowObjCConversionOnExplicit=*/false, 5942 /*AllowExplicit*/ true); 5943 } 5944 } 5945 5946 /// Attempt to convert the given expression to a type which is accepted 5947 /// by the given converter. 5948 /// 5949 /// This routine will attempt to convert an expression of class type to a 5950 /// type accepted by the specified converter. In C++11 and before, the class 5951 /// must have a single non-explicit conversion function converting to a matching 5952 /// type. In C++1y, there can be multiple such conversion functions, but only 5953 /// one target type. 5954 /// 5955 /// \param Loc The source location of the construct that requires the 5956 /// conversion. 5957 /// 5958 /// \param From The expression we're converting from. 5959 /// 5960 /// \param Converter Used to control and diagnose the conversion process. 5961 /// 5962 /// \returns The expression, converted to an integral or enumeration type if 5963 /// successful. 5964 ExprResult Sema::PerformContextualImplicitConversion( 5965 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5966 // We can't perform any more checking for type-dependent expressions. 5967 if (From->isTypeDependent()) 5968 return From; 5969 5970 // Process placeholders immediately. 5971 if (From->hasPlaceholderType()) { 5972 ExprResult result = CheckPlaceholderExpr(From); 5973 if (result.isInvalid()) 5974 return result; 5975 From = result.get(); 5976 } 5977 5978 // If the expression already has a matching type, we're golden. 5979 QualType T = From->getType(); 5980 if (Converter.match(T)) 5981 return DefaultLvalueConversion(From); 5982 5983 // FIXME: Check for missing '()' if T is a function type? 5984 5985 // We can only perform contextual implicit conversions on objects of class 5986 // type. 5987 const RecordType *RecordTy = T->getAs<RecordType>(); 5988 if (!RecordTy || !getLangOpts().CPlusPlus) { 5989 if (!Converter.Suppress) 5990 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5991 return From; 5992 } 5993 5994 // We must have a complete class type. 5995 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5996 ContextualImplicitConverter &Converter; 5997 Expr *From; 5998 5999 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6000 : Converter(Converter), From(From) {} 6001 6002 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6003 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6004 } 6005 } IncompleteDiagnoser(Converter, From); 6006 6007 if (Converter.Suppress ? !isCompleteType(Loc, T) 6008 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6009 return From; 6010 6011 // Look for a conversion to an integral or enumeration type. 6012 UnresolvedSet<4> 6013 ViableConversions; // These are *potentially* viable in C++1y. 6014 UnresolvedSet<4> ExplicitConversions; 6015 const auto &Conversions = 6016 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6017 6018 bool HadMultipleCandidates = 6019 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6020 6021 // To check that there is only one target type, in C++1y: 6022 QualType ToType; 6023 bool HasUniqueTargetType = true; 6024 6025 // Collect explicit or viable (potentially in C++1y) conversions. 6026 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6027 NamedDecl *D = (*I)->getUnderlyingDecl(); 6028 CXXConversionDecl *Conversion; 6029 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6030 if (ConvTemplate) { 6031 if (getLangOpts().CPlusPlus14) 6032 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6033 else 6034 continue; // C++11 does not consider conversion operator templates(?). 6035 } else 6036 Conversion = cast<CXXConversionDecl>(D); 6037 6038 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6039 "Conversion operator templates are considered potentially " 6040 "viable in C++1y"); 6041 6042 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6043 if (Converter.match(CurToType) || ConvTemplate) { 6044 6045 if (Conversion->isExplicit()) { 6046 // FIXME: For C++1y, do we need this restriction? 6047 // cf. diagnoseNoViableConversion() 6048 if (!ConvTemplate) 6049 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6050 } else { 6051 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6052 if (ToType.isNull()) 6053 ToType = CurToType.getUnqualifiedType(); 6054 else if (HasUniqueTargetType && 6055 (CurToType.getUnqualifiedType() != ToType)) 6056 HasUniqueTargetType = false; 6057 } 6058 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6059 } 6060 } 6061 } 6062 6063 if (getLangOpts().CPlusPlus14) { 6064 // C++1y [conv]p6: 6065 // ... An expression e of class type E appearing in such a context 6066 // is said to be contextually implicitly converted to a specified 6067 // type T and is well-formed if and only if e can be implicitly 6068 // converted to a type T that is determined as follows: E is searched 6069 // for conversion functions whose return type is cv T or reference to 6070 // cv T such that T is allowed by the context. There shall be 6071 // exactly one such T. 6072 6073 // If no unique T is found: 6074 if (ToType.isNull()) { 6075 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6076 HadMultipleCandidates, 6077 ExplicitConversions)) 6078 return ExprError(); 6079 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6080 } 6081 6082 // If more than one unique Ts are found: 6083 if (!HasUniqueTargetType) 6084 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6085 ViableConversions); 6086 6087 // If one unique T is found: 6088 // First, build a candidate set from the previously recorded 6089 // potentially viable conversions. 6090 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6091 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6092 CandidateSet); 6093 6094 // Then, perform overload resolution over the candidate set. 6095 OverloadCandidateSet::iterator Best; 6096 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6097 case OR_Success: { 6098 // Apply this conversion. 6099 DeclAccessPair Found = 6100 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6101 if (recordConversion(*this, Loc, From, Converter, T, 6102 HadMultipleCandidates, Found)) 6103 return ExprError(); 6104 break; 6105 } 6106 case OR_Ambiguous: 6107 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6108 ViableConversions); 6109 case OR_No_Viable_Function: 6110 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6111 HadMultipleCandidates, 6112 ExplicitConversions)) 6113 return ExprError(); 6114 LLVM_FALLTHROUGH; 6115 case OR_Deleted: 6116 // We'll complain below about a non-integral condition type. 6117 break; 6118 } 6119 } else { 6120 switch (ViableConversions.size()) { 6121 case 0: { 6122 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6123 HadMultipleCandidates, 6124 ExplicitConversions)) 6125 return ExprError(); 6126 6127 // We'll complain below about a non-integral condition type. 6128 break; 6129 } 6130 case 1: { 6131 // Apply this conversion. 6132 DeclAccessPair Found = ViableConversions[0]; 6133 if (recordConversion(*this, Loc, From, Converter, T, 6134 HadMultipleCandidates, Found)) 6135 return ExprError(); 6136 break; 6137 } 6138 default: 6139 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6140 ViableConversions); 6141 } 6142 } 6143 6144 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6145 } 6146 6147 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6148 /// an acceptable non-member overloaded operator for a call whose 6149 /// arguments have types T1 (and, if non-empty, T2). This routine 6150 /// implements the check in C++ [over.match.oper]p3b2 concerning 6151 /// enumeration types. 6152 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6153 FunctionDecl *Fn, 6154 ArrayRef<Expr *> Args) { 6155 QualType T1 = Args[0]->getType(); 6156 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6157 6158 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6159 return true; 6160 6161 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6162 return true; 6163 6164 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6165 if (Proto->getNumParams() < 1) 6166 return false; 6167 6168 if (T1->isEnumeralType()) { 6169 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6170 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6171 return true; 6172 } 6173 6174 if (Proto->getNumParams() < 2) 6175 return false; 6176 6177 if (!T2.isNull() && T2->isEnumeralType()) { 6178 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6179 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6180 return true; 6181 } 6182 6183 return false; 6184 } 6185 6186 /// AddOverloadCandidate - Adds the given function to the set of 6187 /// candidate functions, using the given function call arguments. If 6188 /// @p SuppressUserConversions, then don't allow user-defined 6189 /// conversions via constructors or conversion operators. 6190 /// 6191 /// \param PartialOverloading true if we are performing "partial" overloading 6192 /// based on an incomplete set of function arguments. This feature is used by 6193 /// code completion. 6194 void Sema::AddOverloadCandidate( 6195 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6196 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6197 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6198 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6199 OverloadCandidateParamOrder PO) { 6200 const FunctionProtoType *Proto 6201 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6202 assert(Proto && "Functions without a prototype cannot be overloaded"); 6203 assert(!Function->getDescribedFunctionTemplate() && 6204 "Use AddTemplateOverloadCandidate for function templates"); 6205 6206 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6207 if (!isa<CXXConstructorDecl>(Method)) { 6208 // If we get here, it's because we're calling a member function 6209 // that is named without a member access expression (e.g., 6210 // "this->f") that was either written explicitly or created 6211 // implicitly. This can happen with a qualified call to a member 6212 // function, e.g., X::f(). We use an empty type for the implied 6213 // object argument (C++ [over.call.func]p3), and the acting context 6214 // is irrelevant. 6215 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6216 Expr::Classification::makeSimpleLValue(), Args, 6217 CandidateSet, SuppressUserConversions, 6218 PartialOverloading, EarlyConversions, PO); 6219 return; 6220 } 6221 // We treat a constructor like a non-member function, since its object 6222 // argument doesn't participate in overload resolution. 6223 } 6224 6225 if (!CandidateSet.isNewCandidate(Function, PO)) 6226 return; 6227 6228 // C++11 [class.copy]p11: [DR1402] 6229 // A defaulted move constructor that is defined as deleted is ignored by 6230 // overload resolution. 6231 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6232 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6233 Constructor->isMoveConstructor()) 6234 return; 6235 6236 // Overload resolution is always an unevaluated context. 6237 EnterExpressionEvaluationContext Unevaluated( 6238 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6239 6240 // C++ [over.match.oper]p3: 6241 // if no operand has a class type, only those non-member functions in the 6242 // lookup set that have a first parameter of type T1 or "reference to 6243 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6244 // is a right operand) a second parameter of type T2 or "reference to 6245 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6246 // candidate functions. 6247 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6248 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6249 return; 6250 6251 // Add this candidate 6252 OverloadCandidate &Candidate = 6253 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6254 Candidate.FoundDecl = FoundDecl; 6255 Candidate.Function = Function; 6256 Candidate.Viable = true; 6257 Candidate.RewriteKind = 6258 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6259 Candidate.IsSurrogate = false; 6260 Candidate.IsADLCandidate = IsADLCandidate; 6261 Candidate.IgnoreObjectArgument = false; 6262 Candidate.ExplicitCallArguments = Args.size(); 6263 6264 // Explicit functions are not actually candidates at all if we're not 6265 // allowing them in this context, but keep them around so we can point 6266 // to them in diagnostics. 6267 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6268 Candidate.Viable = false; 6269 Candidate.FailureKind = ovl_fail_explicit; 6270 return; 6271 } 6272 6273 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6274 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6275 Candidate.Viable = false; 6276 Candidate.FailureKind = ovl_non_default_multiversion_function; 6277 return; 6278 } 6279 6280 if (Constructor) { 6281 // C++ [class.copy]p3: 6282 // A member function template is never instantiated to perform the copy 6283 // of a class object to an object of its class type. 6284 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6285 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6286 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6287 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6288 ClassType))) { 6289 Candidate.Viable = false; 6290 Candidate.FailureKind = ovl_fail_illegal_constructor; 6291 return; 6292 } 6293 6294 // C++ [over.match.funcs]p8: (proposed DR resolution) 6295 // A constructor inherited from class type C that has a first parameter 6296 // of type "reference to P" (including such a constructor instantiated 6297 // from a template) is excluded from the set of candidate functions when 6298 // constructing an object of type cv D if the argument list has exactly 6299 // one argument and D is reference-related to P and P is reference-related 6300 // to C. 6301 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6302 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6303 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6304 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6305 QualType C = Context.getRecordType(Constructor->getParent()); 6306 QualType D = Context.getRecordType(Shadow->getParent()); 6307 SourceLocation Loc = Args.front()->getExprLoc(); 6308 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6309 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6310 Candidate.Viable = false; 6311 Candidate.FailureKind = ovl_fail_inhctor_slice; 6312 return; 6313 } 6314 } 6315 6316 // Check that the constructor is capable of constructing an object in the 6317 // destination address space. 6318 if (!Qualifiers::isAddressSpaceSupersetOf( 6319 Constructor->getMethodQualifiers().getAddressSpace(), 6320 CandidateSet.getDestAS())) { 6321 Candidate.Viable = false; 6322 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6323 } 6324 } 6325 6326 unsigned NumParams = Proto->getNumParams(); 6327 6328 // (C++ 13.3.2p2): A candidate function having fewer than m 6329 // parameters is viable only if it has an ellipsis in its parameter 6330 // list (8.3.5). 6331 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6332 !Proto->isVariadic()) { 6333 Candidate.Viable = false; 6334 Candidate.FailureKind = ovl_fail_too_many_arguments; 6335 return; 6336 } 6337 6338 // (C++ 13.3.2p2): A candidate function having more than m parameters 6339 // is viable only if the (m+1)st parameter has a default argument 6340 // (8.3.6). For the purposes of overload resolution, the 6341 // parameter list is truncated on the right, so that there are 6342 // exactly m parameters. 6343 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6344 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6345 // Not enough arguments. 6346 Candidate.Viable = false; 6347 Candidate.FailureKind = ovl_fail_too_few_arguments; 6348 return; 6349 } 6350 6351 // (CUDA B.1): Check for invalid calls between targets. 6352 if (getLangOpts().CUDA) 6353 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6354 // Skip the check for callers that are implicit members, because in this 6355 // case we may not yet know what the member's target is; the target is 6356 // inferred for the member automatically, based on the bases and fields of 6357 // the class. 6358 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6359 Candidate.Viable = false; 6360 Candidate.FailureKind = ovl_fail_bad_target; 6361 return; 6362 } 6363 6364 if (Function->getTrailingRequiresClause()) { 6365 ConstraintSatisfaction Satisfaction; 6366 if (CheckFunctionConstraints(Function, Satisfaction) || 6367 !Satisfaction.IsSatisfied) { 6368 Candidate.Viable = false; 6369 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6370 return; 6371 } 6372 } 6373 6374 // Determine the implicit conversion sequences for each of the 6375 // arguments. 6376 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6377 unsigned ConvIdx = 6378 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6379 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6380 // We already formed a conversion sequence for this parameter during 6381 // template argument deduction. 6382 } else if (ArgIdx < NumParams) { 6383 // (C++ 13.3.2p3): for F to be a viable function, there shall 6384 // exist for each argument an implicit conversion sequence 6385 // (13.3.3.1) that converts that argument to the corresponding 6386 // parameter of F. 6387 QualType ParamType = Proto->getParamType(ArgIdx); 6388 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6389 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6390 /*InOverloadResolution=*/true, 6391 /*AllowObjCWritebackConversion=*/ 6392 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6393 if (Candidate.Conversions[ConvIdx].isBad()) { 6394 Candidate.Viable = false; 6395 Candidate.FailureKind = ovl_fail_bad_conversion; 6396 return; 6397 } 6398 } else { 6399 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6400 // argument for which there is no corresponding parameter is 6401 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6402 Candidate.Conversions[ConvIdx].setEllipsis(); 6403 } 6404 } 6405 6406 if (EnableIfAttr *FailedAttr = 6407 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6408 Candidate.Viable = false; 6409 Candidate.FailureKind = ovl_fail_enable_if; 6410 Candidate.DeductionFailure.Data = FailedAttr; 6411 return; 6412 } 6413 6414 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6415 Candidate.Viable = false; 6416 Candidate.FailureKind = ovl_fail_ext_disabled; 6417 return; 6418 } 6419 } 6420 6421 ObjCMethodDecl * 6422 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6423 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6424 if (Methods.size() <= 1) 6425 return nullptr; 6426 6427 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6428 bool Match = true; 6429 ObjCMethodDecl *Method = Methods[b]; 6430 unsigned NumNamedArgs = Sel.getNumArgs(); 6431 // Method might have more arguments than selector indicates. This is due 6432 // to addition of c-style arguments in method. 6433 if (Method->param_size() > NumNamedArgs) 6434 NumNamedArgs = Method->param_size(); 6435 if (Args.size() < NumNamedArgs) 6436 continue; 6437 6438 for (unsigned i = 0; i < NumNamedArgs; i++) { 6439 // We can't do any type-checking on a type-dependent argument. 6440 if (Args[i]->isTypeDependent()) { 6441 Match = false; 6442 break; 6443 } 6444 6445 ParmVarDecl *param = Method->parameters()[i]; 6446 Expr *argExpr = Args[i]; 6447 assert(argExpr && "SelectBestMethod(): missing expression"); 6448 6449 // Strip the unbridged-cast placeholder expression off unless it's 6450 // a consumed argument. 6451 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6452 !param->hasAttr<CFConsumedAttr>()) 6453 argExpr = stripARCUnbridgedCast(argExpr); 6454 6455 // If the parameter is __unknown_anytype, move on to the next method. 6456 if (param->getType() == Context.UnknownAnyTy) { 6457 Match = false; 6458 break; 6459 } 6460 6461 ImplicitConversionSequence ConversionState 6462 = TryCopyInitialization(*this, argExpr, param->getType(), 6463 /*SuppressUserConversions*/false, 6464 /*InOverloadResolution=*/true, 6465 /*AllowObjCWritebackConversion=*/ 6466 getLangOpts().ObjCAutoRefCount, 6467 /*AllowExplicit*/false); 6468 // This function looks for a reasonably-exact match, so we consider 6469 // incompatible pointer conversions to be a failure here. 6470 if (ConversionState.isBad() || 6471 (ConversionState.isStandard() && 6472 ConversionState.Standard.Second == 6473 ICK_Incompatible_Pointer_Conversion)) { 6474 Match = false; 6475 break; 6476 } 6477 } 6478 // Promote additional arguments to variadic methods. 6479 if (Match && Method->isVariadic()) { 6480 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6481 if (Args[i]->isTypeDependent()) { 6482 Match = false; 6483 break; 6484 } 6485 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6486 nullptr); 6487 if (Arg.isInvalid()) { 6488 Match = false; 6489 break; 6490 } 6491 } 6492 } else { 6493 // Check for extra arguments to non-variadic methods. 6494 if (Args.size() != NumNamedArgs) 6495 Match = false; 6496 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6497 // Special case when selectors have no argument. In this case, select 6498 // one with the most general result type of 'id'. 6499 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6500 QualType ReturnT = Methods[b]->getReturnType(); 6501 if (ReturnT->isObjCIdType()) 6502 return Methods[b]; 6503 } 6504 } 6505 } 6506 6507 if (Match) 6508 return Method; 6509 } 6510 return nullptr; 6511 } 6512 6513 static bool convertArgsForAvailabilityChecks( 6514 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6515 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6516 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6517 if (ThisArg) { 6518 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6519 assert(!isa<CXXConstructorDecl>(Method) && 6520 "Shouldn't have `this` for ctors!"); 6521 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6522 ExprResult R = S.PerformObjectArgumentInitialization( 6523 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6524 if (R.isInvalid()) 6525 return false; 6526 ConvertedThis = R.get(); 6527 } else { 6528 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6529 (void)MD; 6530 assert((MissingImplicitThis || MD->isStatic() || 6531 isa<CXXConstructorDecl>(MD)) && 6532 "Expected `this` for non-ctor instance methods"); 6533 } 6534 ConvertedThis = nullptr; 6535 } 6536 6537 // Ignore any variadic arguments. Converting them is pointless, since the 6538 // user can't refer to them in the function condition. 6539 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6540 6541 // Convert the arguments. 6542 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6543 ExprResult R; 6544 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6545 S.Context, Function->getParamDecl(I)), 6546 SourceLocation(), Args[I]); 6547 6548 if (R.isInvalid()) 6549 return false; 6550 6551 ConvertedArgs.push_back(R.get()); 6552 } 6553 6554 if (Trap.hasErrorOccurred()) 6555 return false; 6556 6557 // Push default arguments if needed. 6558 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6559 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6560 ParmVarDecl *P = Function->getParamDecl(i); 6561 if (!P->hasDefaultArg()) 6562 return false; 6563 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6564 if (R.isInvalid()) 6565 return false; 6566 ConvertedArgs.push_back(R.get()); 6567 } 6568 6569 if (Trap.hasErrorOccurred()) 6570 return false; 6571 } 6572 return true; 6573 } 6574 6575 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6576 SourceLocation CallLoc, 6577 ArrayRef<Expr *> Args, 6578 bool MissingImplicitThis) { 6579 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6580 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6581 return nullptr; 6582 6583 SFINAETrap Trap(*this); 6584 SmallVector<Expr *, 16> ConvertedArgs; 6585 // FIXME: We should look into making enable_if late-parsed. 6586 Expr *DiscardedThis; 6587 if (!convertArgsForAvailabilityChecks( 6588 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6589 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6590 return *EnableIfAttrs.begin(); 6591 6592 for (auto *EIA : EnableIfAttrs) { 6593 APValue Result; 6594 // FIXME: This doesn't consider value-dependent cases, because doing so is 6595 // very difficult. Ideally, we should handle them more gracefully. 6596 if (EIA->getCond()->isValueDependent() || 6597 !EIA->getCond()->EvaluateWithSubstitution( 6598 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6599 return EIA; 6600 6601 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6602 return EIA; 6603 } 6604 return nullptr; 6605 } 6606 6607 template <typename CheckFn> 6608 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6609 bool ArgDependent, SourceLocation Loc, 6610 CheckFn &&IsSuccessful) { 6611 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6612 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6613 if (ArgDependent == DIA->getArgDependent()) 6614 Attrs.push_back(DIA); 6615 } 6616 6617 // Common case: No diagnose_if attributes, so we can quit early. 6618 if (Attrs.empty()) 6619 return false; 6620 6621 auto WarningBegin = std::stable_partition( 6622 Attrs.begin(), Attrs.end(), 6623 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6624 6625 // Note that diagnose_if attributes are late-parsed, so they appear in the 6626 // correct order (unlike enable_if attributes). 6627 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6628 IsSuccessful); 6629 if (ErrAttr != WarningBegin) { 6630 const DiagnoseIfAttr *DIA = *ErrAttr; 6631 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6632 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6633 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6634 return true; 6635 } 6636 6637 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6638 if (IsSuccessful(DIA)) { 6639 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6640 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6641 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6642 } 6643 6644 return false; 6645 } 6646 6647 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6648 const Expr *ThisArg, 6649 ArrayRef<const Expr *> Args, 6650 SourceLocation Loc) { 6651 return diagnoseDiagnoseIfAttrsWith( 6652 *this, Function, /*ArgDependent=*/true, Loc, 6653 [&](const DiagnoseIfAttr *DIA) { 6654 APValue Result; 6655 // It's sane to use the same Args for any redecl of this function, since 6656 // EvaluateWithSubstitution only cares about the position of each 6657 // argument in the arg list, not the ParmVarDecl* it maps to. 6658 if (!DIA->getCond()->EvaluateWithSubstitution( 6659 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6660 return false; 6661 return Result.isInt() && Result.getInt().getBoolValue(); 6662 }); 6663 } 6664 6665 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6666 SourceLocation Loc) { 6667 return diagnoseDiagnoseIfAttrsWith( 6668 *this, ND, /*ArgDependent=*/false, Loc, 6669 [&](const DiagnoseIfAttr *DIA) { 6670 bool Result; 6671 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6672 Result; 6673 }); 6674 } 6675 6676 /// Add all of the function declarations in the given function set to 6677 /// the overload candidate set. 6678 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6679 ArrayRef<Expr *> Args, 6680 OverloadCandidateSet &CandidateSet, 6681 TemplateArgumentListInfo *ExplicitTemplateArgs, 6682 bool SuppressUserConversions, 6683 bool PartialOverloading, 6684 bool FirstArgumentIsBase) { 6685 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6686 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6687 ArrayRef<Expr *> FunctionArgs = Args; 6688 6689 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6690 FunctionDecl *FD = 6691 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6692 6693 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6694 QualType ObjectType; 6695 Expr::Classification ObjectClassification; 6696 if (Args.size() > 0) { 6697 if (Expr *E = Args[0]) { 6698 // Use the explicit base to restrict the lookup: 6699 ObjectType = E->getType(); 6700 // Pointers in the object arguments are implicitly dereferenced, so we 6701 // always classify them as l-values. 6702 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6703 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6704 else 6705 ObjectClassification = E->Classify(Context); 6706 } // .. else there is an implicit base. 6707 FunctionArgs = Args.slice(1); 6708 } 6709 if (FunTmpl) { 6710 AddMethodTemplateCandidate( 6711 FunTmpl, F.getPair(), 6712 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6713 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6714 FunctionArgs, CandidateSet, SuppressUserConversions, 6715 PartialOverloading); 6716 } else { 6717 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6718 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6719 ObjectClassification, FunctionArgs, CandidateSet, 6720 SuppressUserConversions, PartialOverloading); 6721 } 6722 } else { 6723 // This branch handles both standalone functions and static methods. 6724 6725 // Slice the first argument (which is the base) when we access 6726 // static method as non-static. 6727 if (Args.size() > 0 && 6728 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6729 !isa<CXXConstructorDecl>(FD)))) { 6730 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6731 FunctionArgs = Args.slice(1); 6732 } 6733 if (FunTmpl) { 6734 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6735 ExplicitTemplateArgs, FunctionArgs, 6736 CandidateSet, SuppressUserConversions, 6737 PartialOverloading); 6738 } else { 6739 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6740 SuppressUserConversions, PartialOverloading); 6741 } 6742 } 6743 } 6744 } 6745 6746 /// AddMethodCandidate - Adds a named decl (which is some kind of 6747 /// method) as a method candidate to the given overload set. 6748 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6749 Expr::Classification ObjectClassification, 6750 ArrayRef<Expr *> Args, 6751 OverloadCandidateSet &CandidateSet, 6752 bool SuppressUserConversions, 6753 OverloadCandidateParamOrder PO) { 6754 NamedDecl *Decl = FoundDecl.getDecl(); 6755 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6756 6757 if (isa<UsingShadowDecl>(Decl)) 6758 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6759 6760 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6761 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6762 "Expected a member function template"); 6763 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6764 /*ExplicitArgs*/ nullptr, ObjectType, 6765 ObjectClassification, Args, CandidateSet, 6766 SuppressUserConversions, false, PO); 6767 } else { 6768 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6769 ObjectType, ObjectClassification, Args, CandidateSet, 6770 SuppressUserConversions, false, None, PO); 6771 } 6772 } 6773 6774 /// AddMethodCandidate - Adds the given C++ member function to the set 6775 /// of candidate functions, using the given function call arguments 6776 /// and the object argument (@c Object). For example, in a call 6777 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6778 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6779 /// allow user-defined conversions via constructors or conversion 6780 /// operators. 6781 void 6782 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6783 CXXRecordDecl *ActingContext, QualType ObjectType, 6784 Expr::Classification ObjectClassification, 6785 ArrayRef<Expr *> Args, 6786 OverloadCandidateSet &CandidateSet, 6787 bool SuppressUserConversions, 6788 bool PartialOverloading, 6789 ConversionSequenceList EarlyConversions, 6790 OverloadCandidateParamOrder PO) { 6791 const FunctionProtoType *Proto 6792 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6793 assert(Proto && "Methods without a prototype cannot be overloaded"); 6794 assert(!isa<CXXConstructorDecl>(Method) && 6795 "Use AddOverloadCandidate for constructors"); 6796 6797 if (!CandidateSet.isNewCandidate(Method, PO)) 6798 return; 6799 6800 // C++11 [class.copy]p23: [DR1402] 6801 // A defaulted move assignment operator that is defined as deleted is 6802 // ignored by overload resolution. 6803 if (Method->isDefaulted() && Method->isDeleted() && 6804 Method->isMoveAssignmentOperator()) 6805 return; 6806 6807 // Overload resolution is always an unevaluated context. 6808 EnterExpressionEvaluationContext Unevaluated( 6809 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6810 6811 // Add this candidate 6812 OverloadCandidate &Candidate = 6813 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6814 Candidate.FoundDecl = FoundDecl; 6815 Candidate.Function = Method; 6816 Candidate.RewriteKind = 6817 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6818 Candidate.IsSurrogate = false; 6819 Candidate.IgnoreObjectArgument = false; 6820 Candidate.ExplicitCallArguments = Args.size(); 6821 6822 unsigned NumParams = Proto->getNumParams(); 6823 6824 // (C++ 13.3.2p2): A candidate function having fewer than m 6825 // parameters is viable only if it has an ellipsis in its parameter 6826 // list (8.3.5). 6827 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6828 !Proto->isVariadic()) { 6829 Candidate.Viable = false; 6830 Candidate.FailureKind = ovl_fail_too_many_arguments; 6831 return; 6832 } 6833 6834 // (C++ 13.3.2p2): A candidate function having more than m parameters 6835 // is viable only if the (m+1)st parameter has a default argument 6836 // (8.3.6). For the purposes of overload resolution, the 6837 // parameter list is truncated on the right, so that there are 6838 // exactly m parameters. 6839 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6840 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6841 // Not enough arguments. 6842 Candidate.Viable = false; 6843 Candidate.FailureKind = ovl_fail_too_few_arguments; 6844 return; 6845 } 6846 6847 Candidate.Viable = true; 6848 6849 if (Method->isStatic() || ObjectType.isNull()) 6850 // The implicit object argument is ignored. 6851 Candidate.IgnoreObjectArgument = true; 6852 else { 6853 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6854 // Determine the implicit conversion sequence for the object 6855 // parameter. 6856 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6857 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6858 Method, ActingContext); 6859 if (Candidate.Conversions[ConvIdx].isBad()) { 6860 Candidate.Viable = false; 6861 Candidate.FailureKind = ovl_fail_bad_conversion; 6862 return; 6863 } 6864 } 6865 6866 // (CUDA B.1): Check for invalid calls between targets. 6867 if (getLangOpts().CUDA) 6868 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6869 if (!IsAllowedCUDACall(Caller, Method)) { 6870 Candidate.Viable = false; 6871 Candidate.FailureKind = ovl_fail_bad_target; 6872 return; 6873 } 6874 6875 if (Method->getTrailingRequiresClause()) { 6876 ConstraintSatisfaction Satisfaction; 6877 if (CheckFunctionConstraints(Method, Satisfaction) || 6878 !Satisfaction.IsSatisfied) { 6879 Candidate.Viable = false; 6880 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6881 return; 6882 } 6883 } 6884 6885 // Determine the implicit conversion sequences for each of the 6886 // arguments. 6887 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6888 unsigned ConvIdx = 6889 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6890 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6891 // We already formed a conversion sequence for this parameter during 6892 // template argument deduction. 6893 } else if (ArgIdx < NumParams) { 6894 // (C++ 13.3.2p3): for F to be a viable function, there shall 6895 // exist for each argument an implicit conversion sequence 6896 // (13.3.3.1) that converts that argument to the corresponding 6897 // parameter of F. 6898 QualType ParamType = Proto->getParamType(ArgIdx); 6899 Candidate.Conversions[ConvIdx] 6900 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6901 SuppressUserConversions, 6902 /*InOverloadResolution=*/true, 6903 /*AllowObjCWritebackConversion=*/ 6904 getLangOpts().ObjCAutoRefCount); 6905 if (Candidate.Conversions[ConvIdx].isBad()) { 6906 Candidate.Viable = false; 6907 Candidate.FailureKind = ovl_fail_bad_conversion; 6908 return; 6909 } 6910 } else { 6911 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6912 // argument for which there is no corresponding parameter is 6913 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6914 Candidate.Conversions[ConvIdx].setEllipsis(); 6915 } 6916 } 6917 6918 if (EnableIfAttr *FailedAttr = 6919 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6920 Candidate.Viable = false; 6921 Candidate.FailureKind = ovl_fail_enable_if; 6922 Candidate.DeductionFailure.Data = FailedAttr; 6923 return; 6924 } 6925 6926 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6927 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6928 Candidate.Viable = false; 6929 Candidate.FailureKind = ovl_non_default_multiversion_function; 6930 } 6931 } 6932 6933 /// Add a C++ member function template as a candidate to the candidate 6934 /// set, using template argument deduction to produce an appropriate member 6935 /// function template specialization. 6936 void Sema::AddMethodTemplateCandidate( 6937 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6938 CXXRecordDecl *ActingContext, 6939 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6940 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6941 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6942 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6943 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6944 return; 6945 6946 // C++ [over.match.funcs]p7: 6947 // In each case where a candidate is a function template, candidate 6948 // function template specializations are generated using template argument 6949 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6950 // candidate functions in the usual way.113) A given name can refer to one 6951 // or more function templates and also to a set of overloaded non-template 6952 // functions. In such a case, the candidate functions generated from each 6953 // function template are combined with the set of non-template candidate 6954 // functions. 6955 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6956 FunctionDecl *Specialization = nullptr; 6957 ConversionSequenceList Conversions; 6958 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6959 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6960 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6961 return CheckNonDependentConversions( 6962 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6963 SuppressUserConversions, ActingContext, ObjectType, 6964 ObjectClassification, PO); 6965 })) { 6966 OverloadCandidate &Candidate = 6967 CandidateSet.addCandidate(Conversions.size(), Conversions); 6968 Candidate.FoundDecl = FoundDecl; 6969 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6970 Candidate.Viable = false; 6971 Candidate.RewriteKind = 6972 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6973 Candidate.IsSurrogate = false; 6974 Candidate.IgnoreObjectArgument = 6975 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6976 ObjectType.isNull(); 6977 Candidate.ExplicitCallArguments = Args.size(); 6978 if (Result == TDK_NonDependentConversionFailure) 6979 Candidate.FailureKind = ovl_fail_bad_conversion; 6980 else { 6981 Candidate.FailureKind = ovl_fail_bad_deduction; 6982 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6983 Info); 6984 } 6985 return; 6986 } 6987 6988 // Add the function template specialization produced by template argument 6989 // deduction as a candidate. 6990 assert(Specialization && "Missing member function template specialization?"); 6991 assert(isa<CXXMethodDecl>(Specialization) && 6992 "Specialization is not a member function?"); 6993 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6994 ActingContext, ObjectType, ObjectClassification, Args, 6995 CandidateSet, SuppressUserConversions, PartialOverloading, 6996 Conversions, PO); 6997 } 6998 6999 /// Determine whether a given function template has a simple explicit specifier 7000 /// or a non-value-dependent explicit-specification that evaluates to true. 7001 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7002 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7003 } 7004 7005 /// Add a C++ function template specialization as a candidate 7006 /// in the candidate set, using template argument deduction to produce 7007 /// an appropriate function template specialization. 7008 void Sema::AddTemplateOverloadCandidate( 7009 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7010 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7011 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7012 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7013 OverloadCandidateParamOrder PO) { 7014 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7015 return; 7016 7017 // If the function template has a non-dependent explicit specification, 7018 // exclude it now if appropriate; we are not permitted to perform deduction 7019 // and substitution in this case. 7020 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7021 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7022 Candidate.FoundDecl = FoundDecl; 7023 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7024 Candidate.Viable = false; 7025 Candidate.FailureKind = ovl_fail_explicit; 7026 return; 7027 } 7028 7029 // C++ [over.match.funcs]p7: 7030 // In each case where a candidate is a function template, candidate 7031 // function template specializations are generated using template argument 7032 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7033 // candidate functions in the usual way.113) A given name can refer to one 7034 // or more function templates and also to a set of overloaded non-template 7035 // functions. In such a case, the candidate functions generated from each 7036 // function template are combined with the set of non-template candidate 7037 // functions. 7038 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7039 FunctionDecl *Specialization = nullptr; 7040 ConversionSequenceList Conversions; 7041 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7042 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7043 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7044 return CheckNonDependentConversions( 7045 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7046 SuppressUserConversions, nullptr, QualType(), {}, PO); 7047 })) { 7048 OverloadCandidate &Candidate = 7049 CandidateSet.addCandidate(Conversions.size(), Conversions); 7050 Candidate.FoundDecl = FoundDecl; 7051 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7052 Candidate.Viable = false; 7053 Candidate.RewriteKind = 7054 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7055 Candidate.IsSurrogate = false; 7056 Candidate.IsADLCandidate = IsADLCandidate; 7057 // Ignore the object argument if there is one, since we don't have an object 7058 // type. 7059 Candidate.IgnoreObjectArgument = 7060 isa<CXXMethodDecl>(Candidate.Function) && 7061 !isa<CXXConstructorDecl>(Candidate.Function); 7062 Candidate.ExplicitCallArguments = Args.size(); 7063 if (Result == TDK_NonDependentConversionFailure) 7064 Candidate.FailureKind = ovl_fail_bad_conversion; 7065 else { 7066 Candidate.FailureKind = ovl_fail_bad_deduction; 7067 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7068 Info); 7069 } 7070 return; 7071 } 7072 7073 // Add the function template specialization produced by template argument 7074 // deduction as a candidate. 7075 assert(Specialization && "Missing function template specialization?"); 7076 AddOverloadCandidate( 7077 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7078 PartialOverloading, AllowExplicit, 7079 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7080 } 7081 7082 /// Check that implicit conversion sequences can be formed for each argument 7083 /// whose corresponding parameter has a non-dependent type, per DR1391's 7084 /// [temp.deduct.call]p10. 7085 bool Sema::CheckNonDependentConversions( 7086 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7087 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7088 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7089 CXXRecordDecl *ActingContext, QualType ObjectType, 7090 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7091 // FIXME: The cases in which we allow explicit conversions for constructor 7092 // arguments never consider calling a constructor template. It's not clear 7093 // that is correct. 7094 const bool AllowExplicit = false; 7095 7096 auto *FD = FunctionTemplate->getTemplatedDecl(); 7097 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7098 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7099 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7100 7101 Conversions = 7102 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7103 7104 // Overload resolution is always an unevaluated context. 7105 EnterExpressionEvaluationContext Unevaluated( 7106 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7107 7108 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7109 // require that, but this check should never result in a hard error, and 7110 // overload resolution is permitted to sidestep instantiations. 7111 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7112 !ObjectType.isNull()) { 7113 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7114 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7115 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7116 Method, ActingContext); 7117 if (Conversions[ConvIdx].isBad()) 7118 return true; 7119 } 7120 7121 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7122 ++I) { 7123 QualType ParamType = ParamTypes[I]; 7124 if (!ParamType->isDependentType()) { 7125 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7126 ? 0 7127 : (ThisConversions + I); 7128 Conversions[ConvIdx] 7129 = TryCopyInitialization(*this, Args[I], ParamType, 7130 SuppressUserConversions, 7131 /*InOverloadResolution=*/true, 7132 /*AllowObjCWritebackConversion=*/ 7133 getLangOpts().ObjCAutoRefCount, 7134 AllowExplicit); 7135 if (Conversions[ConvIdx].isBad()) 7136 return true; 7137 } 7138 } 7139 7140 return false; 7141 } 7142 7143 /// Determine whether this is an allowable conversion from the result 7144 /// of an explicit conversion operator to the expected type, per C++ 7145 /// [over.match.conv]p1 and [over.match.ref]p1. 7146 /// 7147 /// \param ConvType The return type of the conversion function. 7148 /// 7149 /// \param ToType The type we are converting to. 7150 /// 7151 /// \param AllowObjCPointerConversion Allow a conversion from one 7152 /// Objective-C pointer to another. 7153 /// 7154 /// \returns true if the conversion is allowable, false otherwise. 7155 static bool isAllowableExplicitConversion(Sema &S, 7156 QualType ConvType, QualType ToType, 7157 bool AllowObjCPointerConversion) { 7158 QualType ToNonRefType = ToType.getNonReferenceType(); 7159 7160 // Easy case: the types are the same. 7161 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7162 return true; 7163 7164 // Allow qualification conversions. 7165 bool ObjCLifetimeConversion; 7166 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7167 ObjCLifetimeConversion)) 7168 return true; 7169 7170 // If we're not allowed to consider Objective-C pointer conversions, 7171 // we're done. 7172 if (!AllowObjCPointerConversion) 7173 return false; 7174 7175 // Is this an Objective-C pointer conversion? 7176 bool IncompatibleObjC = false; 7177 QualType ConvertedType; 7178 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7179 IncompatibleObjC); 7180 } 7181 7182 /// AddConversionCandidate - Add a C++ conversion function as a 7183 /// candidate in the candidate set (C++ [over.match.conv], 7184 /// C++ [over.match.copy]). From is the expression we're converting from, 7185 /// and ToType is the type that we're eventually trying to convert to 7186 /// (which may or may not be the same type as the type that the 7187 /// conversion function produces). 7188 void Sema::AddConversionCandidate( 7189 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7190 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7191 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7192 bool AllowExplicit, bool AllowResultConversion) { 7193 assert(!Conversion->getDescribedFunctionTemplate() && 7194 "Conversion function templates use AddTemplateConversionCandidate"); 7195 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7196 if (!CandidateSet.isNewCandidate(Conversion)) 7197 return; 7198 7199 // If the conversion function has an undeduced return type, trigger its 7200 // deduction now. 7201 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7202 if (DeduceReturnType(Conversion, From->getExprLoc())) 7203 return; 7204 ConvType = Conversion->getConversionType().getNonReferenceType(); 7205 } 7206 7207 // If we don't allow any conversion of the result type, ignore conversion 7208 // functions that don't convert to exactly (possibly cv-qualified) T. 7209 if (!AllowResultConversion && 7210 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7211 return; 7212 7213 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7214 // operator is only a candidate if its return type is the target type or 7215 // can be converted to the target type with a qualification conversion. 7216 // 7217 // FIXME: Include such functions in the candidate list and explain why we 7218 // can't select them. 7219 if (Conversion->isExplicit() && 7220 !isAllowableExplicitConversion(*this, ConvType, ToType, 7221 AllowObjCConversionOnExplicit)) 7222 return; 7223 7224 // Overload resolution is always an unevaluated context. 7225 EnterExpressionEvaluationContext Unevaluated( 7226 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7227 7228 // Add this candidate 7229 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7230 Candidate.FoundDecl = FoundDecl; 7231 Candidate.Function = Conversion; 7232 Candidate.IsSurrogate = false; 7233 Candidate.IgnoreObjectArgument = false; 7234 Candidate.FinalConversion.setAsIdentityConversion(); 7235 Candidate.FinalConversion.setFromType(ConvType); 7236 Candidate.FinalConversion.setAllToTypes(ToType); 7237 Candidate.Viable = true; 7238 Candidate.ExplicitCallArguments = 1; 7239 7240 // Explicit functions are not actually candidates at all if we're not 7241 // allowing them in this context, but keep them around so we can point 7242 // to them in diagnostics. 7243 if (!AllowExplicit && Conversion->isExplicit()) { 7244 Candidate.Viable = false; 7245 Candidate.FailureKind = ovl_fail_explicit; 7246 return; 7247 } 7248 7249 // C++ [over.match.funcs]p4: 7250 // For conversion functions, the function is considered to be a member of 7251 // the class of the implicit implied object argument for the purpose of 7252 // defining the type of the implicit object parameter. 7253 // 7254 // Determine the implicit conversion sequence for the implicit 7255 // object parameter. 7256 QualType ImplicitParamType = From->getType(); 7257 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7258 ImplicitParamType = FromPtrType->getPointeeType(); 7259 CXXRecordDecl *ConversionContext 7260 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7261 7262 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7263 *this, CandidateSet.getLocation(), From->getType(), 7264 From->Classify(Context), Conversion, ConversionContext); 7265 7266 if (Candidate.Conversions[0].isBad()) { 7267 Candidate.Viable = false; 7268 Candidate.FailureKind = ovl_fail_bad_conversion; 7269 return; 7270 } 7271 7272 if (Conversion->getTrailingRequiresClause()) { 7273 ConstraintSatisfaction Satisfaction; 7274 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7275 !Satisfaction.IsSatisfied) { 7276 Candidate.Viable = false; 7277 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7278 return; 7279 } 7280 } 7281 7282 // We won't go through a user-defined type conversion function to convert a 7283 // derived to base as such conversions are given Conversion Rank. They only 7284 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7285 QualType FromCanon 7286 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7287 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7288 if (FromCanon == ToCanon || 7289 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7290 Candidate.Viable = false; 7291 Candidate.FailureKind = ovl_fail_trivial_conversion; 7292 return; 7293 } 7294 7295 // To determine what the conversion from the result of calling the 7296 // conversion function to the type we're eventually trying to 7297 // convert to (ToType), we need to synthesize a call to the 7298 // conversion function and attempt copy initialization from it. This 7299 // makes sure that we get the right semantics with respect to 7300 // lvalues/rvalues and the type. Fortunately, we can allocate this 7301 // call on the stack and we don't need its arguments to be 7302 // well-formed. 7303 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7304 VK_LValue, From->getBeginLoc()); 7305 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7306 Context.getPointerType(Conversion->getType()), 7307 CK_FunctionToPointerDecay, 7308 &ConversionRef, VK_RValue); 7309 7310 QualType ConversionType = Conversion->getConversionType(); 7311 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7312 Candidate.Viable = false; 7313 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7314 return; 7315 } 7316 7317 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7318 7319 // Note that it is safe to allocate CallExpr on the stack here because 7320 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7321 // allocator). 7322 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7323 7324 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7325 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7326 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7327 7328 ImplicitConversionSequence ICS = 7329 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7330 /*SuppressUserConversions=*/true, 7331 /*InOverloadResolution=*/false, 7332 /*AllowObjCWritebackConversion=*/false); 7333 7334 switch (ICS.getKind()) { 7335 case ImplicitConversionSequence::StandardConversion: 7336 Candidate.FinalConversion = ICS.Standard; 7337 7338 // C++ [over.ics.user]p3: 7339 // If the user-defined conversion is specified by a specialization of a 7340 // conversion function template, the second standard conversion sequence 7341 // shall have exact match rank. 7342 if (Conversion->getPrimaryTemplate() && 7343 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7344 Candidate.Viable = false; 7345 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7346 return; 7347 } 7348 7349 // C++0x [dcl.init.ref]p5: 7350 // In the second case, if the reference is an rvalue reference and 7351 // the second standard conversion sequence of the user-defined 7352 // conversion sequence includes an lvalue-to-rvalue conversion, the 7353 // program is ill-formed. 7354 if (ToType->isRValueReferenceType() && 7355 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7356 Candidate.Viable = false; 7357 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7358 return; 7359 } 7360 break; 7361 7362 case ImplicitConversionSequence::BadConversion: 7363 Candidate.Viable = false; 7364 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7365 return; 7366 7367 default: 7368 llvm_unreachable( 7369 "Can only end up with a standard conversion sequence or failure"); 7370 } 7371 7372 if (EnableIfAttr *FailedAttr = 7373 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7374 Candidate.Viable = false; 7375 Candidate.FailureKind = ovl_fail_enable_if; 7376 Candidate.DeductionFailure.Data = FailedAttr; 7377 return; 7378 } 7379 7380 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7381 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7382 Candidate.Viable = false; 7383 Candidate.FailureKind = ovl_non_default_multiversion_function; 7384 } 7385 } 7386 7387 /// Adds a conversion function template specialization 7388 /// candidate to the overload set, using template argument deduction 7389 /// to deduce the template arguments of the conversion function 7390 /// template from the type that we are converting to (C++ 7391 /// [temp.deduct.conv]). 7392 void Sema::AddTemplateConversionCandidate( 7393 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7394 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7395 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7396 bool AllowExplicit, bool AllowResultConversion) { 7397 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7398 "Only conversion function templates permitted here"); 7399 7400 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7401 return; 7402 7403 // If the function template has a non-dependent explicit specification, 7404 // exclude it now if appropriate; we are not permitted to perform deduction 7405 // and substitution in this case. 7406 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7407 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7408 Candidate.FoundDecl = FoundDecl; 7409 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7410 Candidate.Viable = false; 7411 Candidate.FailureKind = ovl_fail_explicit; 7412 return; 7413 } 7414 7415 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7416 CXXConversionDecl *Specialization = nullptr; 7417 if (TemplateDeductionResult Result 7418 = DeduceTemplateArguments(FunctionTemplate, ToType, 7419 Specialization, Info)) { 7420 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7421 Candidate.FoundDecl = FoundDecl; 7422 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7423 Candidate.Viable = false; 7424 Candidate.FailureKind = ovl_fail_bad_deduction; 7425 Candidate.IsSurrogate = false; 7426 Candidate.IgnoreObjectArgument = false; 7427 Candidate.ExplicitCallArguments = 1; 7428 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7429 Info); 7430 return; 7431 } 7432 7433 // Add the conversion function template specialization produced by 7434 // template argument deduction as a candidate. 7435 assert(Specialization && "Missing function template specialization?"); 7436 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7437 CandidateSet, AllowObjCConversionOnExplicit, 7438 AllowExplicit, AllowResultConversion); 7439 } 7440 7441 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7442 /// converts the given @c Object to a function pointer via the 7443 /// conversion function @c Conversion, and then attempts to call it 7444 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7445 /// the type of function that we'll eventually be calling. 7446 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7447 DeclAccessPair FoundDecl, 7448 CXXRecordDecl *ActingContext, 7449 const FunctionProtoType *Proto, 7450 Expr *Object, 7451 ArrayRef<Expr *> Args, 7452 OverloadCandidateSet& CandidateSet) { 7453 if (!CandidateSet.isNewCandidate(Conversion)) 7454 return; 7455 7456 // Overload resolution is always an unevaluated context. 7457 EnterExpressionEvaluationContext Unevaluated( 7458 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7459 7460 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7461 Candidate.FoundDecl = FoundDecl; 7462 Candidate.Function = nullptr; 7463 Candidate.Surrogate = Conversion; 7464 Candidate.Viable = true; 7465 Candidate.IsSurrogate = true; 7466 Candidate.IgnoreObjectArgument = false; 7467 Candidate.ExplicitCallArguments = Args.size(); 7468 7469 // Determine the implicit conversion sequence for the implicit 7470 // object parameter. 7471 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7472 *this, CandidateSet.getLocation(), Object->getType(), 7473 Object->Classify(Context), Conversion, ActingContext); 7474 if (ObjectInit.isBad()) { 7475 Candidate.Viable = false; 7476 Candidate.FailureKind = ovl_fail_bad_conversion; 7477 Candidate.Conversions[0] = ObjectInit; 7478 return; 7479 } 7480 7481 // The first conversion is actually a user-defined conversion whose 7482 // first conversion is ObjectInit's standard conversion (which is 7483 // effectively a reference binding). Record it as such. 7484 Candidate.Conversions[0].setUserDefined(); 7485 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7486 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7487 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7488 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7489 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7490 Candidate.Conversions[0].UserDefined.After 7491 = Candidate.Conversions[0].UserDefined.Before; 7492 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7493 7494 // Find the 7495 unsigned NumParams = Proto->getNumParams(); 7496 7497 // (C++ 13.3.2p2): A candidate function having fewer than m 7498 // parameters is viable only if it has an ellipsis in its parameter 7499 // list (8.3.5). 7500 if (Args.size() > NumParams && !Proto->isVariadic()) { 7501 Candidate.Viable = false; 7502 Candidate.FailureKind = ovl_fail_too_many_arguments; 7503 return; 7504 } 7505 7506 // Function types don't have any default arguments, so just check if 7507 // we have enough arguments. 7508 if (Args.size() < NumParams) { 7509 // Not enough arguments. 7510 Candidate.Viable = false; 7511 Candidate.FailureKind = ovl_fail_too_few_arguments; 7512 return; 7513 } 7514 7515 // Determine the implicit conversion sequences for each of the 7516 // arguments. 7517 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7518 if (ArgIdx < NumParams) { 7519 // (C++ 13.3.2p3): for F to be a viable function, there shall 7520 // exist for each argument an implicit conversion sequence 7521 // (13.3.3.1) that converts that argument to the corresponding 7522 // parameter of F. 7523 QualType ParamType = Proto->getParamType(ArgIdx); 7524 Candidate.Conversions[ArgIdx + 1] 7525 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7526 /*SuppressUserConversions=*/false, 7527 /*InOverloadResolution=*/false, 7528 /*AllowObjCWritebackConversion=*/ 7529 getLangOpts().ObjCAutoRefCount); 7530 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7531 Candidate.Viable = false; 7532 Candidate.FailureKind = ovl_fail_bad_conversion; 7533 return; 7534 } 7535 } else { 7536 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7537 // argument for which there is no corresponding parameter is 7538 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7539 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7540 } 7541 } 7542 7543 if (EnableIfAttr *FailedAttr = 7544 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7545 Candidate.Viable = false; 7546 Candidate.FailureKind = ovl_fail_enable_if; 7547 Candidate.DeductionFailure.Data = FailedAttr; 7548 return; 7549 } 7550 } 7551 7552 /// Add all of the non-member operator function declarations in the given 7553 /// function set to the overload candidate set. 7554 void Sema::AddNonMemberOperatorCandidates( 7555 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7556 OverloadCandidateSet &CandidateSet, 7557 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7558 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7559 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7560 ArrayRef<Expr *> FunctionArgs = Args; 7561 7562 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7563 FunctionDecl *FD = 7564 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7565 7566 // Don't consider rewritten functions if we're not rewriting. 7567 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7568 continue; 7569 7570 assert(!isa<CXXMethodDecl>(FD) && 7571 "unqualified operator lookup found a member function"); 7572 7573 if (FunTmpl) { 7574 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7575 FunctionArgs, CandidateSet); 7576 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7577 AddTemplateOverloadCandidate( 7578 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7579 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7580 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7581 } else { 7582 if (ExplicitTemplateArgs) 7583 continue; 7584 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7585 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7586 AddOverloadCandidate(FD, F.getPair(), 7587 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7588 false, false, true, false, ADLCallKind::NotADL, 7589 None, OverloadCandidateParamOrder::Reversed); 7590 } 7591 } 7592 } 7593 7594 /// Add overload candidates for overloaded operators that are 7595 /// member functions. 7596 /// 7597 /// Add the overloaded operator candidates that are member functions 7598 /// for the operator Op that was used in an operator expression such 7599 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7600 /// CandidateSet will store the added overload candidates. (C++ 7601 /// [over.match.oper]). 7602 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7603 SourceLocation OpLoc, 7604 ArrayRef<Expr *> Args, 7605 OverloadCandidateSet &CandidateSet, 7606 OverloadCandidateParamOrder PO) { 7607 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7608 7609 // C++ [over.match.oper]p3: 7610 // For a unary operator @ with an operand of a type whose 7611 // cv-unqualified version is T1, and for a binary operator @ with 7612 // a left operand of a type whose cv-unqualified version is T1 and 7613 // a right operand of a type whose cv-unqualified version is T2, 7614 // three sets of candidate functions, designated member 7615 // candidates, non-member candidates and built-in candidates, are 7616 // constructed as follows: 7617 QualType T1 = Args[0]->getType(); 7618 7619 // -- If T1 is a complete class type or a class currently being 7620 // defined, the set of member candidates is the result of the 7621 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7622 // the set of member candidates is empty. 7623 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7624 // Complete the type if it can be completed. 7625 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7626 return; 7627 // If the type is neither complete nor being defined, bail out now. 7628 if (!T1Rec->getDecl()->getDefinition()) 7629 return; 7630 7631 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7632 LookupQualifiedName(Operators, T1Rec->getDecl()); 7633 Operators.suppressDiagnostics(); 7634 7635 for (LookupResult::iterator Oper = Operators.begin(), 7636 OperEnd = Operators.end(); 7637 Oper != OperEnd; 7638 ++Oper) 7639 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7640 Args[0]->Classify(Context), Args.slice(1), 7641 CandidateSet, /*SuppressUserConversion=*/false, PO); 7642 } 7643 } 7644 7645 /// AddBuiltinCandidate - Add a candidate for a built-in 7646 /// operator. ResultTy and ParamTys are the result and parameter types 7647 /// of the built-in candidate, respectively. Args and NumArgs are the 7648 /// arguments being passed to the candidate. IsAssignmentOperator 7649 /// should be true when this built-in candidate is an assignment 7650 /// operator. NumContextualBoolArguments is the number of arguments 7651 /// (at the beginning of the argument list) that will be contextually 7652 /// converted to bool. 7653 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7654 OverloadCandidateSet& CandidateSet, 7655 bool IsAssignmentOperator, 7656 unsigned NumContextualBoolArguments) { 7657 // Overload resolution is always an unevaluated context. 7658 EnterExpressionEvaluationContext Unevaluated( 7659 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7660 7661 // Add this candidate 7662 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7663 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7664 Candidate.Function = nullptr; 7665 Candidate.IsSurrogate = false; 7666 Candidate.IgnoreObjectArgument = false; 7667 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7668 7669 // Determine the implicit conversion sequences for each of the 7670 // arguments. 7671 Candidate.Viable = true; 7672 Candidate.ExplicitCallArguments = Args.size(); 7673 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7674 // C++ [over.match.oper]p4: 7675 // For the built-in assignment operators, conversions of the 7676 // left operand are restricted as follows: 7677 // -- no temporaries are introduced to hold the left operand, and 7678 // -- no user-defined conversions are applied to the left 7679 // operand to achieve a type match with the left-most 7680 // parameter of a built-in candidate. 7681 // 7682 // We block these conversions by turning off user-defined 7683 // conversions, since that is the only way that initialization of 7684 // a reference to a non-class type can occur from something that 7685 // is not of the same type. 7686 if (ArgIdx < NumContextualBoolArguments) { 7687 assert(ParamTys[ArgIdx] == Context.BoolTy && 7688 "Contextual conversion to bool requires bool type"); 7689 Candidate.Conversions[ArgIdx] 7690 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7691 } else { 7692 Candidate.Conversions[ArgIdx] 7693 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7694 ArgIdx == 0 && IsAssignmentOperator, 7695 /*InOverloadResolution=*/false, 7696 /*AllowObjCWritebackConversion=*/ 7697 getLangOpts().ObjCAutoRefCount); 7698 } 7699 if (Candidate.Conversions[ArgIdx].isBad()) { 7700 Candidate.Viable = false; 7701 Candidate.FailureKind = ovl_fail_bad_conversion; 7702 break; 7703 } 7704 } 7705 } 7706 7707 namespace { 7708 7709 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7710 /// candidate operator functions for built-in operators (C++ 7711 /// [over.built]). The types are separated into pointer types and 7712 /// enumeration types. 7713 class BuiltinCandidateTypeSet { 7714 /// TypeSet - A set of types. 7715 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7716 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7717 7718 /// PointerTypes - The set of pointer types that will be used in the 7719 /// built-in candidates. 7720 TypeSet PointerTypes; 7721 7722 /// MemberPointerTypes - The set of member pointer types that will be 7723 /// used in the built-in candidates. 7724 TypeSet MemberPointerTypes; 7725 7726 /// EnumerationTypes - The set of enumeration types that will be 7727 /// used in the built-in candidates. 7728 TypeSet EnumerationTypes; 7729 7730 /// The set of vector types that will be used in the built-in 7731 /// candidates. 7732 TypeSet VectorTypes; 7733 7734 /// The set of matrix types that will be used in the built-in 7735 /// candidates. 7736 TypeSet MatrixTypes; 7737 7738 /// A flag indicating non-record types are viable candidates 7739 bool HasNonRecordTypes; 7740 7741 /// A flag indicating whether either arithmetic or enumeration types 7742 /// were present in the candidate set. 7743 bool HasArithmeticOrEnumeralTypes; 7744 7745 /// A flag indicating whether the nullptr type was present in the 7746 /// candidate set. 7747 bool HasNullPtrType; 7748 7749 /// Sema - The semantic analysis instance where we are building the 7750 /// candidate type set. 7751 Sema &SemaRef; 7752 7753 /// Context - The AST context in which we will build the type sets. 7754 ASTContext &Context; 7755 7756 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7757 const Qualifiers &VisibleQuals); 7758 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7759 7760 public: 7761 /// iterator - Iterates through the types that are part of the set. 7762 typedef TypeSet::iterator iterator; 7763 7764 BuiltinCandidateTypeSet(Sema &SemaRef) 7765 : HasNonRecordTypes(false), 7766 HasArithmeticOrEnumeralTypes(false), 7767 HasNullPtrType(false), 7768 SemaRef(SemaRef), 7769 Context(SemaRef.Context) { } 7770 7771 void AddTypesConvertedFrom(QualType Ty, 7772 SourceLocation Loc, 7773 bool AllowUserConversions, 7774 bool AllowExplicitConversions, 7775 const Qualifiers &VisibleTypeConversionsQuals); 7776 7777 /// pointer_begin - First pointer type found; 7778 iterator pointer_begin() { return PointerTypes.begin(); } 7779 7780 /// pointer_end - Past the last pointer type found; 7781 iterator pointer_end() { return PointerTypes.end(); } 7782 7783 /// member_pointer_begin - First member pointer type found; 7784 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7785 7786 /// member_pointer_end - Past the last member pointer type found; 7787 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7788 7789 /// enumeration_begin - First enumeration type found; 7790 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7791 7792 /// enumeration_end - Past the last enumeration type found; 7793 iterator enumeration_end() { return EnumerationTypes.end(); } 7794 7795 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7796 7797 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7798 7799 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7800 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7801 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7802 bool hasNullPtrType() const { return HasNullPtrType; } 7803 }; 7804 7805 } // end anonymous namespace 7806 7807 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7808 /// the set of pointer types along with any more-qualified variants of 7809 /// that type. For example, if @p Ty is "int const *", this routine 7810 /// will add "int const *", "int const volatile *", "int const 7811 /// restrict *", and "int const volatile restrict *" to the set of 7812 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7813 /// false otherwise. 7814 /// 7815 /// FIXME: what to do about extended qualifiers? 7816 bool 7817 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7818 const Qualifiers &VisibleQuals) { 7819 7820 // Insert this type. 7821 if (!PointerTypes.insert(Ty)) 7822 return false; 7823 7824 QualType PointeeTy; 7825 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7826 bool buildObjCPtr = false; 7827 if (!PointerTy) { 7828 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7829 PointeeTy = PTy->getPointeeType(); 7830 buildObjCPtr = true; 7831 } else { 7832 PointeeTy = PointerTy->getPointeeType(); 7833 } 7834 7835 // Don't add qualified variants of arrays. For one, they're not allowed 7836 // (the qualifier would sink to the element type), and for another, the 7837 // only overload situation where it matters is subscript or pointer +- int, 7838 // and those shouldn't have qualifier variants anyway. 7839 if (PointeeTy->isArrayType()) 7840 return true; 7841 7842 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7843 bool hasVolatile = VisibleQuals.hasVolatile(); 7844 bool hasRestrict = VisibleQuals.hasRestrict(); 7845 7846 // Iterate through all strict supersets of BaseCVR. 7847 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7848 if ((CVR | BaseCVR) != CVR) continue; 7849 // Skip over volatile if no volatile found anywhere in the types. 7850 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7851 7852 // Skip over restrict if no restrict found anywhere in the types, or if 7853 // the type cannot be restrict-qualified. 7854 if ((CVR & Qualifiers::Restrict) && 7855 (!hasRestrict || 7856 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7857 continue; 7858 7859 // Build qualified pointee type. 7860 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7861 7862 // Build qualified pointer type. 7863 QualType QPointerTy; 7864 if (!buildObjCPtr) 7865 QPointerTy = Context.getPointerType(QPointeeTy); 7866 else 7867 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7868 7869 // Insert qualified pointer type. 7870 PointerTypes.insert(QPointerTy); 7871 } 7872 7873 return true; 7874 } 7875 7876 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7877 /// to the set of pointer types along with any more-qualified variants of 7878 /// that type. For example, if @p Ty is "int const *", this routine 7879 /// will add "int const *", "int const volatile *", "int const 7880 /// restrict *", and "int const volatile restrict *" to the set of 7881 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7882 /// false otherwise. 7883 /// 7884 /// FIXME: what to do about extended qualifiers? 7885 bool 7886 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7887 QualType Ty) { 7888 // Insert this type. 7889 if (!MemberPointerTypes.insert(Ty)) 7890 return false; 7891 7892 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7893 assert(PointerTy && "type was not a member pointer type!"); 7894 7895 QualType PointeeTy = PointerTy->getPointeeType(); 7896 // Don't add qualified variants of arrays. For one, they're not allowed 7897 // (the qualifier would sink to the element type), and for another, the 7898 // only overload situation where it matters is subscript or pointer +- int, 7899 // and those shouldn't have qualifier variants anyway. 7900 if (PointeeTy->isArrayType()) 7901 return true; 7902 const Type *ClassTy = PointerTy->getClass(); 7903 7904 // Iterate through all strict supersets of the pointee type's CVR 7905 // qualifiers. 7906 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7907 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7908 if ((CVR | BaseCVR) != CVR) continue; 7909 7910 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7911 MemberPointerTypes.insert( 7912 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7913 } 7914 7915 return true; 7916 } 7917 7918 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7919 /// Ty can be implicit converted to the given set of @p Types. We're 7920 /// primarily interested in pointer types and enumeration types. We also 7921 /// take member pointer types, for the conditional operator. 7922 /// AllowUserConversions is true if we should look at the conversion 7923 /// functions of a class type, and AllowExplicitConversions if we 7924 /// should also include the explicit conversion functions of a class 7925 /// type. 7926 void 7927 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7928 SourceLocation Loc, 7929 bool AllowUserConversions, 7930 bool AllowExplicitConversions, 7931 const Qualifiers &VisibleQuals) { 7932 // Only deal with canonical types. 7933 Ty = Context.getCanonicalType(Ty); 7934 7935 // Look through reference types; they aren't part of the type of an 7936 // expression for the purposes of conversions. 7937 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7938 Ty = RefTy->getPointeeType(); 7939 7940 // If we're dealing with an array type, decay to the pointer. 7941 if (Ty->isArrayType()) 7942 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7943 7944 // Otherwise, we don't care about qualifiers on the type. 7945 Ty = Ty.getLocalUnqualifiedType(); 7946 7947 // Flag if we ever add a non-record type. 7948 const RecordType *TyRec = Ty->getAs<RecordType>(); 7949 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7950 7951 // Flag if we encounter an arithmetic type. 7952 HasArithmeticOrEnumeralTypes = 7953 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7954 7955 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7956 PointerTypes.insert(Ty); 7957 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7958 // Insert our type, and its more-qualified variants, into the set 7959 // of types. 7960 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7961 return; 7962 } else if (Ty->isMemberPointerType()) { 7963 // Member pointers are far easier, since the pointee can't be converted. 7964 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7965 return; 7966 } else if (Ty->isEnumeralType()) { 7967 HasArithmeticOrEnumeralTypes = true; 7968 EnumerationTypes.insert(Ty); 7969 } else if (Ty->isVectorType()) { 7970 // We treat vector types as arithmetic types in many contexts as an 7971 // extension. 7972 HasArithmeticOrEnumeralTypes = true; 7973 VectorTypes.insert(Ty); 7974 } else if (Ty->isMatrixType()) { 7975 // Similar to vector types, we treat vector types as arithmetic types in 7976 // many contexts as an extension. 7977 HasArithmeticOrEnumeralTypes = true; 7978 MatrixTypes.insert(Ty); 7979 } else if (Ty->isNullPtrType()) { 7980 HasNullPtrType = true; 7981 } else if (AllowUserConversions && TyRec) { 7982 // No conversion functions in incomplete types. 7983 if (!SemaRef.isCompleteType(Loc, Ty)) 7984 return; 7985 7986 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7987 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7988 if (isa<UsingShadowDecl>(D)) 7989 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7990 7991 // Skip conversion function templates; they don't tell us anything 7992 // about which builtin types we can convert to. 7993 if (isa<FunctionTemplateDecl>(D)) 7994 continue; 7995 7996 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7997 if (AllowExplicitConversions || !Conv->isExplicit()) { 7998 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7999 VisibleQuals); 8000 } 8001 } 8002 } 8003 } 8004 /// Helper function for adjusting address spaces for the pointer or reference 8005 /// operands of builtin operators depending on the argument. 8006 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8007 Expr *Arg) { 8008 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8009 } 8010 8011 /// Helper function for AddBuiltinOperatorCandidates() that adds 8012 /// the volatile- and non-volatile-qualified assignment operators for the 8013 /// given type to the candidate set. 8014 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8015 QualType T, 8016 ArrayRef<Expr *> Args, 8017 OverloadCandidateSet &CandidateSet) { 8018 QualType ParamTypes[2]; 8019 8020 // T& operator=(T&, T) 8021 ParamTypes[0] = S.Context.getLValueReferenceType( 8022 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8023 ParamTypes[1] = T; 8024 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8025 /*IsAssignmentOperator=*/true); 8026 8027 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8028 // volatile T& operator=(volatile T&, T) 8029 ParamTypes[0] = S.Context.getLValueReferenceType( 8030 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8031 Args[0])); 8032 ParamTypes[1] = T; 8033 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8034 /*IsAssignmentOperator=*/true); 8035 } 8036 } 8037 8038 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8039 /// if any, found in visible type conversion functions found in ArgExpr's type. 8040 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8041 Qualifiers VRQuals; 8042 const RecordType *TyRec; 8043 if (const MemberPointerType *RHSMPType = 8044 ArgExpr->getType()->getAs<MemberPointerType>()) 8045 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8046 else 8047 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8048 if (!TyRec) { 8049 // Just to be safe, assume the worst case. 8050 VRQuals.addVolatile(); 8051 VRQuals.addRestrict(); 8052 return VRQuals; 8053 } 8054 8055 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8056 if (!ClassDecl->hasDefinition()) 8057 return VRQuals; 8058 8059 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8060 if (isa<UsingShadowDecl>(D)) 8061 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8062 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8063 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8064 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8065 CanTy = ResTypeRef->getPointeeType(); 8066 // Need to go down the pointer/mempointer chain and add qualifiers 8067 // as see them. 8068 bool done = false; 8069 while (!done) { 8070 if (CanTy.isRestrictQualified()) 8071 VRQuals.addRestrict(); 8072 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8073 CanTy = ResTypePtr->getPointeeType(); 8074 else if (const MemberPointerType *ResTypeMPtr = 8075 CanTy->getAs<MemberPointerType>()) 8076 CanTy = ResTypeMPtr->getPointeeType(); 8077 else 8078 done = true; 8079 if (CanTy.isVolatileQualified()) 8080 VRQuals.addVolatile(); 8081 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8082 return VRQuals; 8083 } 8084 } 8085 } 8086 return VRQuals; 8087 } 8088 8089 namespace { 8090 8091 /// Helper class to manage the addition of builtin operator overload 8092 /// candidates. It provides shared state and utility methods used throughout 8093 /// the process, as well as a helper method to add each group of builtin 8094 /// operator overloads from the standard to a candidate set. 8095 class BuiltinOperatorOverloadBuilder { 8096 // Common instance state available to all overload candidate addition methods. 8097 Sema &S; 8098 ArrayRef<Expr *> Args; 8099 Qualifiers VisibleTypeConversionsQuals; 8100 bool HasArithmeticOrEnumeralCandidateType; 8101 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8102 OverloadCandidateSet &CandidateSet; 8103 8104 static constexpr int ArithmeticTypesCap = 24; 8105 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8106 8107 // Define some indices used to iterate over the arithmetic types in 8108 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8109 // types are that preserved by promotion (C++ [over.built]p2). 8110 unsigned FirstIntegralType, 8111 LastIntegralType; 8112 unsigned FirstPromotedIntegralType, 8113 LastPromotedIntegralType; 8114 unsigned FirstPromotedArithmeticType, 8115 LastPromotedArithmeticType; 8116 unsigned NumArithmeticTypes; 8117 8118 void InitArithmeticTypes() { 8119 // Start of promoted types. 8120 FirstPromotedArithmeticType = 0; 8121 ArithmeticTypes.push_back(S.Context.FloatTy); 8122 ArithmeticTypes.push_back(S.Context.DoubleTy); 8123 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8124 if (S.Context.getTargetInfo().hasFloat128Type()) 8125 ArithmeticTypes.push_back(S.Context.Float128Ty); 8126 8127 // Start of integral types. 8128 FirstIntegralType = ArithmeticTypes.size(); 8129 FirstPromotedIntegralType = ArithmeticTypes.size(); 8130 ArithmeticTypes.push_back(S.Context.IntTy); 8131 ArithmeticTypes.push_back(S.Context.LongTy); 8132 ArithmeticTypes.push_back(S.Context.LongLongTy); 8133 if (S.Context.getTargetInfo().hasInt128Type()) 8134 ArithmeticTypes.push_back(S.Context.Int128Ty); 8135 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8136 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8137 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8138 if (S.Context.getTargetInfo().hasInt128Type()) 8139 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8140 LastPromotedIntegralType = ArithmeticTypes.size(); 8141 LastPromotedArithmeticType = ArithmeticTypes.size(); 8142 // End of promoted types. 8143 8144 ArithmeticTypes.push_back(S.Context.BoolTy); 8145 ArithmeticTypes.push_back(S.Context.CharTy); 8146 ArithmeticTypes.push_back(S.Context.WCharTy); 8147 if (S.Context.getLangOpts().Char8) 8148 ArithmeticTypes.push_back(S.Context.Char8Ty); 8149 ArithmeticTypes.push_back(S.Context.Char16Ty); 8150 ArithmeticTypes.push_back(S.Context.Char32Ty); 8151 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8152 ArithmeticTypes.push_back(S.Context.ShortTy); 8153 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8154 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8155 LastIntegralType = ArithmeticTypes.size(); 8156 NumArithmeticTypes = ArithmeticTypes.size(); 8157 // End of integral types. 8158 // FIXME: What about complex? What about half? 8159 8160 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8161 "Enough inline storage for all arithmetic types."); 8162 } 8163 8164 /// Helper method to factor out the common pattern of adding overloads 8165 /// for '++' and '--' builtin operators. 8166 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8167 bool HasVolatile, 8168 bool HasRestrict) { 8169 QualType ParamTypes[2] = { 8170 S.Context.getLValueReferenceType(CandidateTy), 8171 S.Context.IntTy 8172 }; 8173 8174 // Non-volatile version. 8175 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8176 8177 // Use a heuristic to reduce number of builtin candidates in the set: 8178 // add volatile version only if there are conversions to a volatile type. 8179 if (HasVolatile) { 8180 ParamTypes[0] = 8181 S.Context.getLValueReferenceType( 8182 S.Context.getVolatileType(CandidateTy)); 8183 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8184 } 8185 8186 // Add restrict version only if there are conversions to a restrict type 8187 // and our candidate type is a non-restrict-qualified pointer. 8188 if (HasRestrict && CandidateTy->isAnyPointerType() && 8189 !CandidateTy.isRestrictQualified()) { 8190 ParamTypes[0] 8191 = S.Context.getLValueReferenceType( 8192 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8193 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8194 8195 if (HasVolatile) { 8196 ParamTypes[0] 8197 = S.Context.getLValueReferenceType( 8198 S.Context.getCVRQualifiedType(CandidateTy, 8199 (Qualifiers::Volatile | 8200 Qualifiers::Restrict))); 8201 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8202 } 8203 } 8204 8205 } 8206 8207 /// Helper to add an overload candidate for a binary builtin with types \p L 8208 /// and \p R. 8209 void AddCandidate(QualType L, QualType R) { 8210 QualType LandR[2] = {L, R}; 8211 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8212 } 8213 8214 public: 8215 BuiltinOperatorOverloadBuilder( 8216 Sema &S, ArrayRef<Expr *> Args, 8217 Qualifiers VisibleTypeConversionsQuals, 8218 bool HasArithmeticOrEnumeralCandidateType, 8219 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8220 OverloadCandidateSet &CandidateSet) 8221 : S(S), Args(Args), 8222 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8223 HasArithmeticOrEnumeralCandidateType( 8224 HasArithmeticOrEnumeralCandidateType), 8225 CandidateTypes(CandidateTypes), 8226 CandidateSet(CandidateSet) { 8227 8228 InitArithmeticTypes(); 8229 } 8230 8231 // Increment is deprecated for bool since C++17. 8232 // 8233 // C++ [over.built]p3: 8234 // 8235 // For every pair (T, VQ), where T is an arithmetic type other 8236 // than bool, and VQ is either volatile or empty, there exist 8237 // candidate operator functions of the form 8238 // 8239 // VQ T& operator++(VQ T&); 8240 // T operator++(VQ T&, int); 8241 // 8242 // C++ [over.built]p4: 8243 // 8244 // For every pair (T, VQ), where T is an arithmetic type other 8245 // than bool, and VQ is either volatile or empty, there exist 8246 // candidate operator functions of the form 8247 // 8248 // VQ T& operator--(VQ T&); 8249 // T operator--(VQ T&, int); 8250 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8251 if (!HasArithmeticOrEnumeralCandidateType) 8252 return; 8253 8254 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8255 const auto TypeOfT = ArithmeticTypes[Arith]; 8256 if (TypeOfT == S.Context.BoolTy) { 8257 if (Op == OO_MinusMinus) 8258 continue; 8259 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8260 continue; 8261 } 8262 addPlusPlusMinusMinusStyleOverloads( 8263 TypeOfT, 8264 VisibleTypeConversionsQuals.hasVolatile(), 8265 VisibleTypeConversionsQuals.hasRestrict()); 8266 } 8267 } 8268 8269 // C++ [over.built]p5: 8270 // 8271 // For every pair (T, VQ), where T is a cv-qualified or 8272 // cv-unqualified object type, and VQ is either volatile or 8273 // empty, there exist candidate operator functions of the form 8274 // 8275 // T*VQ& operator++(T*VQ&); 8276 // T*VQ& operator--(T*VQ&); 8277 // T* operator++(T*VQ&, int); 8278 // T* operator--(T*VQ&, int); 8279 void addPlusPlusMinusMinusPointerOverloads() { 8280 for (BuiltinCandidateTypeSet::iterator 8281 Ptr = CandidateTypes[0].pointer_begin(), 8282 PtrEnd = CandidateTypes[0].pointer_end(); 8283 Ptr != PtrEnd; ++Ptr) { 8284 // Skip pointer types that aren't pointers to object types. 8285 if (!(*Ptr)->getPointeeType()->isObjectType()) 8286 continue; 8287 8288 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8289 (!(*Ptr).isVolatileQualified() && 8290 VisibleTypeConversionsQuals.hasVolatile()), 8291 (!(*Ptr).isRestrictQualified() && 8292 VisibleTypeConversionsQuals.hasRestrict())); 8293 } 8294 } 8295 8296 // C++ [over.built]p6: 8297 // For every cv-qualified or cv-unqualified object type T, there 8298 // exist candidate operator functions of the form 8299 // 8300 // T& operator*(T*); 8301 // 8302 // C++ [over.built]p7: 8303 // For every function type T that does not have cv-qualifiers or a 8304 // ref-qualifier, there exist candidate operator functions of the form 8305 // T& operator*(T*); 8306 void addUnaryStarPointerOverloads() { 8307 for (BuiltinCandidateTypeSet::iterator 8308 Ptr = CandidateTypes[0].pointer_begin(), 8309 PtrEnd = CandidateTypes[0].pointer_end(); 8310 Ptr != PtrEnd; ++Ptr) { 8311 QualType ParamTy = *Ptr; 8312 QualType PointeeTy = ParamTy->getPointeeType(); 8313 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8314 continue; 8315 8316 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8317 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8318 continue; 8319 8320 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8321 } 8322 } 8323 8324 // C++ [over.built]p9: 8325 // For every promoted arithmetic type T, there exist candidate 8326 // operator functions of the form 8327 // 8328 // T operator+(T); 8329 // T operator-(T); 8330 void addUnaryPlusOrMinusArithmeticOverloads() { 8331 if (!HasArithmeticOrEnumeralCandidateType) 8332 return; 8333 8334 for (unsigned Arith = FirstPromotedArithmeticType; 8335 Arith < LastPromotedArithmeticType; ++Arith) { 8336 QualType ArithTy = ArithmeticTypes[Arith]; 8337 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8338 } 8339 8340 // Extension: We also add these operators for vector types. 8341 for (QualType VecTy : CandidateTypes[0].vector_types()) 8342 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8343 } 8344 8345 // C++ [over.built]p8: 8346 // For every type T, there exist candidate operator functions of 8347 // the form 8348 // 8349 // T* operator+(T*); 8350 void addUnaryPlusPointerOverloads() { 8351 for (BuiltinCandidateTypeSet::iterator 8352 Ptr = CandidateTypes[0].pointer_begin(), 8353 PtrEnd = CandidateTypes[0].pointer_end(); 8354 Ptr != PtrEnd; ++Ptr) { 8355 QualType ParamTy = *Ptr; 8356 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8357 } 8358 } 8359 8360 // C++ [over.built]p10: 8361 // For every promoted integral type T, there exist candidate 8362 // operator functions of the form 8363 // 8364 // T operator~(T); 8365 void addUnaryTildePromotedIntegralOverloads() { 8366 if (!HasArithmeticOrEnumeralCandidateType) 8367 return; 8368 8369 for (unsigned Int = FirstPromotedIntegralType; 8370 Int < LastPromotedIntegralType; ++Int) { 8371 QualType IntTy = ArithmeticTypes[Int]; 8372 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8373 } 8374 8375 // Extension: We also add this operator for vector types. 8376 for (QualType VecTy : CandidateTypes[0].vector_types()) 8377 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8378 } 8379 8380 // C++ [over.match.oper]p16: 8381 // For every pointer to member type T or type std::nullptr_t, there 8382 // exist candidate operator functions of the form 8383 // 8384 // bool operator==(T,T); 8385 // bool operator!=(T,T); 8386 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8387 /// Set of (canonical) types that we've already handled. 8388 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8389 8390 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8391 for (BuiltinCandidateTypeSet::iterator 8392 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8393 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8394 MemPtr != MemPtrEnd; 8395 ++MemPtr) { 8396 // Don't add the same builtin candidate twice. 8397 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8398 continue; 8399 8400 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8401 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8402 } 8403 8404 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8405 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8406 if (AddedTypes.insert(NullPtrTy).second) { 8407 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8408 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8409 } 8410 } 8411 } 8412 } 8413 8414 // C++ [over.built]p15: 8415 // 8416 // For every T, where T is an enumeration type or a pointer type, 8417 // there exist candidate operator functions of the form 8418 // 8419 // bool operator<(T, T); 8420 // bool operator>(T, T); 8421 // bool operator<=(T, T); 8422 // bool operator>=(T, T); 8423 // bool operator==(T, T); 8424 // bool operator!=(T, T); 8425 // R operator<=>(T, T) 8426 void addGenericBinaryPointerOrEnumeralOverloads() { 8427 // C++ [over.match.oper]p3: 8428 // [...]the built-in candidates include all of the candidate operator 8429 // functions defined in 13.6 that, compared to the given operator, [...] 8430 // do not have the same parameter-type-list as any non-template non-member 8431 // candidate. 8432 // 8433 // Note that in practice, this only affects enumeration types because there 8434 // aren't any built-in candidates of record type, and a user-defined operator 8435 // must have an operand of record or enumeration type. Also, the only other 8436 // overloaded operator with enumeration arguments, operator=, 8437 // cannot be overloaded for enumeration types, so this is the only place 8438 // where we must suppress candidates like this. 8439 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8440 UserDefinedBinaryOperators; 8441 8442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8443 if (CandidateTypes[ArgIdx].enumeration_begin() != 8444 CandidateTypes[ArgIdx].enumeration_end()) { 8445 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8446 CEnd = CandidateSet.end(); 8447 C != CEnd; ++C) { 8448 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8449 continue; 8450 8451 if (C->Function->isFunctionTemplateSpecialization()) 8452 continue; 8453 8454 // We interpret "same parameter-type-list" as applying to the 8455 // "synthesized candidate, with the order of the two parameters 8456 // reversed", not to the original function. 8457 bool Reversed = C->isReversed(); 8458 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8459 ->getType() 8460 .getUnqualifiedType(); 8461 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8462 ->getType() 8463 .getUnqualifiedType(); 8464 8465 // Skip if either parameter isn't of enumeral type. 8466 if (!FirstParamType->isEnumeralType() || 8467 !SecondParamType->isEnumeralType()) 8468 continue; 8469 8470 // Add this operator to the set of known user-defined operators. 8471 UserDefinedBinaryOperators.insert( 8472 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8473 S.Context.getCanonicalType(SecondParamType))); 8474 } 8475 } 8476 } 8477 8478 /// Set of (canonical) types that we've already handled. 8479 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8480 8481 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8482 for (BuiltinCandidateTypeSet::iterator 8483 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8484 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8485 Ptr != PtrEnd; ++Ptr) { 8486 // Don't add the same builtin candidate twice. 8487 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8488 continue; 8489 8490 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8491 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8492 } 8493 for (BuiltinCandidateTypeSet::iterator 8494 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8495 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8496 Enum != EnumEnd; ++Enum) { 8497 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8498 8499 // Don't add the same builtin candidate twice, or if a user defined 8500 // candidate exists. 8501 if (!AddedTypes.insert(CanonType).second || 8502 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8503 CanonType))) 8504 continue; 8505 QualType ParamTypes[2] = { *Enum, *Enum }; 8506 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8507 } 8508 } 8509 } 8510 8511 // C++ [over.built]p13: 8512 // 8513 // For every cv-qualified or cv-unqualified object type T 8514 // there exist candidate operator functions of the form 8515 // 8516 // T* operator+(T*, ptrdiff_t); 8517 // T& operator[](T*, ptrdiff_t); [BELOW] 8518 // T* operator-(T*, ptrdiff_t); 8519 // T* operator+(ptrdiff_t, T*); 8520 // T& operator[](ptrdiff_t, T*); [BELOW] 8521 // 8522 // C++ [over.built]p14: 8523 // 8524 // For every T, where T is a pointer to object type, there 8525 // exist candidate operator functions of the form 8526 // 8527 // ptrdiff_t operator-(T, T); 8528 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8529 /// Set of (canonical) types that we've already handled. 8530 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8531 8532 for (int Arg = 0; Arg < 2; ++Arg) { 8533 QualType AsymmetricParamTypes[2] = { 8534 S.Context.getPointerDiffType(), 8535 S.Context.getPointerDiffType(), 8536 }; 8537 for (BuiltinCandidateTypeSet::iterator 8538 Ptr = CandidateTypes[Arg].pointer_begin(), 8539 PtrEnd = CandidateTypes[Arg].pointer_end(); 8540 Ptr != PtrEnd; ++Ptr) { 8541 QualType PointeeTy = (*Ptr)->getPointeeType(); 8542 if (!PointeeTy->isObjectType()) 8543 continue; 8544 8545 AsymmetricParamTypes[Arg] = *Ptr; 8546 if (Arg == 0 || Op == OO_Plus) { 8547 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8548 // T* operator+(ptrdiff_t, T*); 8549 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8550 } 8551 if (Op == OO_Minus) { 8552 // ptrdiff_t operator-(T, T); 8553 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8554 continue; 8555 8556 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8557 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8558 } 8559 } 8560 } 8561 } 8562 8563 // C++ [over.built]p12: 8564 // 8565 // For every pair of promoted arithmetic types L and R, there 8566 // exist candidate operator functions of the form 8567 // 8568 // LR operator*(L, R); 8569 // LR operator/(L, R); 8570 // LR operator+(L, R); 8571 // LR operator-(L, R); 8572 // bool operator<(L, R); 8573 // bool operator>(L, R); 8574 // bool operator<=(L, R); 8575 // bool operator>=(L, R); 8576 // bool operator==(L, R); 8577 // bool operator!=(L, R); 8578 // 8579 // where LR is the result of the usual arithmetic conversions 8580 // between types L and R. 8581 // 8582 // C++ [over.built]p24: 8583 // 8584 // For every pair of promoted arithmetic types L and R, there exist 8585 // candidate operator functions of the form 8586 // 8587 // LR operator?(bool, L, R); 8588 // 8589 // where LR is the result of the usual arithmetic conversions 8590 // between types L and R. 8591 // Our candidates ignore the first parameter. 8592 void addGenericBinaryArithmeticOverloads() { 8593 if (!HasArithmeticOrEnumeralCandidateType) 8594 return; 8595 8596 for (unsigned Left = FirstPromotedArithmeticType; 8597 Left < LastPromotedArithmeticType; ++Left) { 8598 for (unsigned Right = FirstPromotedArithmeticType; 8599 Right < LastPromotedArithmeticType; ++Right) { 8600 QualType LandR[2] = { ArithmeticTypes[Left], 8601 ArithmeticTypes[Right] }; 8602 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8603 } 8604 } 8605 8606 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8607 // conditional operator for vector types. 8608 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8609 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8610 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8611 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8612 } 8613 } 8614 8615 /// Add binary operator overloads for each candidate matrix type M1, M2: 8616 /// * (M1, M1) -> M1 8617 /// * (M1, M1.getElementType()) -> M1 8618 /// * (M2.getElementType(), M2) -> M2 8619 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8620 void addMatrixBinaryArithmeticOverloads() { 8621 if (!HasArithmeticOrEnumeralCandidateType) 8622 return; 8623 8624 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8625 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8626 AddCandidate(M1, M1); 8627 } 8628 8629 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8630 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8631 if (!CandidateTypes[0].containsMatrixType(M2)) 8632 AddCandidate(M2, M2); 8633 } 8634 } 8635 8636 // C++2a [over.built]p14: 8637 // 8638 // For every integral type T there exists a candidate operator function 8639 // of the form 8640 // 8641 // std::strong_ordering operator<=>(T, T) 8642 // 8643 // C++2a [over.built]p15: 8644 // 8645 // For every pair of floating-point types L and R, there exists a candidate 8646 // operator function of the form 8647 // 8648 // std::partial_ordering operator<=>(L, R); 8649 // 8650 // FIXME: The current specification for integral types doesn't play nice with 8651 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8652 // comparisons. Under the current spec this can lead to ambiguity during 8653 // overload resolution. For example: 8654 // 8655 // enum A : int {a}; 8656 // auto x = (a <=> (long)42); 8657 // 8658 // error: call is ambiguous for arguments 'A' and 'long'. 8659 // note: candidate operator<=>(int, int) 8660 // note: candidate operator<=>(long, long) 8661 // 8662 // To avoid this error, this function deviates from the specification and adds 8663 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8664 // arithmetic types (the same as the generic relational overloads). 8665 // 8666 // For now this function acts as a placeholder. 8667 void addThreeWayArithmeticOverloads() { 8668 addGenericBinaryArithmeticOverloads(); 8669 } 8670 8671 // C++ [over.built]p17: 8672 // 8673 // For every pair of promoted integral types L and R, there 8674 // exist candidate operator functions of the form 8675 // 8676 // LR operator%(L, R); 8677 // LR operator&(L, R); 8678 // LR operator^(L, R); 8679 // LR operator|(L, R); 8680 // L operator<<(L, R); 8681 // L operator>>(L, R); 8682 // 8683 // where LR is the result of the usual arithmetic conversions 8684 // between types L and R. 8685 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8686 if (!HasArithmeticOrEnumeralCandidateType) 8687 return; 8688 8689 for (unsigned Left = FirstPromotedIntegralType; 8690 Left < LastPromotedIntegralType; ++Left) { 8691 for (unsigned Right = FirstPromotedIntegralType; 8692 Right < LastPromotedIntegralType; ++Right) { 8693 QualType LandR[2] = { ArithmeticTypes[Left], 8694 ArithmeticTypes[Right] }; 8695 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8696 } 8697 } 8698 } 8699 8700 // C++ [over.built]p20: 8701 // 8702 // For every pair (T, VQ), where T is an enumeration or 8703 // pointer to member type and VQ is either volatile or 8704 // empty, there exist candidate operator functions of the form 8705 // 8706 // VQ T& operator=(VQ T&, T); 8707 void addAssignmentMemberPointerOrEnumeralOverloads() { 8708 /// Set of (canonical) types that we've already handled. 8709 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8710 8711 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8712 for (BuiltinCandidateTypeSet::iterator 8713 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8714 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8715 Enum != EnumEnd; ++Enum) { 8716 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8717 continue; 8718 8719 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8720 } 8721 8722 for (BuiltinCandidateTypeSet::iterator 8723 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8724 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8725 MemPtr != MemPtrEnd; ++MemPtr) { 8726 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8727 continue; 8728 8729 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8730 } 8731 } 8732 } 8733 8734 // C++ [over.built]p19: 8735 // 8736 // For every pair (T, VQ), where T is any type and VQ is either 8737 // volatile or empty, there exist candidate operator functions 8738 // of the form 8739 // 8740 // T*VQ& operator=(T*VQ&, T*); 8741 // 8742 // C++ [over.built]p21: 8743 // 8744 // For every pair (T, VQ), where T is a cv-qualified or 8745 // cv-unqualified object type and VQ is either volatile or 8746 // empty, there exist candidate operator functions of the form 8747 // 8748 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8749 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8750 void addAssignmentPointerOverloads(bool isEqualOp) { 8751 /// Set of (canonical) types that we've already handled. 8752 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8753 8754 for (BuiltinCandidateTypeSet::iterator 8755 Ptr = CandidateTypes[0].pointer_begin(), 8756 PtrEnd = CandidateTypes[0].pointer_end(); 8757 Ptr != PtrEnd; ++Ptr) { 8758 // If this is operator=, keep track of the builtin candidates we added. 8759 if (isEqualOp) 8760 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8761 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8762 continue; 8763 8764 // non-volatile version 8765 QualType ParamTypes[2] = { 8766 S.Context.getLValueReferenceType(*Ptr), 8767 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8768 }; 8769 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8770 /*IsAssignmentOperator=*/ isEqualOp); 8771 8772 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8773 VisibleTypeConversionsQuals.hasVolatile(); 8774 if (NeedVolatile) { 8775 // volatile version 8776 ParamTypes[0] = 8777 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8778 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8779 /*IsAssignmentOperator=*/isEqualOp); 8780 } 8781 8782 if (!(*Ptr).isRestrictQualified() && 8783 VisibleTypeConversionsQuals.hasRestrict()) { 8784 // restrict version 8785 ParamTypes[0] 8786 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8787 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8788 /*IsAssignmentOperator=*/isEqualOp); 8789 8790 if (NeedVolatile) { 8791 // volatile restrict version 8792 ParamTypes[0] 8793 = S.Context.getLValueReferenceType( 8794 S.Context.getCVRQualifiedType(*Ptr, 8795 (Qualifiers::Volatile | 8796 Qualifiers::Restrict))); 8797 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8798 /*IsAssignmentOperator=*/isEqualOp); 8799 } 8800 } 8801 } 8802 8803 if (isEqualOp) { 8804 for (BuiltinCandidateTypeSet::iterator 8805 Ptr = CandidateTypes[1].pointer_begin(), 8806 PtrEnd = CandidateTypes[1].pointer_end(); 8807 Ptr != PtrEnd; ++Ptr) { 8808 // Make sure we don't add the same candidate twice. 8809 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8810 continue; 8811 8812 QualType ParamTypes[2] = { 8813 S.Context.getLValueReferenceType(*Ptr), 8814 *Ptr, 8815 }; 8816 8817 // non-volatile version 8818 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8819 /*IsAssignmentOperator=*/true); 8820 8821 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8822 VisibleTypeConversionsQuals.hasVolatile(); 8823 if (NeedVolatile) { 8824 // volatile version 8825 ParamTypes[0] = 8826 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8827 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8828 /*IsAssignmentOperator=*/true); 8829 } 8830 8831 if (!(*Ptr).isRestrictQualified() && 8832 VisibleTypeConversionsQuals.hasRestrict()) { 8833 // restrict version 8834 ParamTypes[0] 8835 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8836 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8837 /*IsAssignmentOperator=*/true); 8838 8839 if (NeedVolatile) { 8840 // volatile restrict version 8841 ParamTypes[0] 8842 = S.Context.getLValueReferenceType( 8843 S.Context.getCVRQualifiedType(*Ptr, 8844 (Qualifiers::Volatile | 8845 Qualifiers::Restrict))); 8846 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8847 /*IsAssignmentOperator=*/true); 8848 } 8849 } 8850 } 8851 } 8852 } 8853 8854 // C++ [over.built]p18: 8855 // 8856 // For every triple (L, VQ, R), where L is an arithmetic type, 8857 // VQ is either volatile or empty, and R is a promoted 8858 // arithmetic type, there exist candidate operator functions of 8859 // the form 8860 // 8861 // VQ L& operator=(VQ L&, R); 8862 // VQ L& operator*=(VQ L&, R); 8863 // VQ L& operator/=(VQ L&, R); 8864 // VQ L& operator+=(VQ L&, R); 8865 // VQ L& operator-=(VQ L&, R); 8866 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8867 if (!HasArithmeticOrEnumeralCandidateType) 8868 return; 8869 8870 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8871 for (unsigned Right = FirstPromotedArithmeticType; 8872 Right < LastPromotedArithmeticType; ++Right) { 8873 QualType ParamTypes[2]; 8874 ParamTypes[1] = ArithmeticTypes[Right]; 8875 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8876 S, ArithmeticTypes[Left], Args[0]); 8877 // Add this built-in operator as a candidate (VQ is empty). 8878 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8879 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8880 /*IsAssignmentOperator=*/isEqualOp); 8881 8882 // Add this built-in operator as a candidate (VQ is 'volatile'). 8883 if (VisibleTypeConversionsQuals.hasVolatile()) { 8884 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8885 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8886 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8887 /*IsAssignmentOperator=*/isEqualOp); 8888 } 8889 } 8890 } 8891 8892 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8893 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8894 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8895 QualType ParamTypes[2]; 8896 ParamTypes[1] = Vec2Ty; 8897 // Add this built-in operator as a candidate (VQ is empty). 8898 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8899 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8900 /*IsAssignmentOperator=*/isEqualOp); 8901 8902 // Add this built-in operator as a candidate (VQ is 'volatile'). 8903 if (VisibleTypeConversionsQuals.hasVolatile()) { 8904 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8905 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8906 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8907 /*IsAssignmentOperator=*/isEqualOp); 8908 } 8909 } 8910 } 8911 8912 // C++ [over.built]p22: 8913 // 8914 // For every triple (L, VQ, R), where L is an integral type, VQ 8915 // is either volatile or empty, and R is a promoted integral 8916 // type, there exist candidate operator functions of the form 8917 // 8918 // VQ L& operator%=(VQ L&, R); 8919 // VQ L& operator<<=(VQ L&, R); 8920 // VQ L& operator>>=(VQ L&, R); 8921 // VQ L& operator&=(VQ L&, R); 8922 // VQ L& operator^=(VQ L&, R); 8923 // VQ L& operator|=(VQ L&, R); 8924 void addAssignmentIntegralOverloads() { 8925 if (!HasArithmeticOrEnumeralCandidateType) 8926 return; 8927 8928 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8929 for (unsigned Right = FirstPromotedIntegralType; 8930 Right < LastPromotedIntegralType; ++Right) { 8931 QualType ParamTypes[2]; 8932 ParamTypes[1] = ArithmeticTypes[Right]; 8933 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8934 S, ArithmeticTypes[Left], Args[0]); 8935 // Add this built-in operator as a candidate (VQ is empty). 8936 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8937 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8938 if (VisibleTypeConversionsQuals.hasVolatile()) { 8939 // Add this built-in operator as a candidate (VQ is 'volatile'). 8940 ParamTypes[0] = LeftBaseTy; 8941 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8942 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8943 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8944 } 8945 } 8946 } 8947 } 8948 8949 // C++ [over.operator]p23: 8950 // 8951 // There also exist candidate operator functions of the form 8952 // 8953 // bool operator!(bool); 8954 // bool operator&&(bool, bool); 8955 // bool operator||(bool, bool); 8956 void addExclaimOverload() { 8957 QualType ParamTy = S.Context.BoolTy; 8958 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8959 /*IsAssignmentOperator=*/false, 8960 /*NumContextualBoolArguments=*/1); 8961 } 8962 void addAmpAmpOrPipePipeOverload() { 8963 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8965 /*IsAssignmentOperator=*/false, 8966 /*NumContextualBoolArguments=*/2); 8967 } 8968 8969 // C++ [over.built]p13: 8970 // 8971 // For every cv-qualified or cv-unqualified object type T there 8972 // exist candidate operator functions of the form 8973 // 8974 // T* operator+(T*, ptrdiff_t); [ABOVE] 8975 // T& operator[](T*, ptrdiff_t); 8976 // T* operator-(T*, ptrdiff_t); [ABOVE] 8977 // T* operator+(ptrdiff_t, T*); [ABOVE] 8978 // T& operator[](ptrdiff_t, T*); 8979 void addSubscriptOverloads() { 8980 for (BuiltinCandidateTypeSet::iterator 8981 Ptr = CandidateTypes[0].pointer_begin(), 8982 PtrEnd = CandidateTypes[0].pointer_end(); 8983 Ptr != PtrEnd; ++Ptr) { 8984 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8985 QualType PointeeType = (*Ptr)->getPointeeType(); 8986 if (!PointeeType->isObjectType()) 8987 continue; 8988 8989 // T& operator[](T*, ptrdiff_t) 8990 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8991 } 8992 8993 for (BuiltinCandidateTypeSet::iterator 8994 Ptr = CandidateTypes[1].pointer_begin(), 8995 PtrEnd = CandidateTypes[1].pointer_end(); 8996 Ptr != PtrEnd; ++Ptr) { 8997 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8998 QualType PointeeType = (*Ptr)->getPointeeType(); 8999 if (!PointeeType->isObjectType()) 9000 continue; 9001 9002 // T& operator[](ptrdiff_t, T*) 9003 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9004 } 9005 } 9006 9007 // C++ [over.built]p11: 9008 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9009 // C1 is the same type as C2 or is a derived class of C2, T is an object 9010 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9011 // there exist candidate operator functions of the form 9012 // 9013 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9014 // 9015 // where CV12 is the union of CV1 and CV2. 9016 void addArrowStarOverloads() { 9017 for (BuiltinCandidateTypeSet::iterator 9018 Ptr = CandidateTypes[0].pointer_begin(), 9019 PtrEnd = CandidateTypes[0].pointer_end(); 9020 Ptr != PtrEnd; ++Ptr) { 9021 QualType C1Ty = (*Ptr); 9022 QualType C1; 9023 QualifierCollector Q1; 9024 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9025 if (!isa<RecordType>(C1)) 9026 continue; 9027 // heuristic to reduce number of builtin candidates in the set. 9028 // Add volatile/restrict version only if there are conversions to a 9029 // volatile/restrict type. 9030 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9031 continue; 9032 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9033 continue; 9034 for (BuiltinCandidateTypeSet::iterator 9035 MemPtr = CandidateTypes[1].member_pointer_begin(), 9036 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 9037 MemPtr != MemPtrEnd; ++MemPtr) { 9038 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 9039 QualType C2 = QualType(mptr->getClass(), 0); 9040 C2 = C2.getUnqualifiedType(); 9041 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9042 break; 9043 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 9044 // build CV12 T& 9045 QualType T = mptr->getPointeeType(); 9046 if (!VisibleTypeConversionsQuals.hasVolatile() && 9047 T.isVolatileQualified()) 9048 continue; 9049 if (!VisibleTypeConversionsQuals.hasRestrict() && 9050 T.isRestrictQualified()) 9051 continue; 9052 T = Q1.apply(S.Context, T); 9053 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9054 } 9055 } 9056 } 9057 9058 // Note that we don't consider the first argument, since it has been 9059 // contextually converted to bool long ago. The candidates below are 9060 // therefore added as binary. 9061 // 9062 // C++ [over.built]p25: 9063 // For every type T, where T is a pointer, pointer-to-member, or scoped 9064 // enumeration type, there exist candidate operator functions of the form 9065 // 9066 // T operator?(bool, T, T); 9067 // 9068 void addConditionalOperatorOverloads() { 9069 /// Set of (canonical) types that we've already handled. 9070 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9071 9072 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9073 for (BuiltinCandidateTypeSet::iterator 9074 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9075 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9076 Ptr != PtrEnd; ++Ptr) { 9077 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9078 continue; 9079 9080 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9082 } 9083 9084 for (BuiltinCandidateTypeSet::iterator 9085 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9086 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9087 MemPtr != MemPtrEnd; ++MemPtr) { 9088 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9089 continue; 9090 9091 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9093 } 9094 9095 if (S.getLangOpts().CPlusPlus11) { 9096 for (BuiltinCandidateTypeSet::iterator 9097 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9098 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9099 Enum != EnumEnd; ++Enum) { 9100 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9101 continue; 9102 9103 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9104 continue; 9105 9106 QualType ParamTypes[2] = { *Enum, *Enum }; 9107 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9108 } 9109 } 9110 } 9111 } 9112 }; 9113 9114 } // end anonymous namespace 9115 9116 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9117 /// operator overloads to the candidate set (C++ [over.built]), based 9118 /// on the operator @p Op and the arguments given. For example, if the 9119 /// operator is a binary '+', this routine might add "int 9120 /// operator+(int, int)" to cover integer addition. 9121 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9122 SourceLocation OpLoc, 9123 ArrayRef<Expr *> Args, 9124 OverloadCandidateSet &CandidateSet) { 9125 // Find all of the types that the arguments can convert to, but only 9126 // if the operator we're looking at has built-in operator candidates 9127 // that make use of these types. Also record whether we encounter non-record 9128 // candidate types or either arithmetic or enumeral candidate types. 9129 Qualifiers VisibleTypeConversionsQuals; 9130 VisibleTypeConversionsQuals.addConst(); 9131 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9132 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9133 9134 bool HasNonRecordCandidateType = false; 9135 bool HasArithmeticOrEnumeralCandidateType = false; 9136 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9137 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9138 CandidateTypes.emplace_back(*this); 9139 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9140 OpLoc, 9141 true, 9142 (Op == OO_Exclaim || 9143 Op == OO_AmpAmp || 9144 Op == OO_PipePipe), 9145 VisibleTypeConversionsQuals); 9146 HasNonRecordCandidateType = HasNonRecordCandidateType || 9147 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9148 HasArithmeticOrEnumeralCandidateType = 9149 HasArithmeticOrEnumeralCandidateType || 9150 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9151 } 9152 9153 // Exit early when no non-record types have been added to the candidate set 9154 // for any of the arguments to the operator. 9155 // 9156 // We can't exit early for !, ||, or &&, since there we have always have 9157 // 'bool' overloads. 9158 if (!HasNonRecordCandidateType && 9159 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9160 return; 9161 9162 // Setup an object to manage the common state for building overloads. 9163 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9164 VisibleTypeConversionsQuals, 9165 HasArithmeticOrEnumeralCandidateType, 9166 CandidateTypes, CandidateSet); 9167 9168 // Dispatch over the operation to add in only those overloads which apply. 9169 switch (Op) { 9170 case OO_None: 9171 case NUM_OVERLOADED_OPERATORS: 9172 llvm_unreachable("Expected an overloaded operator"); 9173 9174 case OO_New: 9175 case OO_Delete: 9176 case OO_Array_New: 9177 case OO_Array_Delete: 9178 case OO_Call: 9179 llvm_unreachable( 9180 "Special operators don't use AddBuiltinOperatorCandidates"); 9181 9182 case OO_Comma: 9183 case OO_Arrow: 9184 case OO_Coawait: 9185 // C++ [over.match.oper]p3: 9186 // -- For the operator ',', the unary operator '&', the 9187 // operator '->', or the operator 'co_await', the 9188 // built-in candidates set is empty. 9189 break; 9190 9191 case OO_Plus: // '+' is either unary or binary 9192 if (Args.size() == 1) 9193 OpBuilder.addUnaryPlusPointerOverloads(); 9194 LLVM_FALLTHROUGH; 9195 9196 case OO_Minus: // '-' is either unary or binary 9197 if (Args.size() == 1) { 9198 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9199 } else { 9200 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9201 OpBuilder.addGenericBinaryArithmeticOverloads(); 9202 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9203 } 9204 break; 9205 9206 case OO_Star: // '*' is either unary or binary 9207 if (Args.size() == 1) 9208 OpBuilder.addUnaryStarPointerOverloads(); 9209 else { 9210 OpBuilder.addGenericBinaryArithmeticOverloads(); 9211 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9212 } 9213 break; 9214 9215 case OO_Slash: 9216 OpBuilder.addGenericBinaryArithmeticOverloads(); 9217 break; 9218 9219 case OO_PlusPlus: 9220 case OO_MinusMinus: 9221 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9222 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9223 break; 9224 9225 case OO_EqualEqual: 9226 case OO_ExclaimEqual: 9227 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9228 LLVM_FALLTHROUGH; 9229 9230 case OO_Less: 9231 case OO_Greater: 9232 case OO_LessEqual: 9233 case OO_GreaterEqual: 9234 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9235 OpBuilder.addGenericBinaryArithmeticOverloads(); 9236 break; 9237 9238 case OO_Spaceship: 9239 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9240 OpBuilder.addThreeWayArithmeticOverloads(); 9241 break; 9242 9243 case OO_Percent: 9244 case OO_Caret: 9245 case OO_Pipe: 9246 case OO_LessLess: 9247 case OO_GreaterGreater: 9248 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9249 break; 9250 9251 case OO_Amp: // '&' is either unary or binary 9252 if (Args.size() == 1) 9253 // C++ [over.match.oper]p3: 9254 // -- For the operator ',', the unary operator '&', or the 9255 // operator '->', the built-in candidates set is empty. 9256 break; 9257 9258 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9259 break; 9260 9261 case OO_Tilde: 9262 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9263 break; 9264 9265 case OO_Equal: 9266 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9267 LLVM_FALLTHROUGH; 9268 9269 case OO_PlusEqual: 9270 case OO_MinusEqual: 9271 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9272 LLVM_FALLTHROUGH; 9273 9274 case OO_StarEqual: 9275 case OO_SlashEqual: 9276 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9277 break; 9278 9279 case OO_PercentEqual: 9280 case OO_LessLessEqual: 9281 case OO_GreaterGreaterEqual: 9282 case OO_AmpEqual: 9283 case OO_CaretEqual: 9284 case OO_PipeEqual: 9285 OpBuilder.addAssignmentIntegralOverloads(); 9286 break; 9287 9288 case OO_Exclaim: 9289 OpBuilder.addExclaimOverload(); 9290 break; 9291 9292 case OO_AmpAmp: 9293 case OO_PipePipe: 9294 OpBuilder.addAmpAmpOrPipePipeOverload(); 9295 break; 9296 9297 case OO_Subscript: 9298 OpBuilder.addSubscriptOverloads(); 9299 break; 9300 9301 case OO_ArrowStar: 9302 OpBuilder.addArrowStarOverloads(); 9303 break; 9304 9305 case OO_Conditional: 9306 OpBuilder.addConditionalOperatorOverloads(); 9307 OpBuilder.addGenericBinaryArithmeticOverloads(); 9308 break; 9309 } 9310 } 9311 9312 /// Add function candidates found via argument-dependent lookup 9313 /// to the set of overloading candidates. 9314 /// 9315 /// This routine performs argument-dependent name lookup based on the 9316 /// given function name (which may also be an operator name) and adds 9317 /// all of the overload candidates found by ADL to the overload 9318 /// candidate set (C++ [basic.lookup.argdep]). 9319 void 9320 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9321 SourceLocation Loc, 9322 ArrayRef<Expr *> Args, 9323 TemplateArgumentListInfo *ExplicitTemplateArgs, 9324 OverloadCandidateSet& CandidateSet, 9325 bool PartialOverloading) { 9326 ADLResult Fns; 9327 9328 // FIXME: This approach for uniquing ADL results (and removing 9329 // redundant candidates from the set) relies on pointer-equality, 9330 // which means we need to key off the canonical decl. However, 9331 // always going back to the canonical decl might not get us the 9332 // right set of default arguments. What default arguments are 9333 // we supposed to consider on ADL candidates, anyway? 9334 9335 // FIXME: Pass in the explicit template arguments? 9336 ArgumentDependentLookup(Name, Loc, Args, Fns); 9337 9338 // Erase all of the candidates we already knew about. 9339 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9340 CandEnd = CandidateSet.end(); 9341 Cand != CandEnd; ++Cand) 9342 if (Cand->Function) { 9343 Fns.erase(Cand->Function); 9344 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9345 Fns.erase(FunTmpl); 9346 } 9347 9348 // For each of the ADL candidates we found, add it to the overload 9349 // set. 9350 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9351 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9352 9353 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9354 if (ExplicitTemplateArgs) 9355 continue; 9356 9357 AddOverloadCandidate( 9358 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9359 PartialOverloading, /*AllowExplicit=*/true, 9360 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9361 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9362 AddOverloadCandidate( 9363 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9364 /*SuppressUserConversions=*/false, PartialOverloading, 9365 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9366 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9367 } 9368 } else { 9369 auto *FTD = cast<FunctionTemplateDecl>(*I); 9370 AddTemplateOverloadCandidate( 9371 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9372 /*SuppressUserConversions=*/false, PartialOverloading, 9373 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9374 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9375 Context, FTD->getTemplatedDecl())) { 9376 AddTemplateOverloadCandidate( 9377 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9378 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9379 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9380 OverloadCandidateParamOrder::Reversed); 9381 } 9382 } 9383 } 9384 } 9385 9386 namespace { 9387 enum class Comparison { Equal, Better, Worse }; 9388 } 9389 9390 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9391 /// overload resolution. 9392 /// 9393 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9394 /// Cand1's first N enable_if attributes have precisely the same conditions as 9395 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9396 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9397 /// 9398 /// Note that you can have a pair of candidates such that Cand1's enable_if 9399 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9400 /// worse than Cand1's. 9401 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9402 const FunctionDecl *Cand2) { 9403 // Common case: One (or both) decls don't have enable_if attrs. 9404 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9405 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9406 if (!Cand1Attr || !Cand2Attr) { 9407 if (Cand1Attr == Cand2Attr) 9408 return Comparison::Equal; 9409 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9410 } 9411 9412 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9413 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9414 9415 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9416 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9417 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9418 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9419 9420 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9421 // has fewer enable_if attributes than Cand2, and vice versa. 9422 if (!Cand1A) 9423 return Comparison::Worse; 9424 if (!Cand2A) 9425 return Comparison::Better; 9426 9427 Cand1ID.clear(); 9428 Cand2ID.clear(); 9429 9430 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9431 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9432 if (Cand1ID != Cand2ID) 9433 return Comparison::Worse; 9434 } 9435 9436 return Comparison::Equal; 9437 } 9438 9439 static Comparison 9440 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9441 const OverloadCandidate &Cand2) { 9442 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9443 !Cand2.Function->isMultiVersion()) 9444 return Comparison::Equal; 9445 9446 // If both are invalid, they are equal. If one of them is invalid, the other 9447 // is better. 9448 if (Cand1.Function->isInvalidDecl()) { 9449 if (Cand2.Function->isInvalidDecl()) 9450 return Comparison::Equal; 9451 return Comparison::Worse; 9452 } 9453 if (Cand2.Function->isInvalidDecl()) 9454 return Comparison::Better; 9455 9456 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9457 // cpu_dispatch, else arbitrarily based on the identifiers. 9458 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9459 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9460 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9461 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9462 9463 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9464 return Comparison::Equal; 9465 9466 if (Cand1CPUDisp && !Cand2CPUDisp) 9467 return Comparison::Better; 9468 if (Cand2CPUDisp && !Cand1CPUDisp) 9469 return Comparison::Worse; 9470 9471 if (Cand1CPUSpec && Cand2CPUSpec) { 9472 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9473 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9474 ? Comparison::Better 9475 : Comparison::Worse; 9476 9477 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9478 FirstDiff = std::mismatch( 9479 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9480 Cand2CPUSpec->cpus_begin(), 9481 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9482 return LHS->getName() == RHS->getName(); 9483 }); 9484 9485 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9486 "Two different cpu-specific versions should not have the same " 9487 "identifier list, otherwise they'd be the same decl!"); 9488 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9489 ? Comparison::Better 9490 : Comparison::Worse; 9491 } 9492 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9493 } 9494 9495 /// Compute the type of the implicit object parameter for the given function, 9496 /// if any. Returns None if there is no implicit object parameter, and a null 9497 /// QualType if there is a 'matches anything' implicit object parameter. 9498 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9499 const FunctionDecl *F) { 9500 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9501 return llvm::None; 9502 9503 auto *M = cast<CXXMethodDecl>(F); 9504 // Static member functions' object parameters match all types. 9505 if (M->isStatic()) 9506 return QualType(); 9507 9508 QualType T = M->getThisObjectType(); 9509 if (M->getRefQualifier() == RQ_RValue) 9510 return Context.getRValueReferenceType(T); 9511 return Context.getLValueReferenceType(T); 9512 } 9513 9514 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9515 const FunctionDecl *F2, unsigned NumParams) { 9516 if (declaresSameEntity(F1, F2)) 9517 return true; 9518 9519 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9520 if (First) { 9521 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9522 return *T; 9523 } 9524 assert(I < F->getNumParams()); 9525 return F->getParamDecl(I++)->getType(); 9526 }; 9527 9528 unsigned I1 = 0, I2 = 0; 9529 for (unsigned I = 0; I != NumParams; ++I) { 9530 QualType T1 = NextParam(F1, I1, I == 0); 9531 QualType T2 = NextParam(F2, I2, I == 0); 9532 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9533 return false; 9534 } 9535 return true; 9536 } 9537 9538 /// isBetterOverloadCandidate - Determines whether the first overload 9539 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9540 bool clang::isBetterOverloadCandidate( 9541 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9542 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9543 // Define viable functions to be better candidates than non-viable 9544 // functions. 9545 if (!Cand2.Viable) 9546 return Cand1.Viable; 9547 else if (!Cand1.Viable) 9548 return false; 9549 9550 // C++ [over.match.best]p1: 9551 // 9552 // -- if F is a static member function, ICS1(F) is defined such 9553 // that ICS1(F) is neither better nor worse than ICS1(G) for 9554 // any function G, and, symmetrically, ICS1(G) is neither 9555 // better nor worse than ICS1(F). 9556 unsigned StartArg = 0; 9557 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9558 StartArg = 1; 9559 9560 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9561 // We don't allow incompatible pointer conversions in C++. 9562 if (!S.getLangOpts().CPlusPlus) 9563 return ICS.isStandard() && 9564 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9565 9566 // The only ill-formed conversion we allow in C++ is the string literal to 9567 // char* conversion, which is only considered ill-formed after C++11. 9568 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9569 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9570 }; 9571 9572 // Define functions that don't require ill-formed conversions for a given 9573 // argument to be better candidates than functions that do. 9574 unsigned NumArgs = Cand1.Conversions.size(); 9575 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9576 bool HasBetterConversion = false; 9577 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9578 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9579 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9580 if (Cand1Bad != Cand2Bad) { 9581 if (Cand1Bad) 9582 return false; 9583 HasBetterConversion = true; 9584 } 9585 } 9586 9587 if (HasBetterConversion) 9588 return true; 9589 9590 // C++ [over.match.best]p1: 9591 // A viable function F1 is defined to be a better function than another 9592 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9593 // conversion sequence than ICSi(F2), and then... 9594 bool HasWorseConversion = false; 9595 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9596 switch (CompareImplicitConversionSequences(S, Loc, 9597 Cand1.Conversions[ArgIdx], 9598 Cand2.Conversions[ArgIdx])) { 9599 case ImplicitConversionSequence::Better: 9600 // Cand1 has a better conversion sequence. 9601 HasBetterConversion = true; 9602 break; 9603 9604 case ImplicitConversionSequence::Worse: 9605 if (Cand1.Function && Cand2.Function && 9606 Cand1.isReversed() != Cand2.isReversed() && 9607 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9608 NumArgs)) { 9609 // Work around large-scale breakage caused by considering reversed 9610 // forms of operator== in C++20: 9611 // 9612 // When comparing a function against a reversed function with the same 9613 // parameter types, if we have a better conversion for one argument and 9614 // a worse conversion for the other, the implicit conversion sequences 9615 // are treated as being equally good. 9616 // 9617 // This prevents a comparison function from being considered ambiguous 9618 // with a reversed form that is written in the same way. 9619 // 9620 // We diagnose this as an extension from CreateOverloadedBinOp. 9621 HasWorseConversion = true; 9622 break; 9623 } 9624 9625 // Cand1 can't be better than Cand2. 9626 return false; 9627 9628 case ImplicitConversionSequence::Indistinguishable: 9629 // Do nothing. 9630 break; 9631 } 9632 } 9633 9634 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9635 // ICSj(F2), or, if not that, 9636 if (HasBetterConversion && !HasWorseConversion) 9637 return true; 9638 9639 // -- the context is an initialization by user-defined conversion 9640 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9641 // from the return type of F1 to the destination type (i.e., 9642 // the type of the entity being initialized) is a better 9643 // conversion sequence than the standard conversion sequence 9644 // from the return type of F2 to the destination type. 9645 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9646 Cand1.Function && Cand2.Function && 9647 isa<CXXConversionDecl>(Cand1.Function) && 9648 isa<CXXConversionDecl>(Cand2.Function)) { 9649 // First check whether we prefer one of the conversion functions over the 9650 // other. This only distinguishes the results in non-standard, extension 9651 // cases such as the conversion from a lambda closure type to a function 9652 // pointer or block. 9653 ImplicitConversionSequence::CompareKind Result = 9654 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9655 if (Result == ImplicitConversionSequence::Indistinguishable) 9656 Result = CompareStandardConversionSequences(S, Loc, 9657 Cand1.FinalConversion, 9658 Cand2.FinalConversion); 9659 9660 if (Result != ImplicitConversionSequence::Indistinguishable) 9661 return Result == ImplicitConversionSequence::Better; 9662 9663 // FIXME: Compare kind of reference binding if conversion functions 9664 // convert to a reference type used in direct reference binding, per 9665 // C++14 [over.match.best]p1 section 2 bullet 3. 9666 } 9667 9668 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9669 // as combined with the resolution to CWG issue 243. 9670 // 9671 // When the context is initialization by constructor ([over.match.ctor] or 9672 // either phase of [over.match.list]), a constructor is preferred over 9673 // a conversion function. 9674 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9675 Cand1.Function && Cand2.Function && 9676 isa<CXXConstructorDecl>(Cand1.Function) != 9677 isa<CXXConstructorDecl>(Cand2.Function)) 9678 return isa<CXXConstructorDecl>(Cand1.Function); 9679 9680 // -- F1 is a non-template function and F2 is a function template 9681 // specialization, or, if not that, 9682 bool Cand1IsSpecialization = Cand1.Function && 9683 Cand1.Function->getPrimaryTemplate(); 9684 bool Cand2IsSpecialization = Cand2.Function && 9685 Cand2.Function->getPrimaryTemplate(); 9686 if (Cand1IsSpecialization != Cand2IsSpecialization) 9687 return Cand2IsSpecialization; 9688 9689 // -- F1 and F2 are function template specializations, and the function 9690 // template for F1 is more specialized than the template for F2 9691 // according to the partial ordering rules described in 14.5.5.2, or, 9692 // if not that, 9693 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9694 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9695 Cand1.Function->getPrimaryTemplate(), 9696 Cand2.Function->getPrimaryTemplate(), Loc, 9697 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9698 : TPOC_Call, 9699 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9700 Cand1.isReversed() ^ Cand2.isReversed())) 9701 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9702 } 9703 9704 // -— F1 and F2 are non-template functions with the same 9705 // parameter-type-lists, and F1 is more constrained than F2 [...], 9706 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9707 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9708 Cand2.Function->hasPrototype()) { 9709 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9710 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9711 if (PT1->getNumParams() == PT2->getNumParams() && 9712 PT1->isVariadic() == PT2->isVariadic() && 9713 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9714 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9715 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9716 if (RC1 && RC2) { 9717 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9718 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9719 {RC2}, AtLeastAsConstrained1) || 9720 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9721 {RC1}, AtLeastAsConstrained2)) 9722 return false; 9723 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9724 return AtLeastAsConstrained1; 9725 } else if (RC1 || RC2) { 9726 return RC1 != nullptr; 9727 } 9728 } 9729 } 9730 9731 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9732 // class B of D, and for all arguments the corresponding parameters of 9733 // F1 and F2 have the same type. 9734 // FIXME: Implement the "all parameters have the same type" check. 9735 bool Cand1IsInherited = 9736 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9737 bool Cand2IsInherited = 9738 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9739 if (Cand1IsInherited != Cand2IsInherited) 9740 return Cand2IsInherited; 9741 else if (Cand1IsInherited) { 9742 assert(Cand2IsInherited); 9743 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9744 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9745 if (Cand1Class->isDerivedFrom(Cand2Class)) 9746 return true; 9747 if (Cand2Class->isDerivedFrom(Cand1Class)) 9748 return false; 9749 // Inherited from sibling base classes: still ambiguous. 9750 } 9751 9752 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9753 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9754 // with reversed order of parameters and F1 is not 9755 // 9756 // We rank reversed + different operator as worse than just reversed, but 9757 // that comparison can never happen, because we only consider reversing for 9758 // the maximally-rewritten operator (== or <=>). 9759 if (Cand1.RewriteKind != Cand2.RewriteKind) 9760 return Cand1.RewriteKind < Cand2.RewriteKind; 9761 9762 // Check C++17 tie-breakers for deduction guides. 9763 { 9764 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9765 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9766 if (Guide1 && Guide2) { 9767 // -- F1 is generated from a deduction-guide and F2 is not 9768 if (Guide1->isImplicit() != Guide2->isImplicit()) 9769 return Guide2->isImplicit(); 9770 9771 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9772 if (Guide1->isCopyDeductionCandidate()) 9773 return true; 9774 } 9775 } 9776 9777 // Check for enable_if value-based overload resolution. 9778 if (Cand1.Function && Cand2.Function) { 9779 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9780 if (Cmp != Comparison::Equal) 9781 return Cmp == Comparison::Better; 9782 } 9783 9784 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9785 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9786 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9787 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9788 } 9789 9790 bool HasPS1 = Cand1.Function != nullptr && 9791 functionHasPassObjectSizeParams(Cand1.Function); 9792 bool HasPS2 = Cand2.Function != nullptr && 9793 functionHasPassObjectSizeParams(Cand2.Function); 9794 if (HasPS1 != HasPS2 && HasPS1) 9795 return true; 9796 9797 Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2); 9798 return MV == Comparison::Better; 9799 } 9800 9801 /// Determine whether two declarations are "equivalent" for the purposes of 9802 /// name lookup and overload resolution. This applies when the same internal/no 9803 /// linkage entity is defined by two modules (probably by textually including 9804 /// the same header). In such a case, we don't consider the declarations to 9805 /// declare the same entity, but we also don't want lookups with both 9806 /// declarations visible to be ambiguous in some cases (this happens when using 9807 /// a modularized libstdc++). 9808 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9809 const NamedDecl *B) { 9810 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9811 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9812 if (!VA || !VB) 9813 return false; 9814 9815 // The declarations must be declaring the same name as an internal linkage 9816 // entity in different modules. 9817 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9818 VB->getDeclContext()->getRedeclContext()) || 9819 getOwningModule(VA) == getOwningModule(VB) || 9820 VA->isExternallyVisible() || VB->isExternallyVisible()) 9821 return false; 9822 9823 // Check that the declarations appear to be equivalent. 9824 // 9825 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9826 // For constants and functions, we should check the initializer or body is 9827 // the same. For non-constant variables, we shouldn't allow it at all. 9828 if (Context.hasSameType(VA->getType(), VB->getType())) 9829 return true; 9830 9831 // Enum constants within unnamed enumerations will have different types, but 9832 // may still be similar enough to be interchangeable for our purposes. 9833 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9834 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9835 // Only handle anonymous enums. If the enumerations were named and 9836 // equivalent, they would have been merged to the same type. 9837 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9838 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9839 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9840 !Context.hasSameType(EnumA->getIntegerType(), 9841 EnumB->getIntegerType())) 9842 return false; 9843 // Allow this only if the value is the same for both enumerators. 9844 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9845 } 9846 } 9847 9848 // Nothing else is sufficiently similar. 9849 return false; 9850 } 9851 9852 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9853 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9854 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9855 9856 Module *M = getOwningModule(D); 9857 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9858 << !M << (M ? M->getFullModuleName() : ""); 9859 9860 for (auto *E : Equiv) { 9861 Module *M = getOwningModule(E); 9862 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9863 << !M << (M ? M->getFullModuleName() : ""); 9864 } 9865 } 9866 9867 /// Computes the best viable function (C++ 13.3.3) 9868 /// within an overload candidate set. 9869 /// 9870 /// \param Loc The location of the function name (or operator symbol) for 9871 /// which overload resolution occurs. 9872 /// 9873 /// \param Best If overload resolution was successful or found a deleted 9874 /// function, \p Best points to the candidate function found. 9875 /// 9876 /// \returns The result of overload resolution. 9877 OverloadingResult 9878 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9879 iterator &Best) { 9880 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9881 std::transform(begin(), end(), std::back_inserter(Candidates), 9882 [](OverloadCandidate &Cand) { return &Cand; }); 9883 9884 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9885 // are accepted by both clang and NVCC. However, during a particular 9886 // compilation mode only one call variant is viable. We need to 9887 // exclude non-viable overload candidates from consideration based 9888 // only on their host/device attributes. Specifically, if one 9889 // candidate call is WrongSide and the other is SameSide, we ignore 9890 // the WrongSide candidate. 9891 if (S.getLangOpts().CUDA) { 9892 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9893 bool ContainsSameSideCandidate = 9894 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9895 // Check viable function only. 9896 return Cand->Viable && Cand->Function && 9897 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9898 Sema::CFP_SameSide; 9899 }); 9900 if (ContainsSameSideCandidate) { 9901 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9902 // Check viable function only to avoid unnecessary data copying/moving. 9903 return Cand->Viable && Cand->Function && 9904 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9905 Sema::CFP_WrongSide; 9906 }; 9907 llvm::erase_if(Candidates, IsWrongSideCandidate); 9908 } 9909 } 9910 9911 // Find the best viable function. 9912 Best = end(); 9913 for (auto *Cand : Candidates) { 9914 Cand->Best = false; 9915 if (Cand->Viable) 9916 if (Best == end() || 9917 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9918 Best = Cand; 9919 } 9920 9921 // If we didn't find any viable functions, abort. 9922 if (Best == end()) 9923 return OR_No_Viable_Function; 9924 9925 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9926 9927 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9928 PendingBest.push_back(&*Best); 9929 Best->Best = true; 9930 9931 // Make sure that this function is better than every other viable 9932 // function. If not, we have an ambiguity. 9933 while (!PendingBest.empty()) { 9934 auto *Curr = PendingBest.pop_back_val(); 9935 for (auto *Cand : Candidates) { 9936 if (Cand->Viable && !Cand->Best && 9937 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9938 PendingBest.push_back(Cand); 9939 Cand->Best = true; 9940 9941 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9942 Curr->Function)) 9943 EquivalentCands.push_back(Cand->Function); 9944 else 9945 Best = end(); 9946 } 9947 } 9948 } 9949 9950 // If we found more than one best candidate, this is ambiguous. 9951 if (Best == end()) 9952 return OR_Ambiguous; 9953 9954 // Best is the best viable function. 9955 if (Best->Function && Best->Function->isDeleted()) 9956 return OR_Deleted; 9957 9958 if (!EquivalentCands.empty()) 9959 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9960 EquivalentCands); 9961 9962 return OR_Success; 9963 } 9964 9965 namespace { 9966 9967 enum OverloadCandidateKind { 9968 oc_function, 9969 oc_method, 9970 oc_reversed_binary_operator, 9971 oc_constructor, 9972 oc_implicit_default_constructor, 9973 oc_implicit_copy_constructor, 9974 oc_implicit_move_constructor, 9975 oc_implicit_copy_assignment, 9976 oc_implicit_move_assignment, 9977 oc_implicit_equality_comparison, 9978 oc_inherited_constructor 9979 }; 9980 9981 enum OverloadCandidateSelect { 9982 ocs_non_template, 9983 ocs_template, 9984 ocs_described_template, 9985 }; 9986 9987 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9988 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9989 OverloadCandidateRewriteKind CRK, 9990 std::string &Description) { 9991 9992 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9993 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9994 isTemplate = true; 9995 Description = S.getTemplateArgumentBindingsText( 9996 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9997 } 9998 9999 OverloadCandidateSelect Select = [&]() { 10000 if (!Description.empty()) 10001 return ocs_described_template; 10002 return isTemplate ? ocs_template : ocs_non_template; 10003 }(); 10004 10005 OverloadCandidateKind Kind = [&]() { 10006 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10007 return oc_implicit_equality_comparison; 10008 10009 if (CRK & CRK_Reversed) 10010 return oc_reversed_binary_operator; 10011 10012 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10013 if (!Ctor->isImplicit()) { 10014 if (isa<ConstructorUsingShadowDecl>(Found)) 10015 return oc_inherited_constructor; 10016 else 10017 return oc_constructor; 10018 } 10019 10020 if (Ctor->isDefaultConstructor()) 10021 return oc_implicit_default_constructor; 10022 10023 if (Ctor->isMoveConstructor()) 10024 return oc_implicit_move_constructor; 10025 10026 assert(Ctor->isCopyConstructor() && 10027 "unexpected sort of implicit constructor"); 10028 return oc_implicit_copy_constructor; 10029 } 10030 10031 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10032 // This actually gets spelled 'candidate function' for now, but 10033 // it doesn't hurt to split it out. 10034 if (!Meth->isImplicit()) 10035 return oc_method; 10036 10037 if (Meth->isMoveAssignmentOperator()) 10038 return oc_implicit_move_assignment; 10039 10040 if (Meth->isCopyAssignmentOperator()) 10041 return oc_implicit_copy_assignment; 10042 10043 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10044 return oc_method; 10045 } 10046 10047 return oc_function; 10048 }(); 10049 10050 return std::make_pair(Kind, Select); 10051 } 10052 10053 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10054 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10055 // set. 10056 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10057 S.Diag(FoundDecl->getLocation(), 10058 diag::note_ovl_candidate_inherited_constructor) 10059 << Shadow->getNominatedBaseClass(); 10060 } 10061 10062 } // end anonymous namespace 10063 10064 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10065 const FunctionDecl *FD) { 10066 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10067 bool AlwaysTrue; 10068 if (EnableIf->getCond()->isValueDependent() || 10069 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10070 return false; 10071 if (!AlwaysTrue) 10072 return false; 10073 } 10074 return true; 10075 } 10076 10077 /// Returns true if we can take the address of the function. 10078 /// 10079 /// \param Complain - If true, we'll emit a diagnostic 10080 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10081 /// we in overload resolution? 10082 /// \param Loc - The location of the statement we're complaining about. Ignored 10083 /// if we're not complaining, or if we're in overload resolution. 10084 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10085 bool Complain, 10086 bool InOverloadResolution, 10087 SourceLocation Loc) { 10088 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10089 if (Complain) { 10090 if (InOverloadResolution) 10091 S.Diag(FD->getBeginLoc(), 10092 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10093 else 10094 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10095 } 10096 return false; 10097 } 10098 10099 if (FD->getTrailingRequiresClause()) { 10100 ConstraintSatisfaction Satisfaction; 10101 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10102 return false; 10103 if (!Satisfaction.IsSatisfied) { 10104 if (Complain) { 10105 if (InOverloadResolution) 10106 S.Diag(FD->getBeginLoc(), 10107 diag::note_ovl_candidate_unsatisfied_constraints); 10108 else 10109 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10110 << FD; 10111 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10112 } 10113 return false; 10114 } 10115 } 10116 10117 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10118 return P->hasAttr<PassObjectSizeAttr>(); 10119 }); 10120 if (I == FD->param_end()) 10121 return true; 10122 10123 if (Complain) { 10124 // Add one to ParamNo because it's user-facing 10125 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10126 if (InOverloadResolution) 10127 S.Diag(FD->getLocation(), 10128 diag::note_ovl_candidate_has_pass_object_size_params) 10129 << ParamNo; 10130 else 10131 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10132 << FD << ParamNo; 10133 } 10134 return false; 10135 } 10136 10137 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10138 const FunctionDecl *FD) { 10139 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10140 /*InOverloadResolution=*/true, 10141 /*Loc=*/SourceLocation()); 10142 } 10143 10144 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10145 bool Complain, 10146 SourceLocation Loc) { 10147 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10148 /*InOverloadResolution=*/false, 10149 Loc); 10150 } 10151 10152 // Notes the location of an overload candidate. 10153 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10154 OverloadCandidateRewriteKind RewriteKind, 10155 QualType DestType, bool TakingAddress) { 10156 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10157 return; 10158 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10159 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10160 return; 10161 10162 std::string FnDesc; 10163 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10164 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10165 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10166 << (unsigned)KSPair.first << (unsigned)KSPair.second 10167 << Fn << FnDesc; 10168 10169 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10170 Diag(Fn->getLocation(), PD); 10171 MaybeEmitInheritedConstructorNote(*this, Found); 10172 } 10173 10174 static void 10175 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10176 // Perhaps the ambiguity was caused by two atomic constraints that are 10177 // 'identical' but not equivalent: 10178 // 10179 // void foo() requires (sizeof(T) > 4) { } // #1 10180 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10181 // 10182 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10183 // #2 to subsume #1, but these constraint are not considered equivalent 10184 // according to the subsumption rules because they are not the same 10185 // source-level construct. This behavior is quite confusing and we should try 10186 // to help the user figure out what happened. 10187 10188 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10189 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10190 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10191 if (!I->Function) 10192 continue; 10193 SmallVector<const Expr *, 3> AC; 10194 if (auto *Template = I->Function->getPrimaryTemplate()) 10195 Template->getAssociatedConstraints(AC); 10196 else 10197 I->Function->getAssociatedConstraints(AC); 10198 if (AC.empty()) 10199 continue; 10200 if (FirstCand == nullptr) { 10201 FirstCand = I->Function; 10202 FirstAC = AC; 10203 } else if (SecondCand == nullptr) { 10204 SecondCand = I->Function; 10205 SecondAC = AC; 10206 } else { 10207 // We have more than one pair of constrained functions - this check is 10208 // expensive and we'd rather not try to diagnose it. 10209 return; 10210 } 10211 } 10212 if (!SecondCand) 10213 return; 10214 // The diagnostic can only happen if there are associated constraints on 10215 // both sides (there needs to be some identical atomic constraint). 10216 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10217 SecondCand, SecondAC)) 10218 // Just show the user one diagnostic, they'll probably figure it out 10219 // from here. 10220 return; 10221 } 10222 10223 // Notes the location of all overload candidates designated through 10224 // OverloadedExpr 10225 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10226 bool TakingAddress) { 10227 assert(OverloadedExpr->getType() == Context.OverloadTy); 10228 10229 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10230 OverloadExpr *OvlExpr = Ovl.Expression; 10231 10232 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10233 IEnd = OvlExpr->decls_end(); 10234 I != IEnd; ++I) { 10235 if (FunctionTemplateDecl *FunTmpl = 10236 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10237 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10238 TakingAddress); 10239 } else if (FunctionDecl *Fun 10240 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10241 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10242 } 10243 } 10244 } 10245 10246 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10247 /// "lead" diagnostic; it will be given two arguments, the source and 10248 /// target types of the conversion. 10249 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10250 Sema &S, 10251 SourceLocation CaretLoc, 10252 const PartialDiagnostic &PDiag) const { 10253 S.Diag(CaretLoc, PDiag) 10254 << Ambiguous.getFromType() << Ambiguous.getToType(); 10255 // FIXME: The note limiting machinery is borrowed from 10256 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10257 // refactoring here. 10258 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10259 unsigned CandsShown = 0; 10260 AmbiguousConversionSequence::const_iterator I, E; 10261 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10262 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10263 break; 10264 ++CandsShown; 10265 S.NoteOverloadCandidate(I->first, I->second); 10266 } 10267 if (I != E) 10268 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10269 } 10270 10271 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10272 unsigned I, bool TakingCandidateAddress) { 10273 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10274 assert(Conv.isBad()); 10275 assert(Cand->Function && "for now, candidate must be a function"); 10276 FunctionDecl *Fn = Cand->Function; 10277 10278 // There's a conversion slot for the object argument if this is a 10279 // non-constructor method. Note that 'I' corresponds the 10280 // conversion-slot index. 10281 bool isObjectArgument = false; 10282 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10283 if (I == 0) 10284 isObjectArgument = true; 10285 else 10286 I--; 10287 } 10288 10289 std::string FnDesc; 10290 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10291 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10292 FnDesc); 10293 10294 Expr *FromExpr = Conv.Bad.FromExpr; 10295 QualType FromTy = Conv.Bad.getFromType(); 10296 QualType ToTy = Conv.Bad.getToType(); 10297 10298 if (FromTy == S.Context.OverloadTy) { 10299 assert(FromExpr && "overload set argument came from implicit argument?"); 10300 Expr *E = FromExpr->IgnoreParens(); 10301 if (isa<UnaryOperator>(E)) 10302 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10303 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10304 10305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10306 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10307 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10308 << Name << I + 1; 10309 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10310 return; 10311 } 10312 10313 // Do some hand-waving analysis to see if the non-viability is due 10314 // to a qualifier mismatch. 10315 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10316 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10317 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10318 CToTy = RT->getPointeeType(); 10319 else { 10320 // TODO: detect and diagnose the full richness of const mismatches. 10321 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10322 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10323 CFromTy = FromPT->getPointeeType(); 10324 CToTy = ToPT->getPointeeType(); 10325 } 10326 } 10327 10328 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10329 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10330 Qualifiers FromQs = CFromTy.getQualifiers(); 10331 Qualifiers ToQs = CToTy.getQualifiers(); 10332 10333 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10334 if (isObjectArgument) 10335 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10336 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10337 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10338 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10339 else 10340 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10341 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10342 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10343 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10344 << ToTy->isReferenceType() << I + 1; 10345 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10346 return; 10347 } 10348 10349 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10351 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10352 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10353 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10354 << (unsigned)isObjectArgument << I + 1; 10355 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10356 return; 10357 } 10358 10359 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10360 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10361 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10362 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10363 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10364 << (unsigned)isObjectArgument << I + 1; 10365 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10366 return; 10367 } 10368 10369 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10370 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10371 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10372 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10373 << FromQs.hasUnaligned() << I + 1; 10374 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10375 return; 10376 } 10377 10378 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10379 assert(CVR && "unexpected qualifiers mismatch"); 10380 10381 if (isObjectArgument) { 10382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10383 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10384 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10385 << (CVR - 1); 10386 } else { 10387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10388 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10390 << (CVR - 1) << I + 1; 10391 } 10392 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10393 return; 10394 } 10395 10396 // Special diagnostic for failure to convert an initializer list, since 10397 // telling the user that it has type void is not useful. 10398 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10399 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10400 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10401 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10402 << ToTy << (unsigned)isObjectArgument << I + 1; 10403 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10404 return; 10405 } 10406 10407 // Diagnose references or pointers to incomplete types differently, 10408 // since it's far from impossible that the incompleteness triggered 10409 // the failure. 10410 QualType TempFromTy = FromTy.getNonReferenceType(); 10411 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10412 TempFromTy = PTy->getPointeeType(); 10413 if (TempFromTy->isIncompleteType()) { 10414 // Emit the generic diagnostic and, optionally, add the hints to it. 10415 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10416 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10417 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10418 << ToTy << (unsigned)isObjectArgument << I + 1 10419 << (unsigned)(Cand->Fix.Kind); 10420 10421 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10422 return; 10423 } 10424 10425 // Diagnose base -> derived pointer conversions. 10426 unsigned BaseToDerivedConversion = 0; 10427 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10428 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10429 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10430 FromPtrTy->getPointeeType()) && 10431 !FromPtrTy->getPointeeType()->isIncompleteType() && 10432 !ToPtrTy->getPointeeType()->isIncompleteType() && 10433 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10434 FromPtrTy->getPointeeType())) 10435 BaseToDerivedConversion = 1; 10436 } 10437 } else if (const ObjCObjectPointerType *FromPtrTy 10438 = FromTy->getAs<ObjCObjectPointerType>()) { 10439 if (const ObjCObjectPointerType *ToPtrTy 10440 = ToTy->getAs<ObjCObjectPointerType>()) 10441 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10442 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10443 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10444 FromPtrTy->getPointeeType()) && 10445 FromIface->isSuperClassOf(ToIface)) 10446 BaseToDerivedConversion = 2; 10447 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10448 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10449 !FromTy->isIncompleteType() && 10450 !ToRefTy->getPointeeType()->isIncompleteType() && 10451 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10452 BaseToDerivedConversion = 3; 10453 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10454 ToTy.getNonReferenceType().getCanonicalType() == 10455 FromTy.getNonReferenceType().getCanonicalType()) { 10456 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10457 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10458 << (unsigned)isObjectArgument << I + 1 10459 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10460 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10461 return; 10462 } 10463 } 10464 10465 if (BaseToDerivedConversion) { 10466 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10467 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10468 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10469 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10470 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10471 return; 10472 } 10473 10474 if (isa<ObjCObjectPointerType>(CFromTy) && 10475 isa<PointerType>(CToTy)) { 10476 Qualifiers FromQs = CFromTy.getQualifiers(); 10477 Qualifiers ToQs = CToTy.getQualifiers(); 10478 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10479 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10480 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10481 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10482 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10483 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10484 return; 10485 } 10486 } 10487 10488 if (TakingCandidateAddress && 10489 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10490 return; 10491 10492 // Emit the generic diagnostic and, optionally, add the hints to it. 10493 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10494 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10495 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10496 << ToTy << (unsigned)isObjectArgument << I + 1 10497 << (unsigned)(Cand->Fix.Kind); 10498 10499 // If we can fix the conversion, suggest the FixIts. 10500 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10501 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10502 FDiag << *HI; 10503 S.Diag(Fn->getLocation(), FDiag); 10504 10505 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10506 } 10507 10508 /// Additional arity mismatch diagnosis specific to a function overload 10509 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10510 /// over a candidate in any candidate set. 10511 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10512 unsigned NumArgs) { 10513 FunctionDecl *Fn = Cand->Function; 10514 unsigned MinParams = Fn->getMinRequiredArguments(); 10515 10516 // With invalid overloaded operators, it's possible that we think we 10517 // have an arity mismatch when in fact it looks like we have the 10518 // right number of arguments, because only overloaded operators have 10519 // the weird behavior of overloading member and non-member functions. 10520 // Just don't report anything. 10521 if (Fn->isInvalidDecl() && 10522 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10523 return true; 10524 10525 if (NumArgs < MinParams) { 10526 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10527 (Cand->FailureKind == ovl_fail_bad_deduction && 10528 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10529 } else { 10530 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10531 (Cand->FailureKind == ovl_fail_bad_deduction && 10532 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10533 } 10534 10535 return false; 10536 } 10537 10538 /// General arity mismatch diagnosis over a candidate in a candidate set. 10539 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10540 unsigned NumFormalArgs) { 10541 assert(isa<FunctionDecl>(D) && 10542 "The templated declaration should at least be a function" 10543 " when diagnosing bad template argument deduction due to too many" 10544 " or too few arguments"); 10545 10546 FunctionDecl *Fn = cast<FunctionDecl>(D); 10547 10548 // TODO: treat calls to a missing default constructor as a special case 10549 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10550 unsigned MinParams = Fn->getMinRequiredArguments(); 10551 10552 // at least / at most / exactly 10553 unsigned mode, modeCount; 10554 if (NumFormalArgs < MinParams) { 10555 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10556 FnTy->isTemplateVariadic()) 10557 mode = 0; // "at least" 10558 else 10559 mode = 2; // "exactly" 10560 modeCount = MinParams; 10561 } else { 10562 if (MinParams != FnTy->getNumParams()) 10563 mode = 1; // "at most" 10564 else 10565 mode = 2; // "exactly" 10566 modeCount = FnTy->getNumParams(); 10567 } 10568 10569 std::string Description; 10570 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10571 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10572 10573 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10574 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10575 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10576 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10577 else 10578 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10579 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10580 << Description << mode << modeCount << NumFormalArgs; 10581 10582 MaybeEmitInheritedConstructorNote(S, Found); 10583 } 10584 10585 /// Arity mismatch diagnosis specific to a function overload candidate. 10586 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10587 unsigned NumFormalArgs) { 10588 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10589 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10590 } 10591 10592 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10593 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10594 return TD; 10595 llvm_unreachable("Unsupported: Getting the described template declaration" 10596 " for bad deduction diagnosis"); 10597 } 10598 10599 /// Diagnose a failed template-argument deduction. 10600 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10601 DeductionFailureInfo &DeductionFailure, 10602 unsigned NumArgs, 10603 bool TakingCandidateAddress) { 10604 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10605 NamedDecl *ParamD; 10606 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10607 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10608 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10609 switch (DeductionFailure.Result) { 10610 case Sema::TDK_Success: 10611 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10612 10613 case Sema::TDK_Incomplete: { 10614 assert(ParamD && "no parameter found for incomplete deduction result"); 10615 S.Diag(Templated->getLocation(), 10616 diag::note_ovl_candidate_incomplete_deduction) 10617 << ParamD->getDeclName(); 10618 MaybeEmitInheritedConstructorNote(S, Found); 10619 return; 10620 } 10621 10622 case Sema::TDK_IncompletePack: { 10623 assert(ParamD && "no parameter found for incomplete deduction result"); 10624 S.Diag(Templated->getLocation(), 10625 diag::note_ovl_candidate_incomplete_deduction_pack) 10626 << ParamD->getDeclName() 10627 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10628 << *DeductionFailure.getFirstArg(); 10629 MaybeEmitInheritedConstructorNote(S, Found); 10630 return; 10631 } 10632 10633 case Sema::TDK_Underqualified: { 10634 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10635 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10636 10637 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10638 10639 // Param will have been canonicalized, but it should just be a 10640 // qualified version of ParamD, so move the qualifiers to that. 10641 QualifierCollector Qs; 10642 Qs.strip(Param); 10643 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10644 assert(S.Context.hasSameType(Param, NonCanonParam)); 10645 10646 // Arg has also been canonicalized, but there's nothing we can do 10647 // about that. It also doesn't matter as much, because it won't 10648 // have any template parameters in it (because deduction isn't 10649 // done on dependent types). 10650 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10651 10652 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10653 << ParamD->getDeclName() << Arg << NonCanonParam; 10654 MaybeEmitInheritedConstructorNote(S, Found); 10655 return; 10656 } 10657 10658 case Sema::TDK_Inconsistent: { 10659 assert(ParamD && "no parameter found for inconsistent deduction result"); 10660 int which = 0; 10661 if (isa<TemplateTypeParmDecl>(ParamD)) 10662 which = 0; 10663 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10664 // Deduction might have failed because we deduced arguments of two 10665 // different types for a non-type template parameter. 10666 // FIXME: Use a different TDK value for this. 10667 QualType T1 = 10668 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10669 QualType T2 = 10670 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10671 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10672 S.Diag(Templated->getLocation(), 10673 diag::note_ovl_candidate_inconsistent_deduction_types) 10674 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10675 << *DeductionFailure.getSecondArg() << T2; 10676 MaybeEmitInheritedConstructorNote(S, Found); 10677 return; 10678 } 10679 10680 which = 1; 10681 } else { 10682 which = 2; 10683 } 10684 10685 // Tweak the diagnostic if the problem is that we deduced packs of 10686 // different arities. We'll print the actual packs anyway in case that 10687 // includes additional useful information. 10688 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10689 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10690 DeductionFailure.getFirstArg()->pack_size() != 10691 DeductionFailure.getSecondArg()->pack_size()) { 10692 which = 3; 10693 } 10694 10695 S.Diag(Templated->getLocation(), 10696 diag::note_ovl_candidate_inconsistent_deduction) 10697 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10698 << *DeductionFailure.getSecondArg(); 10699 MaybeEmitInheritedConstructorNote(S, Found); 10700 return; 10701 } 10702 10703 case Sema::TDK_InvalidExplicitArguments: 10704 assert(ParamD && "no parameter found for invalid explicit arguments"); 10705 if (ParamD->getDeclName()) 10706 S.Diag(Templated->getLocation(), 10707 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10708 << ParamD->getDeclName(); 10709 else { 10710 int index = 0; 10711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10712 index = TTP->getIndex(); 10713 else if (NonTypeTemplateParmDecl *NTTP 10714 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10715 index = NTTP->getIndex(); 10716 else 10717 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10718 S.Diag(Templated->getLocation(), 10719 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10720 << (index + 1); 10721 } 10722 MaybeEmitInheritedConstructorNote(S, Found); 10723 return; 10724 10725 case Sema::TDK_ConstraintsNotSatisfied: { 10726 // Format the template argument list into the argument string. 10727 SmallString<128> TemplateArgString; 10728 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10729 TemplateArgString = " "; 10730 TemplateArgString += S.getTemplateArgumentBindingsText( 10731 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10732 if (TemplateArgString.size() == 1) 10733 TemplateArgString.clear(); 10734 S.Diag(Templated->getLocation(), 10735 diag::note_ovl_candidate_unsatisfied_constraints) 10736 << TemplateArgString; 10737 10738 S.DiagnoseUnsatisfiedConstraint( 10739 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10740 return; 10741 } 10742 case Sema::TDK_TooManyArguments: 10743 case Sema::TDK_TooFewArguments: 10744 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10745 return; 10746 10747 case Sema::TDK_InstantiationDepth: 10748 S.Diag(Templated->getLocation(), 10749 diag::note_ovl_candidate_instantiation_depth); 10750 MaybeEmitInheritedConstructorNote(S, Found); 10751 return; 10752 10753 case Sema::TDK_SubstitutionFailure: { 10754 // Format the template argument list into the argument string. 10755 SmallString<128> TemplateArgString; 10756 if (TemplateArgumentList *Args = 10757 DeductionFailure.getTemplateArgumentList()) { 10758 TemplateArgString = " "; 10759 TemplateArgString += S.getTemplateArgumentBindingsText( 10760 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10761 if (TemplateArgString.size() == 1) 10762 TemplateArgString.clear(); 10763 } 10764 10765 // If this candidate was disabled by enable_if, say so. 10766 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10767 if (PDiag && PDiag->second.getDiagID() == 10768 diag::err_typename_nested_not_found_enable_if) { 10769 // FIXME: Use the source range of the condition, and the fully-qualified 10770 // name of the enable_if template. These are both present in PDiag. 10771 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10772 << "'enable_if'" << TemplateArgString; 10773 return; 10774 } 10775 10776 // We found a specific requirement that disabled the enable_if. 10777 if (PDiag && PDiag->second.getDiagID() == 10778 diag::err_typename_nested_not_found_requirement) { 10779 S.Diag(Templated->getLocation(), 10780 diag::note_ovl_candidate_disabled_by_requirement) 10781 << PDiag->second.getStringArg(0) << TemplateArgString; 10782 return; 10783 } 10784 10785 // Format the SFINAE diagnostic into the argument string. 10786 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10787 // formatted message in another diagnostic. 10788 SmallString<128> SFINAEArgString; 10789 SourceRange R; 10790 if (PDiag) { 10791 SFINAEArgString = ": "; 10792 R = SourceRange(PDiag->first, PDiag->first); 10793 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10794 } 10795 10796 S.Diag(Templated->getLocation(), 10797 diag::note_ovl_candidate_substitution_failure) 10798 << TemplateArgString << SFINAEArgString << R; 10799 MaybeEmitInheritedConstructorNote(S, Found); 10800 return; 10801 } 10802 10803 case Sema::TDK_DeducedMismatch: 10804 case Sema::TDK_DeducedMismatchNested: { 10805 // Format the template argument list into the argument string. 10806 SmallString<128> TemplateArgString; 10807 if (TemplateArgumentList *Args = 10808 DeductionFailure.getTemplateArgumentList()) { 10809 TemplateArgString = " "; 10810 TemplateArgString += S.getTemplateArgumentBindingsText( 10811 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10812 if (TemplateArgString.size() == 1) 10813 TemplateArgString.clear(); 10814 } 10815 10816 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10817 << (*DeductionFailure.getCallArgIndex() + 1) 10818 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10819 << TemplateArgString 10820 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10821 break; 10822 } 10823 10824 case Sema::TDK_NonDeducedMismatch: { 10825 // FIXME: Provide a source location to indicate what we couldn't match. 10826 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10827 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10828 if (FirstTA.getKind() == TemplateArgument::Template && 10829 SecondTA.getKind() == TemplateArgument::Template) { 10830 TemplateName FirstTN = FirstTA.getAsTemplate(); 10831 TemplateName SecondTN = SecondTA.getAsTemplate(); 10832 if (FirstTN.getKind() == TemplateName::Template && 10833 SecondTN.getKind() == TemplateName::Template) { 10834 if (FirstTN.getAsTemplateDecl()->getName() == 10835 SecondTN.getAsTemplateDecl()->getName()) { 10836 // FIXME: This fixes a bad diagnostic where both templates are named 10837 // the same. This particular case is a bit difficult since: 10838 // 1) It is passed as a string to the diagnostic printer. 10839 // 2) The diagnostic printer only attempts to find a better 10840 // name for types, not decls. 10841 // Ideally, this should folded into the diagnostic printer. 10842 S.Diag(Templated->getLocation(), 10843 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10844 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10845 return; 10846 } 10847 } 10848 } 10849 10850 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10851 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10852 return; 10853 10854 // FIXME: For generic lambda parameters, check if the function is a lambda 10855 // call operator, and if so, emit a prettier and more informative 10856 // diagnostic that mentions 'auto' and lambda in addition to 10857 // (or instead of?) the canonical template type parameters. 10858 S.Diag(Templated->getLocation(), 10859 diag::note_ovl_candidate_non_deduced_mismatch) 10860 << FirstTA << SecondTA; 10861 return; 10862 } 10863 // TODO: diagnose these individually, then kill off 10864 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10865 case Sema::TDK_MiscellaneousDeductionFailure: 10866 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10867 MaybeEmitInheritedConstructorNote(S, Found); 10868 return; 10869 case Sema::TDK_CUDATargetMismatch: 10870 S.Diag(Templated->getLocation(), 10871 diag::note_cuda_ovl_candidate_target_mismatch); 10872 return; 10873 } 10874 } 10875 10876 /// Diagnose a failed template-argument deduction, for function calls. 10877 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10878 unsigned NumArgs, 10879 bool TakingCandidateAddress) { 10880 unsigned TDK = Cand->DeductionFailure.Result; 10881 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10882 if (CheckArityMismatch(S, Cand, NumArgs)) 10883 return; 10884 } 10885 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10886 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10887 } 10888 10889 /// CUDA: diagnose an invalid call across targets. 10890 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10891 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10892 FunctionDecl *Callee = Cand->Function; 10893 10894 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10895 CalleeTarget = S.IdentifyCUDATarget(Callee); 10896 10897 std::string FnDesc; 10898 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10899 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10900 Cand->getRewriteKind(), FnDesc); 10901 10902 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10903 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10904 << FnDesc /* Ignored */ 10905 << CalleeTarget << CallerTarget; 10906 10907 // This could be an implicit constructor for which we could not infer the 10908 // target due to a collsion. Diagnose that case. 10909 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10910 if (Meth != nullptr && Meth->isImplicit()) { 10911 CXXRecordDecl *ParentClass = Meth->getParent(); 10912 Sema::CXXSpecialMember CSM; 10913 10914 switch (FnKindPair.first) { 10915 default: 10916 return; 10917 case oc_implicit_default_constructor: 10918 CSM = Sema::CXXDefaultConstructor; 10919 break; 10920 case oc_implicit_copy_constructor: 10921 CSM = Sema::CXXCopyConstructor; 10922 break; 10923 case oc_implicit_move_constructor: 10924 CSM = Sema::CXXMoveConstructor; 10925 break; 10926 case oc_implicit_copy_assignment: 10927 CSM = Sema::CXXCopyAssignment; 10928 break; 10929 case oc_implicit_move_assignment: 10930 CSM = Sema::CXXMoveAssignment; 10931 break; 10932 }; 10933 10934 bool ConstRHS = false; 10935 if (Meth->getNumParams()) { 10936 if (const ReferenceType *RT = 10937 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10938 ConstRHS = RT->getPointeeType().isConstQualified(); 10939 } 10940 } 10941 10942 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10943 /* ConstRHS */ ConstRHS, 10944 /* Diagnose */ true); 10945 } 10946 } 10947 10948 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10949 FunctionDecl *Callee = Cand->Function; 10950 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10951 10952 S.Diag(Callee->getLocation(), 10953 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10954 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10955 } 10956 10957 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10958 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10959 assert(ES.isExplicit() && "not an explicit candidate"); 10960 10961 unsigned Kind; 10962 switch (Cand->Function->getDeclKind()) { 10963 case Decl::Kind::CXXConstructor: 10964 Kind = 0; 10965 break; 10966 case Decl::Kind::CXXConversion: 10967 Kind = 1; 10968 break; 10969 case Decl::Kind::CXXDeductionGuide: 10970 Kind = Cand->Function->isImplicit() ? 0 : 2; 10971 break; 10972 default: 10973 llvm_unreachable("invalid Decl"); 10974 } 10975 10976 // Note the location of the first (in-class) declaration; a redeclaration 10977 // (particularly an out-of-class definition) will typically lack the 10978 // 'explicit' specifier. 10979 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10980 FunctionDecl *First = Cand->Function->getFirstDecl(); 10981 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10982 First = Pattern->getFirstDecl(); 10983 10984 S.Diag(First->getLocation(), 10985 diag::note_ovl_candidate_explicit) 10986 << Kind << (ES.getExpr() ? 1 : 0) 10987 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10988 } 10989 10990 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10991 FunctionDecl *Callee = Cand->Function; 10992 10993 S.Diag(Callee->getLocation(), 10994 diag::note_ovl_candidate_disabled_by_extension) 10995 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10996 } 10997 10998 /// Generates a 'note' diagnostic for an overload candidate. We've 10999 /// already generated a primary error at the call site. 11000 /// 11001 /// It really does need to be a single diagnostic with its caret 11002 /// pointed at the candidate declaration. Yes, this creates some 11003 /// major challenges of technical writing. Yes, this makes pointing 11004 /// out problems with specific arguments quite awkward. It's still 11005 /// better than generating twenty screens of text for every failed 11006 /// overload. 11007 /// 11008 /// It would be great to be able to express per-candidate problems 11009 /// more richly for those diagnostic clients that cared, but we'd 11010 /// still have to be just as careful with the default diagnostics. 11011 /// \param CtorDestAS Addr space of object being constructed (for ctor 11012 /// candidates only). 11013 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11014 unsigned NumArgs, 11015 bool TakingCandidateAddress, 11016 LangAS CtorDestAS = LangAS::Default) { 11017 FunctionDecl *Fn = Cand->Function; 11018 11019 // Note deleted candidates, but only if they're viable. 11020 if (Cand->Viable) { 11021 if (Fn->isDeleted()) { 11022 std::string FnDesc; 11023 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11024 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11025 Cand->getRewriteKind(), FnDesc); 11026 11027 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11028 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11029 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11030 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11031 return; 11032 } 11033 11034 // We don't really have anything else to say about viable candidates. 11035 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11036 return; 11037 } 11038 11039 switch (Cand->FailureKind) { 11040 case ovl_fail_too_many_arguments: 11041 case ovl_fail_too_few_arguments: 11042 return DiagnoseArityMismatch(S, Cand, NumArgs); 11043 11044 case ovl_fail_bad_deduction: 11045 return DiagnoseBadDeduction(S, Cand, NumArgs, 11046 TakingCandidateAddress); 11047 11048 case ovl_fail_illegal_constructor: { 11049 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11050 << (Fn->getPrimaryTemplate() ? 1 : 0); 11051 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11052 return; 11053 } 11054 11055 case ovl_fail_object_addrspace_mismatch: { 11056 Qualifiers QualsForPrinting; 11057 QualsForPrinting.setAddressSpace(CtorDestAS); 11058 S.Diag(Fn->getLocation(), 11059 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11060 << QualsForPrinting; 11061 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11062 return; 11063 } 11064 11065 case ovl_fail_trivial_conversion: 11066 case ovl_fail_bad_final_conversion: 11067 case ovl_fail_final_conversion_not_exact: 11068 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11069 11070 case ovl_fail_bad_conversion: { 11071 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11072 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11073 if (Cand->Conversions[I].isBad()) 11074 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11075 11076 // FIXME: this currently happens when we're called from SemaInit 11077 // when user-conversion overload fails. Figure out how to handle 11078 // those conditions and diagnose them well. 11079 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11080 } 11081 11082 case ovl_fail_bad_target: 11083 return DiagnoseBadTarget(S, Cand); 11084 11085 case ovl_fail_enable_if: 11086 return DiagnoseFailedEnableIfAttr(S, Cand); 11087 11088 case ovl_fail_explicit: 11089 return DiagnoseFailedExplicitSpec(S, Cand); 11090 11091 case ovl_fail_ext_disabled: 11092 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11093 11094 case ovl_fail_inhctor_slice: 11095 // It's generally not interesting to note copy/move constructors here. 11096 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11097 return; 11098 S.Diag(Fn->getLocation(), 11099 diag::note_ovl_candidate_inherited_constructor_slice) 11100 << (Fn->getPrimaryTemplate() ? 1 : 0) 11101 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11102 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11103 return; 11104 11105 case ovl_fail_addr_not_available: { 11106 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11107 (void)Available; 11108 assert(!Available); 11109 break; 11110 } 11111 case ovl_non_default_multiversion_function: 11112 // Do nothing, these should simply be ignored. 11113 break; 11114 11115 case ovl_fail_constraints_not_satisfied: { 11116 std::string FnDesc; 11117 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11118 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11119 Cand->getRewriteKind(), FnDesc); 11120 11121 S.Diag(Fn->getLocation(), 11122 diag::note_ovl_candidate_constraints_not_satisfied) 11123 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11124 << FnDesc /* Ignored */; 11125 ConstraintSatisfaction Satisfaction; 11126 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11127 break; 11128 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11129 } 11130 } 11131 } 11132 11133 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11134 // Desugar the type of the surrogate down to a function type, 11135 // retaining as many typedefs as possible while still showing 11136 // the function type (and, therefore, its parameter types). 11137 QualType FnType = Cand->Surrogate->getConversionType(); 11138 bool isLValueReference = false; 11139 bool isRValueReference = false; 11140 bool isPointer = false; 11141 if (const LValueReferenceType *FnTypeRef = 11142 FnType->getAs<LValueReferenceType>()) { 11143 FnType = FnTypeRef->getPointeeType(); 11144 isLValueReference = true; 11145 } else if (const RValueReferenceType *FnTypeRef = 11146 FnType->getAs<RValueReferenceType>()) { 11147 FnType = FnTypeRef->getPointeeType(); 11148 isRValueReference = true; 11149 } 11150 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11151 FnType = FnTypePtr->getPointeeType(); 11152 isPointer = true; 11153 } 11154 // Desugar down to a function type. 11155 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11156 // Reconstruct the pointer/reference as appropriate. 11157 if (isPointer) FnType = S.Context.getPointerType(FnType); 11158 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11159 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11160 11161 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11162 << FnType; 11163 } 11164 11165 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11166 SourceLocation OpLoc, 11167 OverloadCandidate *Cand) { 11168 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11169 std::string TypeStr("operator"); 11170 TypeStr += Opc; 11171 TypeStr += "("; 11172 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11173 if (Cand->Conversions.size() == 1) { 11174 TypeStr += ")"; 11175 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11176 } else { 11177 TypeStr += ", "; 11178 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11179 TypeStr += ")"; 11180 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11181 } 11182 } 11183 11184 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11185 OverloadCandidate *Cand) { 11186 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11187 if (ICS.isBad()) break; // all meaningless after first invalid 11188 if (!ICS.isAmbiguous()) continue; 11189 11190 ICS.DiagnoseAmbiguousConversion( 11191 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11192 } 11193 } 11194 11195 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11196 if (Cand->Function) 11197 return Cand->Function->getLocation(); 11198 if (Cand->IsSurrogate) 11199 return Cand->Surrogate->getLocation(); 11200 return SourceLocation(); 11201 } 11202 11203 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11204 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11205 case Sema::TDK_Success: 11206 case Sema::TDK_NonDependentConversionFailure: 11207 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11208 11209 case Sema::TDK_Invalid: 11210 case Sema::TDK_Incomplete: 11211 case Sema::TDK_IncompletePack: 11212 return 1; 11213 11214 case Sema::TDK_Underqualified: 11215 case Sema::TDK_Inconsistent: 11216 return 2; 11217 11218 case Sema::TDK_SubstitutionFailure: 11219 case Sema::TDK_DeducedMismatch: 11220 case Sema::TDK_ConstraintsNotSatisfied: 11221 case Sema::TDK_DeducedMismatchNested: 11222 case Sema::TDK_NonDeducedMismatch: 11223 case Sema::TDK_MiscellaneousDeductionFailure: 11224 case Sema::TDK_CUDATargetMismatch: 11225 return 3; 11226 11227 case Sema::TDK_InstantiationDepth: 11228 return 4; 11229 11230 case Sema::TDK_InvalidExplicitArguments: 11231 return 5; 11232 11233 case Sema::TDK_TooManyArguments: 11234 case Sema::TDK_TooFewArguments: 11235 return 6; 11236 } 11237 llvm_unreachable("Unhandled deduction result"); 11238 } 11239 11240 namespace { 11241 struct CompareOverloadCandidatesForDisplay { 11242 Sema &S; 11243 SourceLocation Loc; 11244 size_t NumArgs; 11245 OverloadCandidateSet::CandidateSetKind CSK; 11246 11247 CompareOverloadCandidatesForDisplay( 11248 Sema &S, SourceLocation Loc, size_t NArgs, 11249 OverloadCandidateSet::CandidateSetKind CSK) 11250 : S(S), NumArgs(NArgs), CSK(CSK) {} 11251 11252 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11253 // If there are too many or too few arguments, that's the high-order bit we 11254 // want to sort by, even if the immediate failure kind was something else. 11255 if (C->FailureKind == ovl_fail_too_many_arguments || 11256 C->FailureKind == ovl_fail_too_few_arguments) 11257 return static_cast<OverloadFailureKind>(C->FailureKind); 11258 11259 if (C->Function) { 11260 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11261 return ovl_fail_too_many_arguments; 11262 if (NumArgs < C->Function->getMinRequiredArguments()) 11263 return ovl_fail_too_few_arguments; 11264 } 11265 11266 return static_cast<OverloadFailureKind>(C->FailureKind); 11267 } 11268 11269 bool operator()(const OverloadCandidate *L, 11270 const OverloadCandidate *R) { 11271 // Fast-path this check. 11272 if (L == R) return false; 11273 11274 // Order first by viability. 11275 if (L->Viable) { 11276 if (!R->Viable) return true; 11277 11278 // TODO: introduce a tri-valued comparison for overload 11279 // candidates. Would be more worthwhile if we had a sort 11280 // that could exploit it. 11281 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11282 return true; 11283 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11284 return false; 11285 } else if (R->Viable) 11286 return false; 11287 11288 assert(L->Viable == R->Viable); 11289 11290 // Criteria by which we can sort non-viable candidates: 11291 if (!L->Viable) { 11292 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11293 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11294 11295 // 1. Arity mismatches come after other candidates. 11296 if (LFailureKind == ovl_fail_too_many_arguments || 11297 LFailureKind == ovl_fail_too_few_arguments) { 11298 if (RFailureKind == ovl_fail_too_many_arguments || 11299 RFailureKind == ovl_fail_too_few_arguments) { 11300 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11301 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11302 if (LDist == RDist) { 11303 if (LFailureKind == RFailureKind) 11304 // Sort non-surrogates before surrogates. 11305 return !L->IsSurrogate && R->IsSurrogate; 11306 // Sort candidates requiring fewer parameters than there were 11307 // arguments given after candidates requiring more parameters 11308 // than there were arguments given. 11309 return LFailureKind == ovl_fail_too_many_arguments; 11310 } 11311 return LDist < RDist; 11312 } 11313 return false; 11314 } 11315 if (RFailureKind == ovl_fail_too_many_arguments || 11316 RFailureKind == ovl_fail_too_few_arguments) 11317 return true; 11318 11319 // 2. Bad conversions come first and are ordered by the number 11320 // of bad conversions and quality of good conversions. 11321 if (LFailureKind == ovl_fail_bad_conversion) { 11322 if (RFailureKind != ovl_fail_bad_conversion) 11323 return true; 11324 11325 // The conversion that can be fixed with a smaller number of changes, 11326 // comes first. 11327 unsigned numLFixes = L->Fix.NumConversionsFixed; 11328 unsigned numRFixes = R->Fix.NumConversionsFixed; 11329 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11330 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11331 if (numLFixes != numRFixes) { 11332 return numLFixes < numRFixes; 11333 } 11334 11335 // If there's any ordering between the defined conversions... 11336 // FIXME: this might not be transitive. 11337 assert(L->Conversions.size() == R->Conversions.size()); 11338 11339 int leftBetter = 0; 11340 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11341 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11342 switch (CompareImplicitConversionSequences(S, Loc, 11343 L->Conversions[I], 11344 R->Conversions[I])) { 11345 case ImplicitConversionSequence::Better: 11346 leftBetter++; 11347 break; 11348 11349 case ImplicitConversionSequence::Worse: 11350 leftBetter--; 11351 break; 11352 11353 case ImplicitConversionSequence::Indistinguishable: 11354 break; 11355 } 11356 } 11357 if (leftBetter > 0) return true; 11358 if (leftBetter < 0) return false; 11359 11360 } else if (RFailureKind == ovl_fail_bad_conversion) 11361 return false; 11362 11363 if (LFailureKind == ovl_fail_bad_deduction) { 11364 if (RFailureKind != ovl_fail_bad_deduction) 11365 return true; 11366 11367 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11368 return RankDeductionFailure(L->DeductionFailure) 11369 < RankDeductionFailure(R->DeductionFailure); 11370 } else if (RFailureKind == ovl_fail_bad_deduction) 11371 return false; 11372 11373 // TODO: others? 11374 } 11375 11376 // Sort everything else by location. 11377 SourceLocation LLoc = GetLocationForCandidate(L); 11378 SourceLocation RLoc = GetLocationForCandidate(R); 11379 11380 // Put candidates without locations (e.g. builtins) at the end. 11381 if (LLoc.isInvalid()) return false; 11382 if (RLoc.isInvalid()) return true; 11383 11384 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11385 } 11386 }; 11387 } 11388 11389 /// CompleteNonViableCandidate - Normally, overload resolution only 11390 /// computes up to the first bad conversion. Produces the FixIt set if 11391 /// possible. 11392 static void 11393 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11394 ArrayRef<Expr *> Args, 11395 OverloadCandidateSet::CandidateSetKind CSK) { 11396 assert(!Cand->Viable); 11397 11398 // Don't do anything on failures other than bad conversion. 11399 if (Cand->FailureKind != ovl_fail_bad_conversion) 11400 return; 11401 11402 // We only want the FixIts if all the arguments can be corrected. 11403 bool Unfixable = false; 11404 // Use a implicit copy initialization to check conversion fixes. 11405 Cand->Fix.setConversionChecker(TryCopyInitialization); 11406 11407 // Attempt to fix the bad conversion. 11408 unsigned ConvCount = Cand->Conversions.size(); 11409 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11410 ++ConvIdx) { 11411 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11412 if (Cand->Conversions[ConvIdx].isInitialized() && 11413 Cand->Conversions[ConvIdx].isBad()) { 11414 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11415 break; 11416 } 11417 } 11418 11419 // FIXME: this should probably be preserved from the overload 11420 // operation somehow. 11421 bool SuppressUserConversions = false; 11422 11423 unsigned ConvIdx = 0; 11424 unsigned ArgIdx = 0; 11425 ArrayRef<QualType> ParamTypes; 11426 bool Reversed = Cand->isReversed(); 11427 11428 if (Cand->IsSurrogate) { 11429 QualType ConvType 11430 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11431 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11432 ConvType = ConvPtrType->getPointeeType(); 11433 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11434 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11435 ConvIdx = 1; 11436 } else if (Cand->Function) { 11437 ParamTypes = 11438 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11439 if (isa<CXXMethodDecl>(Cand->Function) && 11440 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11441 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11442 ConvIdx = 1; 11443 if (CSK == OverloadCandidateSet::CSK_Operator && 11444 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11445 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11446 ArgIdx = 1; 11447 } 11448 } else { 11449 // Builtin operator. 11450 assert(ConvCount <= 3); 11451 ParamTypes = Cand->BuiltinParamTypes; 11452 } 11453 11454 // Fill in the rest of the conversions. 11455 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11456 ConvIdx != ConvCount; 11457 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11458 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11459 if (Cand->Conversions[ConvIdx].isInitialized()) { 11460 // We've already checked this conversion. 11461 } else if (ParamIdx < ParamTypes.size()) { 11462 if (ParamTypes[ParamIdx]->isDependentType()) 11463 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11464 Args[ArgIdx]->getType()); 11465 else { 11466 Cand->Conversions[ConvIdx] = 11467 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11468 SuppressUserConversions, 11469 /*InOverloadResolution=*/true, 11470 /*AllowObjCWritebackConversion=*/ 11471 S.getLangOpts().ObjCAutoRefCount); 11472 // Store the FixIt in the candidate if it exists. 11473 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11474 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11475 } 11476 } else 11477 Cand->Conversions[ConvIdx].setEllipsis(); 11478 } 11479 } 11480 11481 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11482 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11483 SourceLocation OpLoc, 11484 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11485 // Sort the candidates by viability and position. Sorting directly would 11486 // be prohibitive, so we make a set of pointers and sort those. 11487 SmallVector<OverloadCandidate*, 32> Cands; 11488 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11489 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11490 if (!Filter(*Cand)) 11491 continue; 11492 switch (OCD) { 11493 case OCD_AllCandidates: 11494 if (!Cand->Viable) { 11495 if (!Cand->Function && !Cand->IsSurrogate) { 11496 // This a non-viable builtin candidate. We do not, in general, 11497 // want to list every possible builtin candidate. 11498 continue; 11499 } 11500 CompleteNonViableCandidate(S, Cand, Args, Kind); 11501 } 11502 break; 11503 11504 case OCD_ViableCandidates: 11505 if (!Cand->Viable) 11506 continue; 11507 break; 11508 11509 case OCD_AmbiguousCandidates: 11510 if (!Cand->Best) 11511 continue; 11512 break; 11513 } 11514 11515 Cands.push_back(Cand); 11516 } 11517 11518 llvm::stable_sort( 11519 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11520 11521 return Cands; 11522 } 11523 11524 /// When overload resolution fails, prints diagnostic messages containing the 11525 /// candidates in the candidate set. 11526 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11527 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11528 StringRef Opc, SourceLocation OpLoc, 11529 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11530 11531 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11532 11533 S.Diag(PD.first, PD.second); 11534 11535 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11536 11537 if (OCD == OCD_AmbiguousCandidates) 11538 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11539 } 11540 11541 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11542 ArrayRef<OverloadCandidate *> Cands, 11543 StringRef Opc, SourceLocation OpLoc) { 11544 bool ReportedAmbiguousConversions = false; 11545 11546 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11547 unsigned CandsShown = 0; 11548 auto I = Cands.begin(), E = Cands.end(); 11549 for (; I != E; ++I) { 11550 OverloadCandidate *Cand = *I; 11551 11552 // Set an arbitrary limit on the number of candidate functions we'll spam 11553 // the user with. FIXME: This limit should depend on details of the 11554 // candidate list. 11555 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11556 break; 11557 } 11558 ++CandsShown; 11559 11560 if (Cand->Function) 11561 NoteFunctionCandidate(S, Cand, Args.size(), 11562 /*TakingCandidateAddress=*/false, DestAS); 11563 else if (Cand->IsSurrogate) 11564 NoteSurrogateCandidate(S, Cand); 11565 else { 11566 assert(Cand->Viable && 11567 "Non-viable built-in candidates are not added to Cands."); 11568 // Generally we only see ambiguities including viable builtin 11569 // operators if overload resolution got screwed up by an 11570 // ambiguous user-defined conversion. 11571 // 11572 // FIXME: It's quite possible for different conversions to see 11573 // different ambiguities, though. 11574 if (!ReportedAmbiguousConversions) { 11575 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11576 ReportedAmbiguousConversions = true; 11577 } 11578 11579 // If this is a viable builtin, print it. 11580 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11581 } 11582 } 11583 11584 if (I != E) 11585 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11586 } 11587 11588 static SourceLocation 11589 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11590 return Cand->Specialization ? Cand->Specialization->getLocation() 11591 : SourceLocation(); 11592 } 11593 11594 namespace { 11595 struct CompareTemplateSpecCandidatesForDisplay { 11596 Sema &S; 11597 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11598 11599 bool operator()(const TemplateSpecCandidate *L, 11600 const TemplateSpecCandidate *R) { 11601 // Fast-path this check. 11602 if (L == R) 11603 return false; 11604 11605 // Assuming that both candidates are not matches... 11606 11607 // Sort by the ranking of deduction failures. 11608 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11609 return RankDeductionFailure(L->DeductionFailure) < 11610 RankDeductionFailure(R->DeductionFailure); 11611 11612 // Sort everything else by location. 11613 SourceLocation LLoc = GetLocationForCandidate(L); 11614 SourceLocation RLoc = GetLocationForCandidate(R); 11615 11616 // Put candidates without locations (e.g. builtins) at the end. 11617 if (LLoc.isInvalid()) 11618 return false; 11619 if (RLoc.isInvalid()) 11620 return true; 11621 11622 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11623 } 11624 }; 11625 } 11626 11627 /// Diagnose a template argument deduction failure. 11628 /// We are treating these failures as overload failures due to bad 11629 /// deductions. 11630 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11631 bool ForTakingAddress) { 11632 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11633 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11634 } 11635 11636 void TemplateSpecCandidateSet::destroyCandidates() { 11637 for (iterator i = begin(), e = end(); i != e; ++i) { 11638 i->DeductionFailure.Destroy(); 11639 } 11640 } 11641 11642 void TemplateSpecCandidateSet::clear() { 11643 destroyCandidates(); 11644 Candidates.clear(); 11645 } 11646 11647 /// NoteCandidates - When no template specialization match is found, prints 11648 /// diagnostic messages containing the non-matching specializations that form 11649 /// the candidate set. 11650 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11651 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11652 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11653 // Sort the candidates by position (assuming no candidate is a match). 11654 // Sorting directly would be prohibitive, so we make a set of pointers 11655 // and sort those. 11656 SmallVector<TemplateSpecCandidate *, 32> Cands; 11657 Cands.reserve(size()); 11658 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11659 if (Cand->Specialization) 11660 Cands.push_back(Cand); 11661 // Otherwise, this is a non-matching builtin candidate. We do not, 11662 // in general, want to list every possible builtin candidate. 11663 } 11664 11665 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11666 11667 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11668 // for generalization purposes (?). 11669 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11670 11671 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11672 unsigned CandsShown = 0; 11673 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11674 TemplateSpecCandidate *Cand = *I; 11675 11676 // Set an arbitrary limit on the number of candidates we'll spam 11677 // the user with. FIXME: This limit should depend on details of the 11678 // candidate list. 11679 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11680 break; 11681 ++CandsShown; 11682 11683 assert(Cand->Specialization && 11684 "Non-matching built-in candidates are not added to Cands."); 11685 Cand->NoteDeductionFailure(S, ForTakingAddress); 11686 } 11687 11688 if (I != E) 11689 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11690 } 11691 11692 // [PossiblyAFunctionType] --> [Return] 11693 // NonFunctionType --> NonFunctionType 11694 // R (A) --> R(A) 11695 // R (*)(A) --> R (A) 11696 // R (&)(A) --> R (A) 11697 // R (S::*)(A) --> R (A) 11698 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11699 QualType Ret = PossiblyAFunctionType; 11700 if (const PointerType *ToTypePtr = 11701 PossiblyAFunctionType->getAs<PointerType>()) 11702 Ret = ToTypePtr->getPointeeType(); 11703 else if (const ReferenceType *ToTypeRef = 11704 PossiblyAFunctionType->getAs<ReferenceType>()) 11705 Ret = ToTypeRef->getPointeeType(); 11706 else if (const MemberPointerType *MemTypePtr = 11707 PossiblyAFunctionType->getAs<MemberPointerType>()) 11708 Ret = MemTypePtr->getPointeeType(); 11709 Ret = 11710 Context.getCanonicalType(Ret).getUnqualifiedType(); 11711 return Ret; 11712 } 11713 11714 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11715 bool Complain = true) { 11716 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11717 S.DeduceReturnType(FD, Loc, Complain)) 11718 return true; 11719 11720 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11721 if (S.getLangOpts().CPlusPlus17 && 11722 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11723 !S.ResolveExceptionSpec(Loc, FPT)) 11724 return true; 11725 11726 return false; 11727 } 11728 11729 namespace { 11730 // A helper class to help with address of function resolution 11731 // - allows us to avoid passing around all those ugly parameters 11732 class AddressOfFunctionResolver { 11733 Sema& S; 11734 Expr* SourceExpr; 11735 const QualType& TargetType; 11736 QualType TargetFunctionType; // Extracted function type from target type 11737 11738 bool Complain; 11739 //DeclAccessPair& ResultFunctionAccessPair; 11740 ASTContext& Context; 11741 11742 bool TargetTypeIsNonStaticMemberFunction; 11743 bool FoundNonTemplateFunction; 11744 bool StaticMemberFunctionFromBoundPointer; 11745 bool HasComplained; 11746 11747 OverloadExpr::FindResult OvlExprInfo; 11748 OverloadExpr *OvlExpr; 11749 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11750 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11751 TemplateSpecCandidateSet FailedCandidates; 11752 11753 public: 11754 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11755 const QualType &TargetType, bool Complain) 11756 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11757 Complain(Complain), Context(S.getASTContext()), 11758 TargetTypeIsNonStaticMemberFunction( 11759 !!TargetType->getAs<MemberPointerType>()), 11760 FoundNonTemplateFunction(false), 11761 StaticMemberFunctionFromBoundPointer(false), 11762 HasComplained(false), 11763 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11764 OvlExpr(OvlExprInfo.Expression), 11765 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11766 ExtractUnqualifiedFunctionTypeFromTargetType(); 11767 11768 if (TargetFunctionType->isFunctionType()) { 11769 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11770 if (!UME->isImplicitAccess() && 11771 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11772 StaticMemberFunctionFromBoundPointer = true; 11773 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11774 DeclAccessPair dap; 11775 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11776 OvlExpr, false, &dap)) { 11777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11778 if (!Method->isStatic()) { 11779 // If the target type is a non-function type and the function found 11780 // is a non-static member function, pretend as if that was the 11781 // target, it's the only possible type to end up with. 11782 TargetTypeIsNonStaticMemberFunction = true; 11783 11784 // And skip adding the function if its not in the proper form. 11785 // We'll diagnose this due to an empty set of functions. 11786 if (!OvlExprInfo.HasFormOfMemberPointer) 11787 return; 11788 } 11789 11790 Matches.push_back(std::make_pair(dap, Fn)); 11791 } 11792 return; 11793 } 11794 11795 if (OvlExpr->hasExplicitTemplateArgs()) 11796 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11797 11798 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11799 // C++ [over.over]p4: 11800 // If more than one function is selected, [...] 11801 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11802 if (FoundNonTemplateFunction) 11803 EliminateAllTemplateMatches(); 11804 else 11805 EliminateAllExceptMostSpecializedTemplate(); 11806 } 11807 } 11808 11809 if (S.getLangOpts().CUDA && Matches.size() > 1) 11810 EliminateSuboptimalCudaMatches(); 11811 } 11812 11813 bool hasComplained() const { return HasComplained; } 11814 11815 private: 11816 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11817 QualType Discard; 11818 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11819 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11820 } 11821 11822 /// \return true if A is considered a better overload candidate for the 11823 /// desired type than B. 11824 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11825 // If A doesn't have exactly the correct type, we don't want to classify it 11826 // as "better" than anything else. This way, the user is required to 11827 // disambiguate for us if there are multiple candidates and no exact match. 11828 return candidateHasExactlyCorrectType(A) && 11829 (!candidateHasExactlyCorrectType(B) || 11830 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11831 } 11832 11833 /// \return true if we were able to eliminate all but one overload candidate, 11834 /// false otherwise. 11835 bool eliminiateSuboptimalOverloadCandidates() { 11836 // Same algorithm as overload resolution -- one pass to pick the "best", 11837 // another pass to be sure that nothing is better than the best. 11838 auto Best = Matches.begin(); 11839 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11840 if (isBetterCandidate(I->second, Best->second)) 11841 Best = I; 11842 11843 const FunctionDecl *BestFn = Best->second; 11844 auto IsBestOrInferiorToBest = [this, BestFn]( 11845 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11846 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11847 }; 11848 11849 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11850 // option, so we can potentially give the user a better error 11851 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11852 return false; 11853 Matches[0] = *Best; 11854 Matches.resize(1); 11855 return true; 11856 } 11857 11858 bool isTargetTypeAFunction() const { 11859 return TargetFunctionType->isFunctionType(); 11860 } 11861 11862 // [ToType] [Return] 11863 11864 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11865 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11866 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11867 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11868 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11869 } 11870 11871 // return true if any matching specializations were found 11872 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11873 const DeclAccessPair& CurAccessFunPair) { 11874 if (CXXMethodDecl *Method 11875 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11876 // Skip non-static function templates when converting to pointer, and 11877 // static when converting to member pointer. 11878 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11879 return false; 11880 } 11881 else if (TargetTypeIsNonStaticMemberFunction) 11882 return false; 11883 11884 // C++ [over.over]p2: 11885 // If the name is a function template, template argument deduction is 11886 // done (14.8.2.2), and if the argument deduction succeeds, the 11887 // resulting template argument list is used to generate a single 11888 // function template specialization, which is added to the set of 11889 // overloaded functions considered. 11890 FunctionDecl *Specialization = nullptr; 11891 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11892 if (Sema::TemplateDeductionResult Result 11893 = S.DeduceTemplateArguments(FunctionTemplate, 11894 &OvlExplicitTemplateArgs, 11895 TargetFunctionType, Specialization, 11896 Info, /*IsAddressOfFunction*/true)) { 11897 // Make a note of the failed deduction for diagnostics. 11898 FailedCandidates.addCandidate() 11899 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11900 MakeDeductionFailureInfo(Context, Result, Info)); 11901 return false; 11902 } 11903 11904 // Template argument deduction ensures that we have an exact match or 11905 // compatible pointer-to-function arguments that would be adjusted by ICS. 11906 // This function template specicalization works. 11907 assert(S.isSameOrCompatibleFunctionType( 11908 Context.getCanonicalType(Specialization->getType()), 11909 Context.getCanonicalType(TargetFunctionType))); 11910 11911 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11912 return false; 11913 11914 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11915 return true; 11916 } 11917 11918 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11919 const DeclAccessPair& CurAccessFunPair) { 11920 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11921 // Skip non-static functions when converting to pointer, and static 11922 // when converting to member pointer. 11923 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11924 return false; 11925 } 11926 else if (TargetTypeIsNonStaticMemberFunction) 11927 return false; 11928 11929 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11930 if (S.getLangOpts().CUDA) 11931 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11932 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11933 return false; 11934 if (FunDecl->isMultiVersion()) { 11935 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11936 if (TA && !TA->isDefaultVersion()) 11937 return false; 11938 } 11939 11940 // If any candidate has a placeholder return type, trigger its deduction 11941 // now. 11942 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11943 Complain)) { 11944 HasComplained |= Complain; 11945 return false; 11946 } 11947 11948 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11949 return false; 11950 11951 // If we're in C, we need to support types that aren't exactly identical. 11952 if (!S.getLangOpts().CPlusPlus || 11953 candidateHasExactlyCorrectType(FunDecl)) { 11954 Matches.push_back(std::make_pair( 11955 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11956 FoundNonTemplateFunction = true; 11957 return true; 11958 } 11959 } 11960 11961 return false; 11962 } 11963 11964 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11965 bool Ret = false; 11966 11967 // If the overload expression doesn't have the form of a pointer to 11968 // member, don't try to convert it to a pointer-to-member type. 11969 if (IsInvalidFormOfPointerToMemberFunction()) 11970 return false; 11971 11972 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11973 E = OvlExpr->decls_end(); 11974 I != E; ++I) { 11975 // Look through any using declarations to find the underlying function. 11976 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11977 11978 // C++ [over.over]p3: 11979 // Non-member functions and static member functions match 11980 // targets of type "pointer-to-function" or "reference-to-function." 11981 // Nonstatic member functions match targets of 11982 // type "pointer-to-member-function." 11983 // Note that according to DR 247, the containing class does not matter. 11984 if (FunctionTemplateDecl *FunctionTemplate 11985 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11986 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11987 Ret = true; 11988 } 11989 // If we have explicit template arguments supplied, skip non-templates. 11990 else if (!OvlExpr->hasExplicitTemplateArgs() && 11991 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11992 Ret = true; 11993 } 11994 assert(Ret || Matches.empty()); 11995 return Ret; 11996 } 11997 11998 void EliminateAllExceptMostSpecializedTemplate() { 11999 // [...] and any given function template specialization F1 is 12000 // eliminated if the set contains a second function template 12001 // specialization whose function template is more specialized 12002 // than the function template of F1 according to the partial 12003 // ordering rules of 14.5.5.2. 12004 12005 // The algorithm specified above is quadratic. We instead use a 12006 // two-pass algorithm (similar to the one used to identify the 12007 // best viable function in an overload set) that identifies the 12008 // best function template (if it exists). 12009 12010 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12011 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12012 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12013 12014 // TODO: It looks like FailedCandidates does not serve much purpose 12015 // here, since the no_viable diagnostic has index 0. 12016 UnresolvedSetIterator Result = S.getMostSpecialized( 12017 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12018 SourceExpr->getBeginLoc(), S.PDiag(), 12019 S.PDiag(diag::err_addr_ovl_ambiguous) 12020 << Matches[0].second->getDeclName(), 12021 S.PDiag(diag::note_ovl_candidate) 12022 << (unsigned)oc_function << (unsigned)ocs_described_template, 12023 Complain, TargetFunctionType); 12024 12025 if (Result != MatchesCopy.end()) { 12026 // Make it the first and only element 12027 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12028 Matches[0].second = cast<FunctionDecl>(*Result); 12029 Matches.resize(1); 12030 } else 12031 HasComplained |= Complain; 12032 } 12033 12034 void EliminateAllTemplateMatches() { 12035 // [...] any function template specializations in the set are 12036 // eliminated if the set also contains a non-template function, [...] 12037 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12038 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12039 ++I; 12040 else { 12041 Matches[I] = Matches[--N]; 12042 Matches.resize(N); 12043 } 12044 } 12045 } 12046 12047 void EliminateSuboptimalCudaMatches() { 12048 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12049 } 12050 12051 public: 12052 void ComplainNoMatchesFound() const { 12053 assert(Matches.empty()); 12054 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12055 << OvlExpr->getName() << TargetFunctionType 12056 << OvlExpr->getSourceRange(); 12057 if (FailedCandidates.empty()) 12058 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12059 /*TakingAddress=*/true); 12060 else { 12061 // We have some deduction failure messages. Use them to diagnose 12062 // the function templates, and diagnose the non-template candidates 12063 // normally. 12064 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12065 IEnd = OvlExpr->decls_end(); 12066 I != IEnd; ++I) 12067 if (FunctionDecl *Fun = 12068 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12069 if (!functionHasPassObjectSizeParams(Fun)) 12070 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12071 /*TakingAddress=*/true); 12072 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12073 } 12074 } 12075 12076 bool IsInvalidFormOfPointerToMemberFunction() const { 12077 return TargetTypeIsNonStaticMemberFunction && 12078 !OvlExprInfo.HasFormOfMemberPointer; 12079 } 12080 12081 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12082 // TODO: Should we condition this on whether any functions might 12083 // have matched, or is it more appropriate to do that in callers? 12084 // TODO: a fixit wouldn't hurt. 12085 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12086 << TargetType << OvlExpr->getSourceRange(); 12087 } 12088 12089 bool IsStaticMemberFunctionFromBoundPointer() const { 12090 return StaticMemberFunctionFromBoundPointer; 12091 } 12092 12093 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12094 S.Diag(OvlExpr->getBeginLoc(), 12095 diag::err_invalid_form_pointer_member_function) 12096 << OvlExpr->getSourceRange(); 12097 } 12098 12099 void ComplainOfInvalidConversion() const { 12100 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12101 << OvlExpr->getName() << TargetType; 12102 } 12103 12104 void ComplainMultipleMatchesFound() const { 12105 assert(Matches.size() > 1); 12106 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12107 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12108 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12109 /*TakingAddress=*/true); 12110 } 12111 12112 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12113 12114 int getNumMatches() const { return Matches.size(); } 12115 12116 FunctionDecl* getMatchingFunctionDecl() const { 12117 if (Matches.size() != 1) return nullptr; 12118 return Matches[0].second; 12119 } 12120 12121 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12122 if (Matches.size() != 1) return nullptr; 12123 return &Matches[0].first; 12124 } 12125 }; 12126 } 12127 12128 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12129 /// an overloaded function (C++ [over.over]), where @p From is an 12130 /// expression with overloaded function type and @p ToType is the type 12131 /// we're trying to resolve to. For example: 12132 /// 12133 /// @code 12134 /// int f(double); 12135 /// int f(int); 12136 /// 12137 /// int (*pfd)(double) = f; // selects f(double) 12138 /// @endcode 12139 /// 12140 /// This routine returns the resulting FunctionDecl if it could be 12141 /// resolved, and NULL otherwise. When @p Complain is true, this 12142 /// routine will emit diagnostics if there is an error. 12143 FunctionDecl * 12144 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12145 QualType TargetType, 12146 bool Complain, 12147 DeclAccessPair &FoundResult, 12148 bool *pHadMultipleCandidates) { 12149 assert(AddressOfExpr->getType() == Context.OverloadTy); 12150 12151 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12152 Complain); 12153 int NumMatches = Resolver.getNumMatches(); 12154 FunctionDecl *Fn = nullptr; 12155 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12156 if (NumMatches == 0 && ShouldComplain) { 12157 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12158 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12159 else 12160 Resolver.ComplainNoMatchesFound(); 12161 } 12162 else if (NumMatches > 1 && ShouldComplain) 12163 Resolver.ComplainMultipleMatchesFound(); 12164 else if (NumMatches == 1) { 12165 Fn = Resolver.getMatchingFunctionDecl(); 12166 assert(Fn); 12167 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12168 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12169 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12170 if (Complain) { 12171 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12172 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12173 else 12174 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12175 } 12176 } 12177 12178 if (pHadMultipleCandidates) 12179 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12180 return Fn; 12181 } 12182 12183 /// Given an expression that refers to an overloaded function, try to 12184 /// resolve that function to a single function that can have its address taken. 12185 /// This will modify `Pair` iff it returns non-null. 12186 /// 12187 /// This routine can only succeed if from all of the candidates in the overload 12188 /// set for SrcExpr that can have their addresses taken, there is one candidate 12189 /// that is more constrained than the rest. 12190 FunctionDecl * 12191 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12192 OverloadExpr::FindResult R = OverloadExpr::find(E); 12193 OverloadExpr *Ovl = R.Expression; 12194 bool IsResultAmbiguous = false; 12195 FunctionDecl *Result = nullptr; 12196 DeclAccessPair DAP; 12197 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12198 12199 auto CheckMoreConstrained = 12200 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12201 SmallVector<const Expr *, 1> AC1, AC2; 12202 FD1->getAssociatedConstraints(AC1); 12203 FD2->getAssociatedConstraints(AC2); 12204 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12205 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12206 return None; 12207 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12208 return None; 12209 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12210 return None; 12211 return AtLeastAsConstrained1; 12212 }; 12213 12214 // Don't use the AddressOfResolver because we're specifically looking for 12215 // cases where we have one overload candidate that lacks 12216 // enable_if/pass_object_size/... 12217 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12218 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12219 if (!FD) 12220 return nullptr; 12221 12222 if (!checkAddressOfFunctionIsAvailable(FD)) 12223 continue; 12224 12225 // We have more than one result - see if it is more constrained than the 12226 // previous one. 12227 if (Result) { 12228 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12229 Result); 12230 if (!MoreConstrainedThanPrevious) { 12231 IsResultAmbiguous = true; 12232 AmbiguousDecls.push_back(FD); 12233 continue; 12234 } 12235 if (!*MoreConstrainedThanPrevious) 12236 continue; 12237 // FD is more constrained - replace Result with it. 12238 } 12239 IsResultAmbiguous = false; 12240 DAP = I.getPair(); 12241 Result = FD; 12242 } 12243 12244 if (IsResultAmbiguous) 12245 return nullptr; 12246 12247 if (Result) { 12248 SmallVector<const Expr *, 1> ResultAC; 12249 // We skipped over some ambiguous declarations which might be ambiguous with 12250 // the selected result. 12251 for (FunctionDecl *Skipped : AmbiguousDecls) 12252 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12253 return nullptr; 12254 Pair = DAP; 12255 } 12256 return Result; 12257 } 12258 12259 /// Given an overloaded function, tries to turn it into a non-overloaded 12260 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12261 /// will perform access checks, diagnose the use of the resultant decl, and, if 12262 /// requested, potentially perform a function-to-pointer decay. 12263 /// 12264 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12265 /// Otherwise, returns true. This may emit diagnostics and return true. 12266 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12267 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12268 Expr *E = SrcExpr.get(); 12269 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12270 12271 DeclAccessPair DAP; 12272 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12273 if (!Found || Found->isCPUDispatchMultiVersion() || 12274 Found->isCPUSpecificMultiVersion()) 12275 return false; 12276 12277 // Emitting multiple diagnostics for a function that is both inaccessible and 12278 // unavailable is consistent with our behavior elsewhere. So, always check 12279 // for both. 12280 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12281 CheckAddressOfMemberAccess(E, DAP); 12282 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12283 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12284 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12285 else 12286 SrcExpr = Fixed; 12287 return true; 12288 } 12289 12290 /// Given an expression that refers to an overloaded function, try to 12291 /// resolve that overloaded function expression down to a single function. 12292 /// 12293 /// This routine can only resolve template-ids that refer to a single function 12294 /// template, where that template-id refers to a single template whose template 12295 /// arguments are either provided by the template-id or have defaults, 12296 /// as described in C++0x [temp.arg.explicit]p3. 12297 /// 12298 /// If no template-ids are found, no diagnostics are emitted and NULL is 12299 /// returned. 12300 FunctionDecl * 12301 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12302 bool Complain, 12303 DeclAccessPair *FoundResult) { 12304 // C++ [over.over]p1: 12305 // [...] [Note: any redundant set of parentheses surrounding the 12306 // overloaded function name is ignored (5.1). ] 12307 // C++ [over.over]p1: 12308 // [...] The overloaded function name can be preceded by the & 12309 // operator. 12310 12311 // If we didn't actually find any template-ids, we're done. 12312 if (!ovl->hasExplicitTemplateArgs()) 12313 return nullptr; 12314 12315 TemplateArgumentListInfo ExplicitTemplateArgs; 12316 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12317 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12318 12319 // Look through all of the overloaded functions, searching for one 12320 // whose type matches exactly. 12321 FunctionDecl *Matched = nullptr; 12322 for (UnresolvedSetIterator I = ovl->decls_begin(), 12323 E = ovl->decls_end(); I != E; ++I) { 12324 // C++0x [temp.arg.explicit]p3: 12325 // [...] In contexts where deduction is done and fails, or in contexts 12326 // where deduction is not done, if a template argument list is 12327 // specified and it, along with any default template arguments, 12328 // identifies a single function template specialization, then the 12329 // template-id is an lvalue for the function template specialization. 12330 FunctionTemplateDecl *FunctionTemplate 12331 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12332 12333 // C++ [over.over]p2: 12334 // If the name is a function template, template argument deduction is 12335 // done (14.8.2.2), and if the argument deduction succeeds, the 12336 // resulting template argument list is used to generate a single 12337 // function template specialization, which is added to the set of 12338 // overloaded functions considered. 12339 FunctionDecl *Specialization = nullptr; 12340 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12341 if (TemplateDeductionResult Result 12342 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12343 Specialization, Info, 12344 /*IsAddressOfFunction*/true)) { 12345 // Make a note of the failed deduction for diagnostics. 12346 // TODO: Actually use the failed-deduction info? 12347 FailedCandidates.addCandidate() 12348 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12349 MakeDeductionFailureInfo(Context, Result, Info)); 12350 continue; 12351 } 12352 12353 assert(Specialization && "no specialization and no error?"); 12354 12355 // Multiple matches; we can't resolve to a single declaration. 12356 if (Matched) { 12357 if (Complain) { 12358 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12359 << ovl->getName(); 12360 NoteAllOverloadCandidates(ovl); 12361 } 12362 return nullptr; 12363 } 12364 12365 Matched = Specialization; 12366 if (FoundResult) *FoundResult = I.getPair(); 12367 } 12368 12369 if (Matched && 12370 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12371 return nullptr; 12372 12373 return Matched; 12374 } 12375 12376 // Resolve and fix an overloaded expression that can be resolved 12377 // because it identifies a single function template specialization. 12378 // 12379 // Last three arguments should only be supplied if Complain = true 12380 // 12381 // Return true if it was logically possible to so resolve the 12382 // expression, regardless of whether or not it succeeded. Always 12383 // returns true if 'complain' is set. 12384 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12385 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12386 bool complain, SourceRange OpRangeForComplaining, 12387 QualType DestTypeForComplaining, 12388 unsigned DiagIDForComplaining) { 12389 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12390 12391 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12392 12393 DeclAccessPair found; 12394 ExprResult SingleFunctionExpression; 12395 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12396 ovl.Expression, /*complain*/ false, &found)) { 12397 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12398 SrcExpr = ExprError(); 12399 return true; 12400 } 12401 12402 // It is only correct to resolve to an instance method if we're 12403 // resolving a form that's permitted to be a pointer to member. 12404 // Otherwise we'll end up making a bound member expression, which 12405 // is illegal in all the contexts we resolve like this. 12406 if (!ovl.HasFormOfMemberPointer && 12407 isa<CXXMethodDecl>(fn) && 12408 cast<CXXMethodDecl>(fn)->isInstance()) { 12409 if (!complain) return false; 12410 12411 Diag(ovl.Expression->getExprLoc(), 12412 diag::err_bound_member_function) 12413 << 0 << ovl.Expression->getSourceRange(); 12414 12415 // TODO: I believe we only end up here if there's a mix of 12416 // static and non-static candidates (otherwise the expression 12417 // would have 'bound member' type, not 'overload' type). 12418 // Ideally we would note which candidate was chosen and why 12419 // the static candidates were rejected. 12420 SrcExpr = ExprError(); 12421 return true; 12422 } 12423 12424 // Fix the expression to refer to 'fn'. 12425 SingleFunctionExpression = 12426 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12427 12428 // If desired, do function-to-pointer decay. 12429 if (doFunctionPointerConverion) { 12430 SingleFunctionExpression = 12431 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12432 if (SingleFunctionExpression.isInvalid()) { 12433 SrcExpr = ExprError(); 12434 return true; 12435 } 12436 } 12437 } 12438 12439 if (!SingleFunctionExpression.isUsable()) { 12440 if (complain) { 12441 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12442 << ovl.Expression->getName() 12443 << DestTypeForComplaining 12444 << OpRangeForComplaining 12445 << ovl.Expression->getQualifierLoc().getSourceRange(); 12446 NoteAllOverloadCandidates(SrcExpr.get()); 12447 12448 SrcExpr = ExprError(); 12449 return true; 12450 } 12451 12452 return false; 12453 } 12454 12455 SrcExpr = SingleFunctionExpression; 12456 return true; 12457 } 12458 12459 /// Add a single candidate to the overload set. 12460 static void AddOverloadedCallCandidate(Sema &S, 12461 DeclAccessPair FoundDecl, 12462 TemplateArgumentListInfo *ExplicitTemplateArgs, 12463 ArrayRef<Expr *> Args, 12464 OverloadCandidateSet &CandidateSet, 12465 bool PartialOverloading, 12466 bool KnownValid) { 12467 NamedDecl *Callee = FoundDecl.getDecl(); 12468 if (isa<UsingShadowDecl>(Callee)) 12469 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12470 12471 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12472 if (ExplicitTemplateArgs) { 12473 assert(!KnownValid && "Explicit template arguments?"); 12474 return; 12475 } 12476 // Prevent ill-formed function decls to be added as overload candidates. 12477 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12478 return; 12479 12480 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12481 /*SuppressUserConversions=*/false, 12482 PartialOverloading); 12483 return; 12484 } 12485 12486 if (FunctionTemplateDecl *FuncTemplate 12487 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12488 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12489 ExplicitTemplateArgs, Args, CandidateSet, 12490 /*SuppressUserConversions=*/false, 12491 PartialOverloading); 12492 return; 12493 } 12494 12495 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12496 } 12497 12498 /// Add the overload candidates named by callee and/or found by argument 12499 /// dependent lookup to the given overload set. 12500 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12501 ArrayRef<Expr *> Args, 12502 OverloadCandidateSet &CandidateSet, 12503 bool PartialOverloading) { 12504 12505 #ifndef NDEBUG 12506 // Verify that ArgumentDependentLookup is consistent with the rules 12507 // in C++0x [basic.lookup.argdep]p3: 12508 // 12509 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12510 // and let Y be the lookup set produced by argument dependent 12511 // lookup (defined as follows). If X contains 12512 // 12513 // -- a declaration of a class member, or 12514 // 12515 // -- a block-scope function declaration that is not a 12516 // using-declaration, or 12517 // 12518 // -- a declaration that is neither a function or a function 12519 // template 12520 // 12521 // then Y is empty. 12522 12523 if (ULE->requiresADL()) { 12524 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12525 E = ULE->decls_end(); I != E; ++I) { 12526 assert(!(*I)->getDeclContext()->isRecord()); 12527 assert(isa<UsingShadowDecl>(*I) || 12528 !(*I)->getDeclContext()->isFunctionOrMethod()); 12529 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12530 } 12531 } 12532 #endif 12533 12534 // It would be nice to avoid this copy. 12535 TemplateArgumentListInfo TABuffer; 12536 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12537 if (ULE->hasExplicitTemplateArgs()) { 12538 ULE->copyTemplateArgumentsInto(TABuffer); 12539 ExplicitTemplateArgs = &TABuffer; 12540 } 12541 12542 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12543 E = ULE->decls_end(); I != E; ++I) 12544 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12545 CandidateSet, PartialOverloading, 12546 /*KnownValid*/ true); 12547 12548 if (ULE->requiresADL()) 12549 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12550 Args, ExplicitTemplateArgs, 12551 CandidateSet, PartialOverloading); 12552 } 12553 12554 /// Determine whether a declaration with the specified name could be moved into 12555 /// a different namespace. 12556 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12557 switch (Name.getCXXOverloadedOperator()) { 12558 case OO_New: case OO_Array_New: 12559 case OO_Delete: case OO_Array_Delete: 12560 return false; 12561 12562 default: 12563 return true; 12564 } 12565 } 12566 12567 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12568 /// template, where the non-dependent name was declared after the template 12569 /// was defined. This is common in code written for a compilers which do not 12570 /// correctly implement two-stage name lookup. 12571 /// 12572 /// Returns true if a viable candidate was found and a diagnostic was issued. 12573 static bool 12574 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12575 const CXXScopeSpec &SS, LookupResult &R, 12576 OverloadCandidateSet::CandidateSetKind CSK, 12577 TemplateArgumentListInfo *ExplicitTemplateArgs, 12578 ArrayRef<Expr *> Args, 12579 bool *DoDiagnoseEmptyLookup = nullptr) { 12580 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12581 return false; 12582 12583 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12584 if (DC->isTransparentContext()) 12585 continue; 12586 12587 SemaRef.LookupQualifiedName(R, DC); 12588 12589 if (!R.empty()) { 12590 R.suppressDiagnostics(); 12591 12592 if (isa<CXXRecordDecl>(DC)) { 12593 // Don't diagnose names we find in classes; we get much better 12594 // diagnostics for these from DiagnoseEmptyLookup. 12595 R.clear(); 12596 if (DoDiagnoseEmptyLookup) 12597 *DoDiagnoseEmptyLookup = true; 12598 return false; 12599 } 12600 12601 OverloadCandidateSet Candidates(FnLoc, CSK); 12602 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12603 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12604 ExplicitTemplateArgs, Args, 12605 Candidates, false, /*KnownValid*/ false); 12606 12607 OverloadCandidateSet::iterator Best; 12608 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12609 // No viable functions. Don't bother the user with notes for functions 12610 // which don't work and shouldn't be found anyway. 12611 R.clear(); 12612 return false; 12613 } 12614 12615 // Find the namespaces where ADL would have looked, and suggest 12616 // declaring the function there instead. 12617 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12618 Sema::AssociatedClassSet AssociatedClasses; 12619 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12620 AssociatedNamespaces, 12621 AssociatedClasses); 12622 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12623 if (canBeDeclaredInNamespace(R.getLookupName())) { 12624 DeclContext *Std = SemaRef.getStdNamespace(); 12625 for (Sema::AssociatedNamespaceSet::iterator 12626 it = AssociatedNamespaces.begin(), 12627 end = AssociatedNamespaces.end(); it != end; ++it) { 12628 // Never suggest declaring a function within namespace 'std'. 12629 if (Std && Std->Encloses(*it)) 12630 continue; 12631 12632 // Never suggest declaring a function within a namespace with a 12633 // reserved name, like __gnu_cxx. 12634 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12635 if (NS && 12636 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12637 continue; 12638 12639 SuggestedNamespaces.insert(*it); 12640 } 12641 } 12642 12643 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12644 << R.getLookupName(); 12645 if (SuggestedNamespaces.empty()) { 12646 SemaRef.Diag(Best->Function->getLocation(), 12647 diag::note_not_found_by_two_phase_lookup) 12648 << R.getLookupName() << 0; 12649 } else if (SuggestedNamespaces.size() == 1) { 12650 SemaRef.Diag(Best->Function->getLocation(), 12651 diag::note_not_found_by_two_phase_lookup) 12652 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12653 } else { 12654 // FIXME: It would be useful to list the associated namespaces here, 12655 // but the diagnostics infrastructure doesn't provide a way to produce 12656 // a localized representation of a list of items. 12657 SemaRef.Diag(Best->Function->getLocation(), 12658 diag::note_not_found_by_two_phase_lookup) 12659 << R.getLookupName() << 2; 12660 } 12661 12662 // Try to recover by calling this function. 12663 return true; 12664 } 12665 12666 R.clear(); 12667 } 12668 12669 return false; 12670 } 12671 12672 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12673 /// template, where the non-dependent operator was declared after the template 12674 /// was defined. 12675 /// 12676 /// Returns true if a viable candidate was found and a diagnostic was issued. 12677 static bool 12678 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12679 SourceLocation OpLoc, 12680 ArrayRef<Expr *> Args) { 12681 DeclarationName OpName = 12682 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12683 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12684 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12685 OverloadCandidateSet::CSK_Operator, 12686 /*ExplicitTemplateArgs=*/nullptr, Args); 12687 } 12688 12689 namespace { 12690 class BuildRecoveryCallExprRAII { 12691 Sema &SemaRef; 12692 public: 12693 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12694 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12695 SemaRef.IsBuildingRecoveryCallExpr = true; 12696 } 12697 12698 ~BuildRecoveryCallExprRAII() { 12699 SemaRef.IsBuildingRecoveryCallExpr = false; 12700 } 12701 }; 12702 12703 } 12704 12705 /// Attempts to recover from a call where no functions were found. 12706 /// 12707 /// Returns true if new candidates were found. 12708 static ExprResult 12709 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12710 UnresolvedLookupExpr *ULE, 12711 SourceLocation LParenLoc, 12712 MutableArrayRef<Expr *> Args, 12713 SourceLocation RParenLoc, 12714 bool EmptyLookup, bool AllowTypoCorrection) { 12715 // Do not try to recover if it is already building a recovery call. 12716 // This stops infinite loops for template instantiations like 12717 // 12718 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12719 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12720 // 12721 if (SemaRef.IsBuildingRecoveryCallExpr) 12722 return ExprError(); 12723 BuildRecoveryCallExprRAII RCE(SemaRef); 12724 12725 CXXScopeSpec SS; 12726 SS.Adopt(ULE->getQualifierLoc()); 12727 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12728 12729 TemplateArgumentListInfo TABuffer; 12730 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12731 if (ULE->hasExplicitTemplateArgs()) { 12732 ULE->copyTemplateArgumentsInto(TABuffer); 12733 ExplicitTemplateArgs = &TABuffer; 12734 } 12735 12736 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12737 Sema::LookupOrdinaryName); 12738 bool DoDiagnoseEmptyLookup = EmptyLookup; 12739 if (!DiagnoseTwoPhaseLookup( 12740 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12741 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12742 NoTypoCorrectionCCC NoTypoValidator{}; 12743 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12744 ExplicitTemplateArgs != nullptr, 12745 dyn_cast<MemberExpr>(Fn)); 12746 CorrectionCandidateCallback &Validator = 12747 AllowTypoCorrection 12748 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12749 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12750 if (!DoDiagnoseEmptyLookup || 12751 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12752 Args)) 12753 return ExprError(); 12754 } 12755 12756 assert(!R.empty() && "lookup results empty despite recovery"); 12757 12758 // If recovery created an ambiguity, just bail out. 12759 if (R.isAmbiguous()) { 12760 R.suppressDiagnostics(); 12761 return ExprError(); 12762 } 12763 12764 // Build an implicit member call if appropriate. Just drop the 12765 // casts and such from the call, we don't really care. 12766 ExprResult NewFn = ExprError(); 12767 if ((*R.begin())->isCXXClassMember()) 12768 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12769 ExplicitTemplateArgs, S); 12770 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12771 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12772 ExplicitTemplateArgs); 12773 else 12774 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12775 12776 if (NewFn.isInvalid()) 12777 return ExprError(); 12778 12779 // This shouldn't cause an infinite loop because we're giving it 12780 // an expression with viable lookup results, which should never 12781 // end up here. 12782 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12783 MultiExprArg(Args.data(), Args.size()), 12784 RParenLoc); 12785 } 12786 12787 /// Constructs and populates an OverloadedCandidateSet from 12788 /// the given function. 12789 /// \returns true when an the ExprResult output parameter has been set. 12790 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12791 UnresolvedLookupExpr *ULE, 12792 MultiExprArg Args, 12793 SourceLocation RParenLoc, 12794 OverloadCandidateSet *CandidateSet, 12795 ExprResult *Result) { 12796 #ifndef NDEBUG 12797 if (ULE->requiresADL()) { 12798 // To do ADL, we must have found an unqualified name. 12799 assert(!ULE->getQualifier() && "qualified name with ADL"); 12800 12801 // We don't perform ADL for implicit declarations of builtins. 12802 // Verify that this was correctly set up. 12803 FunctionDecl *F; 12804 if (ULE->decls_begin() != ULE->decls_end() && 12805 ULE->decls_begin() + 1 == ULE->decls_end() && 12806 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12807 F->getBuiltinID() && F->isImplicit()) 12808 llvm_unreachable("performing ADL for builtin"); 12809 12810 // We don't perform ADL in C. 12811 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12812 } 12813 #endif 12814 12815 UnbridgedCastsSet UnbridgedCasts; 12816 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12817 *Result = ExprError(); 12818 return true; 12819 } 12820 12821 // Add the functions denoted by the callee to the set of candidate 12822 // functions, including those from argument-dependent lookup. 12823 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12824 12825 if (getLangOpts().MSVCCompat && 12826 CurContext->isDependentContext() && !isSFINAEContext() && 12827 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12828 12829 OverloadCandidateSet::iterator Best; 12830 if (CandidateSet->empty() || 12831 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12832 OR_No_Viable_Function) { 12833 // In Microsoft mode, if we are inside a template class member function 12834 // then create a type dependent CallExpr. The goal is to postpone name 12835 // lookup to instantiation time to be able to search into type dependent 12836 // base classes. 12837 CallExpr *CE = 12838 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue, 12839 RParenLoc, CurFPFeatureOverrides()); 12840 CE->markDependentForPostponedNameLookup(); 12841 *Result = CE; 12842 return true; 12843 } 12844 } 12845 12846 if (CandidateSet->empty()) 12847 return false; 12848 12849 UnbridgedCasts.restore(); 12850 return false; 12851 } 12852 12853 // Guess at what the return type for an unresolvable overload should be. 12854 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12855 OverloadCandidateSet::iterator *Best) { 12856 llvm::Optional<QualType> Result; 12857 // Adjust Type after seeing a candidate. 12858 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12859 if (!Candidate.Function) 12860 return; 12861 if (Candidate.Function->isInvalidDecl()) 12862 return; 12863 QualType T = Candidate.Function->getReturnType(); 12864 if (T.isNull()) 12865 return; 12866 if (!Result) 12867 Result = T; 12868 else if (Result != T) 12869 Result = QualType(); 12870 }; 12871 12872 // Look for an unambiguous type from a progressively larger subset. 12873 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12874 // 12875 // First, consider only the best candidate. 12876 if (Best && *Best != CS.end()) 12877 ConsiderCandidate(**Best); 12878 // Next, consider only viable candidates. 12879 if (!Result) 12880 for (const auto &C : CS) 12881 if (C.Viable) 12882 ConsiderCandidate(C); 12883 // Finally, consider all candidates. 12884 if (!Result) 12885 for (const auto &C : CS) 12886 ConsiderCandidate(C); 12887 12888 return Result.getValueOr(QualType()); 12889 } 12890 12891 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12892 /// the completed call expression. If overload resolution fails, emits 12893 /// diagnostics and returns ExprError() 12894 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12895 UnresolvedLookupExpr *ULE, 12896 SourceLocation LParenLoc, 12897 MultiExprArg Args, 12898 SourceLocation RParenLoc, 12899 Expr *ExecConfig, 12900 OverloadCandidateSet *CandidateSet, 12901 OverloadCandidateSet::iterator *Best, 12902 OverloadingResult OverloadResult, 12903 bool AllowTypoCorrection) { 12904 if (CandidateSet->empty()) 12905 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12906 RParenLoc, /*EmptyLookup=*/true, 12907 AllowTypoCorrection); 12908 12909 switch (OverloadResult) { 12910 case OR_Success: { 12911 FunctionDecl *FDecl = (*Best)->Function; 12912 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12913 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12914 return ExprError(); 12915 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12916 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12917 ExecConfig, /*IsExecConfig=*/false, 12918 (*Best)->IsADLCandidate); 12919 } 12920 12921 case OR_No_Viable_Function: { 12922 // Try to recover by looking for viable functions which the user might 12923 // have meant to call. 12924 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12925 Args, RParenLoc, 12926 /*EmptyLookup=*/false, 12927 AllowTypoCorrection); 12928 if (!Recovery.isInvalid()) 12929 return Recovery; 12930 12931 // If the user passes in a function that we can't take the address of, we 12932 // generally end up emitting really bad error messages. Here, we attempt to 12933 // emit better ones. 12934 for (const Expr *Arg : Args) { 12935 if (!Arg->getType()->isFunctionType()) 12936 continue; 12937 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12938 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12939 if (FD && 12940 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12941 Arg->getExprLoc())) 12942 return ExprError(); 12943 } 12944 } 12945 12946 CandidateSet->NoteCandidates( 12947 PartialDiagnosticAt( 12948 Fn->getBeginLoc(), 12949 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12950 << ULE->getName() << Fn->getSourceRange()), 12951 SemaRef, OCD_AllCandidates, Args); 12952 break; 12953 } 12954 12955 case OR_Ambiguous: 12956 CandidateSet->NoteCandidates( 12957 PartialDiagnosticAt(Fn->getBeginLoc(), 12958 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12959 << ULE->getName() << Fn->getSourceRange()), 12960 SemaRef, OCD_AmbiguousCandidates, Args); 12961 break; 12962 12963 case OR_Deleted: { 12964 CandidateSet->NoteCandidates( 12965 PartialDiagnosticAt(Fn->getBeginLoc(), 12966 SemaRef.PDiag(diag::err_ovl_deleted_call) 12967 << ULE->getName() << Fn->getSourceRange()), 12968 SemaRef, OCD_AllCandidates, Args); 12969 12970 // We emitted an error for the unavailable/deleted function call but keep 12971 // the call in the AST. 12972 FunctionDecl *FDecl = (*Best)->Function; 12973 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12974 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12975 ExecConfig, /*IsExecConfig=*/false, 12976 (*Best)->IsADLCandidate); 12977 } 12978 } 12979 12980 // Overload resolution failed, try to recover. 12981 SmallVector<Expr *, 8> SubExprs = {Fn}; 12982 SubExprs.append(Args.begin(), Args.end()); 12983 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 12984 chooseRecoveryType(*CandidateSet, Best)); 12985 } 12986 12987 static void markUnaddressableCandidatesUnviable(Sema &S, 12988 OverloadCandidateSet &CS) { 12989 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12990 if (I->Viable && 12991 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12992 I->Viable = false; 12993 I->FailureKind = ovl_fail_addr_not_available; 12994 } 12995 } 12996 } 12997 12998 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12999 /// (which eventually refers to the declaration Func) and the call 13000 /// arguments Args/NumArgs, attempt to resolve the function call down 13001 /// to a specific function. If overload resolution succeeds, returns 13002 /// the call expression produced by overload resolution. 13003 /// Otherwise, emits diagnostics and returns ExprError. 13004 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13005 UnresolvedLookupExpr *ULE, 13006 SourceLocation LParenLoc, 13007 MultiExprArg Args, 13008 SourceLocation RParenLoc, 13009 Expr *ExecConfig, 13010 bool AllowTypoCorrection, 13011 bool CalleesAddressIsTaken) { 13012 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13013 OverloadCandidateSet::CSK_Normal); 13014 ExprResult result; 13015 13016 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13017 &result)) 13018 return result; 13019 13020 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13021 // functions that aren't addressible are considered unviable. 13022 if (CalleesAddressIsTaken) 13023 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13024 13025 OverloadCandidateSet::iterator Best; 13026 OverloadingResult OverloadResult = 13027 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13028 13029 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13030 ExecConfig, &CandidateSet, &Best, 13031 OverloadResult, AllowTypoCorrection); 13032 } 13033 13034 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13035 return Functions.size() > 1 || 13036 (Functions.size() == 1 && 13037 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13038 } 13039 13040 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13041 NestedNameSpecifierLoc NNSLoc, 13042 DeclarationNameInfo DNI, 13043 const UnresolvedSetImpl &Fns, 13044 bool PerformADL) { 13045 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13046 PerformADL, IsOverloaded(Fns), 13047 Fns.begin(), Fns.end()); 13048 } 13049 13050 /// Create a unary operation that may resolve to an overloaded 13051 /// operator. 13052 /// 13053 /// \param OpLoc The location of the operator itself (e.g., '*'). 13054 /// 13055 /// \param Opc The UnaryOperatorKind that describes this operator. 13056 /// 13057 /// \param Fns The set of non-member functions that will be 13058 /// considered by overload resolution. The caller needs to build this 13059 /// set based on the context using, e.g., 13060 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13061 /// set should not contain any member functions; those will be added 13062 /// by CreateOverloadedUnaryOp(). 13063 /// 13064 /// \param Input The input argument. 13065 ExprResult 13066 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13067 const UnresolvedSetImpl &Fns, 13068 Expr *Input, bool PerformADL) { 13069 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13070 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13071 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13072 // TODO: provide better source location info. 13073 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13074 13075 if (checkPlaceholderForOverload(*this, Input)) 13076 return ExprError(); 13077 13078 Expr *Args[2] = { Input, nullptr }; 13079 unsigned NumArgs = 1; 13080 13081 // For post-increment and post-decrement, add the implicit '0' as 13082 // the second argument, so that we know this is a post-increment or 13083 // post-decrement. 13084 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13085 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13086 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13087 SourceLocation()); 13088 NumArgs = 2; 13089 } 13090 13091 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13092 13093 if (Input->isTypeDependent()) { 13094 if (Fns.empty()) 13095 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13096 VK_RValue, OK_Ordinary, OpLoc, false, 13097 CurFPFeatureOverrides()); 13098 13099 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13100 ExprResult Fn = CreateUnresolvedLookupExpr( 13101 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13102 if (Fn.isInvalid()) 13103 return ExprError(); 13104 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13105 Context.DependentTy, VK_RValue, OpLoc, 13106 CurFPFeatureOverrides()); 13107 } 13108 13109 // Build an empty overload set. 13110 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13111 13112 // Add the candidates from the given function set. 13113 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13114 13115 // Add operator candidates that are member functions. 13116 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13117 13118 // Add candidates from ADL. 13119 if (PerformADL) { 13120 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13121 /*ExplicitTemplateArgs*/nullptr, 13122 CandidateSet); 13123 } 13124 13125 // Add builtin operator candidates. 13126 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13127 13128 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13129 13130 // Perform overload resolution. 13131 OverloadCandidateSet::iterator Best; 13132 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13133 case OR_Success: { 13134 // We found a built-in operator or an overloaded operator. 13135 FunctionDecl *FnDecl = Best->Function; 13136 13137 if (FnDecl) { 13138 Expr *Base = nullptr; 13139 // We matched an overloaded operator. Build a call to that 13140 // operator. 13141 13142 // Convert the arguments. 13143 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13144 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13145 13146 ExprResult InputRes = 13147 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13148 Best->FoundDecl, Method); 13149 if (InputRes.isInvalid()) 13150 return ExprError(); 13151 Base = Input = InputRes.get(); 13152 } else { 13153 // Convert the arguments. 13154 ExprResult InputInit 13155 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13156 Context, 13157 FnDecl->getParamDecl(0)), 13158 SourceLocation(), 13159 Input); 13160 if (InputInit.isInvalid()) 13161 return ExprError(); 13162 Input = InputInit.get(); 13163 } 13164 13165 // Build the actual expression node. 13166 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13167 Base, HadMultipleCandidates, 13168 OpLoc); 13169 if (FnExpr.isInvalid()) 13170 return ExprError(); 13171 13172 // Determine the result type. 13173 QualType ResultTy = FnDecl->getReturnType(); 13174 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13175 ResultTy = ResultTy.getNonLValueExprType(Context); 13176 13177 Args[0] = Input; 13178 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13179 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13180 CurFPFeatureOverrides(), Best->IsADLCandidate); 13181 13182 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13183 return ExprError(); 13184 13185 if (CheckFunctionCall(FnDecl, TheCall, 13186 FnDecl->getType()->castAs<FunctionProtoType>())) 13187 return ExprError(); 13188 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13189 } else { 13190 // We matched a built-in operator. Convert the arguments, then 13191 // break out so that we will build the appropriate built-in 13192 // operator node. 13193 ExprResult InputRes = PerformImplicitConversion( 13194 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13195 CCK_ForBuiltinOverloadedOp); 13196 if (InputRes.isInvalid()) 13197 return ExprError(); 13198 Input = InputRes.get(); 13199 break; 13200 } 13201 } 13202 13203 case OR_No_Viable_Function: 13204 // This is an erroneous use of an operator which can be overloaded by 13205 // a non-member function. Check for non-member operators which were 13206 // defined too late to be candidates. 13207 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13208 // FIXME: Recover by calling the found function. 13209 return ExprError(); 13210 13211 // No viable function; fall through to handling this as a 13212 // built-in operator, which will produce an error message for us. 13213 break; 13214 13215 case OR_Ambiguous: 13216 CandidateSet.NoteCandidates( 13217 PartialDiagnosticAt(OpLoc, 13218 PDiag(diag::err_ovl_ambiguous_oper_unary) 13219 << UnaryOperator::getOpcodeStr(Opc) 13220 << Input->getType() << Input->getSourceRange()), 13221 *this, OCD_AmbiguousCandidates, ArgsArray, 13222 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13223 return ExprError(); 13224 13225 case OR_Deleted: 13226 CandidateSet.NoteCandidates( 13227 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13228 << UnaryOperator::getOpcodeStr(Opc) 13229 << Input->getSourceRange()), 13230 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13231 OpLoc); 13232 return ExprError(); 13233 } 13234 13235 // Either we found no viable overloaded operator or we matched a 13236 // built-in operator. In either case, fall through to trying to 13237 // build a built-in operation. 13238 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13239 } 13240 13241 /// Perform lookup for an overloaded binary operator. 13242 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13243 OverloadedOperatorKind Op, 13244 const UnresolvedSetImpl &Fns, 13245 ArrayRef<Expr *> Args, bool PerformADL) { 13246 SourceLocation OpLoc = CandidateSet.getLocation(); 13247 13248 OverloadedOperatorKind ExtraOp = 13249 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13250 ? getRewrittenOverloadedOperator(Op) 13251 : OO_None; 13252 13253 // Add the candidates from the given function set. This also adds the 13254 // rewritten candidates using these functions if necessary. 13255 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13256 13257 // Add operator candidates that are member functions. 13258 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13259 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13260 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13261 OverloadCandidateParamOrder::Reversed); 13262 13263 // In C++20, also add any rewritten member candidates. 13264 if (ExtraOp) { 13265 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13266 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13267 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13268 CandidateSet, 13269 OverloadCandidateParamOrder::Reversed); 13270 } 13271 13272 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13273 // performed for an assignment operator (nor for operator[] nor operator->, 13274 // which don't get here). 13275 if (Op != OO_Equal && PerformADL) { 13276 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13277 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13278 /*ExplicitTemplateArgs*/ nullptr, 13279 CandidateSet); 13280 if (ExtraOp) { 13281 DeclarationName ExtraOpName = 13282 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13283 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13284 /*ExplicitTemplateArgs*/ nullptr, 13285 CandidateSet); 13286 } 13287 } 13288 13289 // Add builtin operator candidates. 13290 // 13291 // FIXME: We don't add any rewritten candidates here. This is strictly 13292 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13293 // resulting in our selecting a rewritten builtin candidate. For example: 13294 // 13295 // enum class E { e }; 13296 // bool operator!=(E, E) requires false; 13297 // bool k = E::e != E::e; 13298 // 13299 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13300 // it seems unreasonable to consider rewritten builtin candidates. A core 13301 // issue has been filed proposing to removed this requirement. 13302 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13303 } 13304 13305 /// Create a binary operation that may resolve to an overloaded 13306 /// operator. 13307 /// 13308 /// \param OpLoc The location of the operator itself (e.g., '+'). 13309 /// 13310 /// \param Opc The BinaryOperatorKind that describes this operator. 13311 /// 13312 /// \param Fns The set of non-member functions that will be 13313 /// considered by overload resolution. The caller needs to build this 13314 /// set based on the context using, e.g., 13315 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13316 /// set should not contain any member functions; those will be added 13317 /// by CreateOverloadedBinOp(). 13318 /// 13319 /// \param LHS Left-hand argument. 13320 /// \param RHS Right-hand argument. 13321 /// \param PerformADL Whether to consider operator candidates found by ADL. 13322 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13323 /// C++20 operator rewrites. 13324 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13325 /// the function in question. Such a function is never a candidate in 13326 /// our overload resolution. This also enables synthesizing a three-way 13327 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13328 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13329 BinaryOperatorKind Opc, 13330 const UnresolvedSetImpl &Fns, Expr *LHS, 13331 Expr *RHS, bool PerformADL, 13332 bool AllowRewrittenCandidates, 13333 FunctionDecl *DefaultedFn) { 13334 Expr *Args[2] = { LHS, RHS }; 13335 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13336 13337 if (!getLangOpts().CPlusPlus20) 13338 AllowRewrittenCandidates = false; 13339 13340 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13341 13342 // If either side is type-dependent, create an appropriate dependent 13343 // expression. 13344 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13345 if (Fns.empty()) { 13346 // If there are no functions to store, just build a dependent 13347 // BinaryOperator or CompoundAssignment. 13348 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13349 return BinaryOperator::Create( 13350 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, 13351 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13352 return CompoundAssignOperator::Create( 13353 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13354 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13355 Context.DependentTy); 13356 } 13357 13358 // FIXME: save results of ADL from here? 13359 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13360 // TODO: provide better source location info in DNLoc component. 13361 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13362 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13363 ExprResult Fn = CreateUnresolvedLookupExpr( 13364 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13365 if (Fn.isInvalid()) 13366 return ExprError(); 13367 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13368 Context.DependentTy, VK_RValue, OpLoc, 13369 CurFPFeatureOverrides()); 13370 } 13371 13372 // Always do placeholder-like conversions on the RHS. 13373 if (checkPlaceholderForOverload(*this, Args[1])) 13374 return ExprError(); 13375 13376 // Do placeholder-like conversion on the LHS; note that we should 13377 // not get here with a PseudoObject LHS. 13378 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13379 if (checkPlaceholderForOverload(*this, Args[0])) 13380 return ExprError(); 13381 13382 // If this is the assignment operator, we only perform overload resolution 13383 // if the left-hand side is a class or enumeration type. This is actually 13384 // a hack. The standard requires that we do overload resolution between the 13385 // various built-in candidates, but as DR507 points out, this can lead to 13386 // problems. So we do it this way, which pretty much follows what GCC does. 13387 // Note that we go the traditional code path for compound assignment forms. 13388 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13389 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13390 13391 // If this is the .* operator, which is not overloadable, just 13392 // create a built-in binary operator. 13393 if (Opc == BO_PtrMemD) 13394 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13395 13396 // Build the overload set. 13397 OverloadCandidateSet CandidateSet( 13398 OpLoc, OverloadCandidateSet::CSK_Operator, 13399 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13400 if (DefaultedFn) 13401 CandidateSet.exclude(DefaultedFn); 13402 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13403 13404 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13405 13406 // Perform overload resolution. 13407 OverloadCandidateSet::iterator Best; 13408 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13409 case OR_Success: { 13410 // We found a built-in operator or an overloaded operator. 13411 FunctionDecl *FnDecl = Best->Function; 13412 13413 bool IsReversed = Best->isReversed(); 13414 if (IsReversed) 13415 std::swap(Args[0], Args[1]); 13416 13417 if (FnDecl) { 13418 Expr *Base = nullptr; 13419 // We matched an overloaded operator. Build a call to that 13420 // operator. 13421 13422 OverloadedOperatorKind ChosenOp = 13423 FnDecl->getDeclName().getCXXOverloadedOperator(); 13424 13425 // C++2a [over.match.oper]p9: 13426 // If a rewritten operator== candidate is selected by overload 13427 // resolution for an operator@, its return type shall be cv bool 13428 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13429 !FnDecl->getReturnType()->isBooleanType()) { 13430 bool IsExtension = 13431 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13432 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13433 : diag::err_ovl_rewrite_equalequal_not_bool) 13434 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13435 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13436 Diag(FnDecl->getLocation(), diag::note_declared_at); 13437 if (!IsExtension) 13438 return ExprError(); 13439 } 13440 13441 if (AllowRewrittenCandidates && !IsReversed && 13442 CandidateSet.getRewriteInfo().isReversible()) { 13443 // We could have reversed this operator, but didn't. Check if some 13444 // reversed form was a viable candidate, and if so, if it had a 13445 // better conversion for either parameter. If so, this call is 13446 // formally ambiguous, and allowing it is an extension. 13447 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13448 for (OverloadCandidate &Cand : CandidateSet) { 13449 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13450 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13451 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13452 if (CompareImplicitConversionSequences( 13453 *this, OpLoc, Cand.Conversions[ArgIdx], 13454 Best->Conversions[ArgIdx]) == 13455 ImplicitConversionSequence::Better) { 13456 AmbiguousWith.push_back(Cand.Function); 13457 break; 13458 } 13459 } 13460 } 13461 } 13462 13463 if (!AmbiguousWith.empty()) { 13464 bool AmbiguousWithSelf = 13465 AmbiguousWith.size() == 1 && 13466 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13467 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13468 << BinaryOperator::getOpcodeStr(Opc) 13469 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13470 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13471 if (AmbiguousWithSelf) { 13472 Diag(FnDecl->getLocation(), 13473 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13474 } else { 13475 Diag(FnDecl->getLocation(), 13476 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13477 for (auto *F : AmbiguousWith) 13478 Diag(F->getLocation(), 13479 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13480 } 13481 } 13482 } 13483 13484 // Convert the arguments. 13485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13486 // Best->Access is only meaningful for class members. 13487 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13488 13489 ExprResult Arg1 = 13490 PerformCopyInitialization( 13491 InitializedEntity::InitializeParameter(Context, 13492 FnDecl->getParamDecl(0)), 13493 SourceLocation(), Args[1]); 13494 if (Arg1.isInvalid()) 13495 return ExprError(); 13496 13497 ExprResult Arg0 = 13498 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13499 Best->FoundDecl, Method); 13500 if (Arg0.isInvalid()) 13501 return ExprError(); 13502 Base = Args[0] = Arg0.getAs<Expr>(); 13503 Args[1] = RHS = Arg1.getAs<Expr>(); 13504 } else { 13505 // Convert the arguments. 13506 ExprResult Arg0 = PerformCopyInitialization( 13507 InitializedEntity::InitializeParameter(Context, 13508 FnDecl->getParamDecl(0)), 13509 SourceLocation(), Args[0]); 13510 if (Arg0.isInvalid()) 13511 return ExprError(); 13512 13513 ExprResult Arg1 = 13514 PerformCopyInitialization( 13515 InitializedEntity::InitializeParameter(Context, 13516 FnDecl->getParamDecl(1)), 13517 SourceLocation(), Args[1]); 13518 if (Arg1.isInvalid()) 13519 return ExprError(); 13520 Args[0] = LHS = Arg0.getAs<Expr>(); 13521 Args[1] = RHS = Arg1.getAs<Expr>(); 13522 } 13523 13524 // Build the actual expression node. 13525 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13526 Best->FoundDecl, Base, 13527 HadMultipleCandidates, OpLoc); 13528 if (FnExpr.isInvalid()) 13529 return ExprError(); 13530 13531 // Determine the result type. 13532 QualType ResultTy = FnDecl->getReturnType(); 13533 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13534 ResultTy = ResultTy.getNonLValueExprType(Context); 13535 13536 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13537 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13538 CurFPFeatureOverrides(), Best->IsADLCandidate); 13539 13540 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13541 FnDecl)) 13542 return ExprError(); 13543 13544 ArrayRef<const Expr *> ArgsArray(Args, 2); 13545 const Expr *ImplicitThis = nullptr; 13546 // Cut off the implicit 'this'. 13547 if (isa<CXXMethodDecl>(FnDecl)) { 13548 ImplicitThis = ArgsArray[0]; 13549 ArgsArray = ArgsArray.slice(1); 13550 } 13551 13552 // Check for a self move. 13553 if (Op == OO_Equal) 13554 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13555 13556 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13557 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13558 VariadicDoesNotApply); 13559 13560 ExprResult R = MaybeBindToTemporary(TheCall); 13561 if (R.isInvalid()) 13562 return ExprError(); 13563 13564 R = CheckForImmediateInvocation(R, FnDecl); 13565 if (R.isInvalid()) 13566 return ExprError(); 13567 13568 // For a rewritten candidate, we've already reversed the arguments 13569 // if needed. Perform the rest of the rewrite now. 13570 if ((Best->RewriteKind & CRK_DifferentOperator) || 13571 (Op == OO_Spaceship && IsReversed)) { 13572 if (Op == OO_ExclaimEqual) { 13573 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13574 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13575 } else { 13576 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13577 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13578 Expr *ZeroLiteral = 13579 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13580 13581 Sema::CodeSynthesisContext Ctx; 13582 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13583 Ctx.Entity = FnDecl; 13584 pushCodeSynthesisContext(Ctx); 13585 13586 R = CreateOverloadedBinOp( 13587 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13588 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13589 /*AllowRewrittenCandidates=*/false); 13590 13591 popCodeSynthesisContext(); 13592 } 13593 if (R.isInvalid()) 13594 return ExprError(); 13595 } else { 13596 assert(ChosenOp == Op && "unexpected operator name"); 13597 } 13598 13599 // Make a note in the AST if we did any rewriting. 13600 if (Best->RewriteKind != CRK_None) 13601 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13602 13603 return R; 13604 } else { 13605 // We matched a built-in operator. Convert the arguments, then 13606 // break out so that we will build the appropriate built-in 13607 // operator node. 13608 ExprResult ArgsRes0 = PerformImplicitConversion( 13609 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13610 AA_Passing, CCK_ForBuiltinOverloadedOp); 13611 if (ArgsRes0.isInvalid()) 13612 return ExprError(); 13613 Args[0] = ArgsRes0.get(); 13614 13615 ExprResult ArgsRes1 = PerformImplicitConversion( 13616 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13617 AA_Passing, CCK_ForBuiltinOverloadedOp); 13618 if (ArgsRes1.isInvalid()) 13619 return ExprError(); 13620 Args[1] = ArgsRes1.get(); 13621 break; 13622 } 13623 } 13624 13625 case OR_No_Viable_Function: { 13626 // C++ [over.match.oper]p9: 13627 // If the operator is the operator , [...] and there are no 13628 // viable functions, then the operator is assumed to be the 13629 // built-in operator and interpreted according to clause 5. 13630 if (Opc == BO_Comma) 13631 break; 13632 13633 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13634 // compare result using '==' and '<'. 13635 if (DefaultedFn && Opc == BO_Cmp) { 13636 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13637 Args[1], DefaultedFn); 13638 if (E.isInvalid() || E.isUsable()) 13639 return E; 13640 } 13641 13642 // For class as left operand for assignment or compound assignment 13643 // operator do not fall through to handling in built-in, but report that 13644 // no overloaded assignment operator found 13645 ExprResult Result = ExprError(); 13646 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13647 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13648 Args, OpLoc); 13649 if (Args[0]->getType()->isRecordType() && 13650 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13651 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13652 << BinaryOperator::getOpcodeStr(Opc) 13653 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13654 if (Args[0]->getType()->isIncompleteType()) { 13655 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13656 << Args[0]->getType() 13657 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13658 } 13659 } else { 13660 // This is an erroneous use of an operator which can be overloaded by 13661 // a non-member function. Check for non-member operators which were 13662 // defined too late to be candidates. 13663 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13664 // FIXME: Recover by calling the found function. 13665 return ExprError(); 13666 13667 // No viable function; try to create a built-in operation, which will 13668 // produce an error. Then, show the non-viable candidates. 13669 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13670 } 13671 assert(Result.isInvalid() && 13672 "C++ binary operator overloading is missing candidates!"); 13673 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13674 return Result; 13675 } 13676 13677 case OR_Ambiguous: 13678 CandidateSet.NoteCandidates( 13679 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13680 << BinaryOperator::getOpcodeStr(Opc) 13681 << Args[0]->getType() 13682 << Args[1]->getType() 13683 << Args[0]->getSourceRange() 13684 << Args[1]->getSourceRange()), 13685 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13686 OpLoc); 13687 return ExprError(); 13688 13689 case OR_Deleted: 13690 if (isImplicitlyDeleted(Best->Function)) { 13691 FunctionDecl *DeletedFD = Best->Function; 13692 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13693 if (DFK.isSpecialMember()) { 13694 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13695 << Args[0]->getType() << DFK.asSpecialMember(); 13696 } else { 13697 assert(DFK.isComparison()); 13698 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13699 << Args[0]->getType() << DeletedFD; 13700 } 13701 13702 // The user probably meant to call this special member. Just 13703 // explain why it's deleted. 13704 NoteDeletedFunction(DeletedFD); 13705 return ExprError(); 13706 } 13707 CandidateSet.NoteCandidates( 13708 PartialDiagnosticAt( 13709 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13710 << getOperatorSpelling(Best->Function->getDeclName() 13711 .getCXXOverloadedOperator()) 13712 << Args[0]->getSourceRange() 13713 << Args[1]->getSourceRange()), 13714 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13715 OpLoc); 13716 return ExprError(); 13717 } 13718 13719 // We matched a built-in operator; build it. 13720 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13721 } 13722 13723 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13724 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13725 FunctionDecl *DefaultedFn) { 13726 const ComparisonCategoryInfo *Info = 13727 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13728 // If we're not producing a known comparison category type, we can't 13729 // synthesize a three-way comparison. Let the caller diagnose this. 13730 if (!Info) 13731 return ExprResult((Expr*)nullptr); 13732 13733 // If we ever want to perform this synthesis more generally, we will need to 13734 // apply the temporary materialization conversion to the operands. 13735 assert(LHS->isGLValue() && RHS->isGLValue() && 13736 "cannot use prvalue expressions more than once"); 13737 Expr *OrigLHS = LHS; 13738 Expr *OrigRHS = RHS; 13739 13740 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13741 // each of them multiple times below. 13742 LHS = new (Context) 13743 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13744 LHS->getObjectKind(), LHS); 13745 RHS = new (Context) 13746 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13747 RHS->getObjectKind(), RHS); 13748 13749 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13750 DefaultedFn); 13751 if (Eq.isInvalid()) 13752 return ExprError(); 13753 13754 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13755 true, DefaultedFn); 13756 if (Less.isInvalid()) 13757 return ExprError(); 13758 13759 ExprResult Greater; 13760 if (Info->isPartial()) { 13761 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13762 DefaultedFn); 13763 if (Greater.isInvalid()) 13764 return ExprError(); 13765 } 13766 13767 // Form the list of comparisons we're going to perform. 13768 struct Comparison { 13769 ExprResult Cmp; 13770 ComparisonCategoryResult Result; 13771 } Comparisons[4] = 13772 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13773 : ComparisonCategoryResult::Equivalent}, 13774 {Less, ComparisonCategoryResult::Less}, 13775 {Greater, ComparisonCategoryResult::Greater}, 13776 {ExprResult(), ComparisonCategoryResult::Unordered}, 13777 }; 13778 13779 int I = Info->isPartial() ? 3 : 2; 13780 13781 // Combine the comparisons with suitable conditional expressions. 13782 ExprResult Result; 13783 for (; I >= 0; --I) { 13784 // Build a reference to the comparison category constant. 13785 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13786 // FIXME: Missing a constant for a comparison category. Diagnose this? 13787 if (!VI) 13788 return ExprResult((Expr*)nullptr); 13789 ExprResult ThisResult = 13790 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13791 if (ThisResult.isInvalid()) 13792 return ExprError(); 13793 13794 // Build a conditional unless this is the final case. 13795 if (Result.get()) { 13796 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13797 ThisResult.get(), Result.get()); 13798 if (Result.isInvalid()) 13799 return ExprError(); 13800 } else { 13801 Result = ThisResult; 13802 } 13803 } 13804 13805 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13806 // bind the OpaqueValueExprs before they're (repeatedly) used. 13807 Expr *SyntacticForm = BinaryOperator::Create( 13808 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13809 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13810 CurFPFeatureOverrides()); 13811 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13812 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13813 } 13814 13815 ExprResult 13816 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13817 SourceLocation RLoc, 13818 Expr *Base, Expr *Idx) { 13819 Expr *Args[2] = { Base, Idx }; 13820 DeclarationName OpName = 13821 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13822 13823 // If either side is type-dependent, create an appropriate dependent 13824 // expression. 13825 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13826 13827 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13828 // CHECKME: no 'operator' keyword? 13829 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13830 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13831 ExprResult Fn = CreateUnresolvedLookupExpr( 13832 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 13833 if (Fn.isInvalid()) 13834 return ExprError(); 13835 // Can't add any actual overloads yet 13836 13837 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 13838 Context.DependentTy, VK_RValue, RLoc, 13839 CurFPFeatureOverrides()); 13840 } 13841 13842 // Handle placeholders on both operands. 13843 if (checkPlaceholderForOverload(*this, Args[0])) 13844 return ExprError(); 13845 if (checkPlaceholderForOverload(*this, Args[1])) 13846 return ExprError(); 13847 13848 // Build an empty overload set. 13849 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13850 13851 // Subscript can only be overloaded as a member function. 13852 13853 // Add operator candidates that are member functions. 13854 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13855 13856 // Add builtin operator candidates. 13857 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13858 13859 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13860 13861 // Perform overload resolution. 13862 OverloadCandidateSet::iterator Best; 13863 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13864 case OR_Success: { 13865 // We found a built-in operator or an overloaded operator. 13866 FunctionDecl *FnDecl = Best->Function; 13867 13868 if (FnDecl) { 13869 // We matched an overloaded operator. Build a call to that 13870 // operator. 13871 13872 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13873 13874 // Convert the arguments. 13875 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13876 ExprResult Arg0 = 13877 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13878 Best->FoundDecl, Method); 13879 if (Arg0.isInvalid()) 13880 return ExprError(); 13881 Args[0] = Arg0.get(); 13882 13883 // Convert the arguments. 13884 ExprResult InputInit 13885 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13886 Context, 13887 FnDecl->getParamDecl(0)), 13888 SourceLocation(), 13889 Args[1]); 13890 if (InputInit.isInvalid()) 13891 return ExprError(); 13892 13893 Args[1] = InputInit.getAs<Expr>(); 13894 13895 // Build the actual expression node. 13896 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13897 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13898 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13899 Best->FoundDecl, 13900 Base, 13901 HadMultipleCandidates, 13902 OpLocInfo.getLoc(), 13903 OpLocInfo.getInfo()); 13904 if (FnExpr.isInvalid()) 13905 return ExprError(); 13906 13907 // Determine the result type 13908 QualType ResultTy = FnDecl->getReturnType(); 13909 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13910 ResultTy = ResultTy.getNonLValueExprType(Context); 13911 13912 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13913 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 13914 CurFPFeatureOverrides()); 13915 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13916 return ExprError(); 13917 13918 if (CheckFunctionCall(Method, TheCall, 13919 Method->getType()->castAs<FunctionProtoType>())) 13920 return ExprError(); 13921 13922 return MaybeBindToTemporary(TheCall); 13923 } else { 13924 // We matched a built-in operator. Convert the arguments, then 13925 // break out so that we will build the appropriate built-in 13926 // operator node. 13927 ExprResult ArgsRes0 = PerformImplicitConversion( 13928 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13929 AA_Passing, CCK_ForBuiltinOverloadedOp); 13930 if (ArgsRes0.isInvalid()) 13931 return ExprError(); 13932 Args[0] = ArgsRes0.get(); 13933 13934 ExprResult ArgsRes1 = PerformImplicitConversion( 13935 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13936 AA_Passing, CCK_ForBuiltinOverloadedOp); 13937 if (ArgsRes1.isInvalid()) 13938 return ExprError(); 13939 Args[1] = ArgsRes1.get(); 13940 13941 break; 13942 } 13943 } 13944 13945 case OR_No_Viable_Function: { 13946 PartialDiagnostic PD = CandidateSet.empty() 13947 ? (PDiag(diag::err_ovl_no_oper) 13948 << Args[0]->getType() << /*subscript*/ 0 13949 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13950 : (PDiag(diag::err_ovl_no_viable_subscript) 13951 << Args[0]->getType() << Args[0]->getSourceRange() 13952 << Args[1]->getSourceRange()); 13953 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13954 OCD_AllCandidates, Args, "[]", LLoc); 13955 return ExprError(); 13956 } 13957 13958 case OR_Ambiguous: 13959 CandidateSet.NoteCandidates( 13960 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13961 << "[]" << Args[0]->getType() 13962 << Args[1]->getType() 13963 << Args[0]->getSourceRange() 13964 << Args[1]->getSourceRange()), 13965 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13966 return ExprError(); 13967 13968 case OR_Deleted: 13969 CandidateSet.NoteCandidates( 13970 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13971 << "[]" << Args[0]->getSourceRange() 13972 << Args[1]->getSourceRange()), 13973 *this, OCD_AllCandidates, Args, "[]", LLoc); 13974 return ExprError(); 13975 } 13976 13977 // We matched a built-in operator; build it. 13978 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13979 } 13980 13981 /// BuildCallToMemberFunction - Build a call to a member 13982 /// function. MemExpr is the expression that refers to the member 13983 /// function (and includes the object parameter), Args/NumArgs are the 13984 /// arguments to the function call (not including the object 13985 /// parameter). The caller needs to validate that the member 13986 /// expression refers to a non-static member function or an overloaded 13987 /// member function. 13988 ExprResult 13989 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13990 SourceLocation LParenLoc, 13991 MultiExprArg Args, 13992 SourceLocation RParenLoc) { 13993 assert(MemExprE->getType() == Context.BoundMemberTy || 13994 MemExprE->getType() == Context.OverloadTy); 13995 13996 // Dig out the member expression. This holds both the object 13997 // argument and the member function we're referring to. 13998 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13999 14000 // Determine whether this is a call to a pointer-to-member function. 14001 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14002 assert(op->getType() == Context.BoundMemberTy); 14003 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14004 14005 QualType fnType = 14006 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14007 14008 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14009 QualType resultType = proto->getCallResultType(Context); 14010 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14011 14012 // Check that the object type isn't more qualified than the 14013 // member function we're calling. 14014 Qualifiers funcQuals = proto->getMethodQuals(); 14015 14016 QualType objectType = op->getLHS()->getType(); 14017 if (op->getOpcode() == BO_PtrMemI) 14018 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14019 Qualifiers objectQuals = objectType.getQualifiers(); 14020 14021 Qualifiers difference = objectQuals - funcQuals; 14022 difference.removeObjCGCAttr(); 14023 difference.removeAddressSpace(); 14024 if (difference) { 14025 std::string qualsString = difference.getAsString(); 14026 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14027 << fnType.getUnqualifiedType() 14028 << qualsString 14029 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14030 } 14031 14032 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14033 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14034 CurFPFeatureOverrides(), proto->getNumParams()); 14035 14036 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14037 call, nullptr)) 14038 return ExprError(); 14039 14040 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14041 return ExprError(); 14042 14043 if (CheckOtherCall(call, proto)) 14044 return ExprError(); 14045 14046 return MaybeBindToTemporary(call); 14047 } 14048 14049 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14050 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14051 RParenLoc, CurFPFeatureOverrides()); 14052 14053 UnbridgedCastsSet UnbridgedCasts; 14054 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14055 return ExprError(); 14056 14057 MemberExpr *MemExpr; 14058 CXXMethodDecl *Method = nullptr; 14059 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14060 NestedNameSpecifier *Qualifier = nullptr; 14061 if (isa<MemberExpr>(NakedMemExpr)) { 14062 MemExpr = cast<MemberExpr>(NakedMemExpr); 14063 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14064 FoundDecl = MemExpr->getFoundDecl(); 14065 Qualifier = MemExpr->getQualifier(); 14066 UnbridgedCasts.restore(); 14067 } else { 14068 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14069 Qualifier = UnresExpr->getQualifier(); 14070 14071 QualType ObjectType = UnresExpr->getBaseType(); 14072 Expr::Classification ObjectClassification 14073 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14074 : UnresExpr->getBase()->Classify(Context); 14075 14076 // Add overload candidates 14077 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14078 OverloadCandidateSet::CSK_Normal); 14079 14080 // FIXME: avoid copy. 14081 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14082 if (UnresExpr->hasExplicitTemplateArgs()) { 14083 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14084 TemplateArgs = &TemplateArgsBuffer; 14085 } 14086 14087 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14088 E = UnresExpr->decls_end(); I != E; ++I) { 14089 14090 NamedDecl *Func = *I; 14091 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14092 if (isa<UsingShadowDecl>(Func)) 14093 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14094 14095 14096 // Microsoft supports direct constructor calls. 14097 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14098 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14099 CandidateSet, 14100 /*SuppressUserConversions*/ false); 14101 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14102 // If explicit template arguments were provided, we can't call a 14103 // non-template member function. 14104 if (TemplateArgs) 14105 continue; 14106 14107 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14108 ObjectClassification, Args, CandidateSet, 14109 /*SuppressUserConversions=*/false); 14110 } else { 14111 AddMethodTemplateCandidate( 14112 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14113 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14114 /*SuppressUserConversions=*/false); 14115 } 14116 } 14117 14118 DeclarationName DeclName = UnresExpr->getMemberName(); 14119 14120 UnbridgedCasts.restore(); 14121 14122 OverloadCandidateSet::iterator Best; 14123 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14124 Best)) { 14125 case OR_Success: 14126 Method = cast<CXXMethodDecl>(Best->Function); 14127 FoundDecl = Best->FoundDecl; 14128 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14129 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14130 return ExprError(); 14131 // If FoundDecl is different from Method (such as if one is a template 14132 // and the other a specialization), make sure DiagnoseUseOfDecl is 14133 // called on both. 14134 // FIXME: This would be more comprehensively addressed by modifying 14135 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14136 // being used. 14137 if (Method != FoundDecl.getDecl() && 14138 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14139 return ExprError(); 14140 break; 14141 14142 case OR_No_Viable_Function: 14143 CandidateSet.NoteCandidates( 14144 PartialDiagnosticAt( 14145 UnresExpr->getMemberLoc(), 14146 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14147 << DeclName << MemExprE->getSourceRange()), 14148 *this, OCD_AllCandidates, Args); 14149 // FIXME: Leaking incoming expressions! 14150 return ExprError(); 14151 14152 case OR_Ambiguous: 14153 CandidateSet.NoteCandidates( 14154 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14155 PDiag(diag::err_ovl_ambiguous_member_call) 14156 << DeclName << MemExprE->getSourceRange()), 14157 *this, OCD_AmbiguousCandidates, Args); 14158 // FIXME: Leaking incoming expressions! 14159 return ExprError(); 14160 14161 case OR_Deleted: 14162 CandidateSet.NoteCandidates( 14163 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14164 PDiag(diag::err_ovl_deleted_member_call) 14165 << DeclName << MemExprE->getSourceRange()), 14166 *this, OCD_AllCandidates, Args); 14167 // FIXME: Leaking incoming expressions! 14168 return ExprError(); 14169 } 14170 14171 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14172 14173 // If overload resolution picked a static member, build a 14174 // non-member call based on that function. 14175 if (Method->isStatic()) { 14176 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14177 RParenLoc); 14178 } 14179 14180 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14181 } 14182 14183 QualType ResultType = Method->getReturnType(); 14184 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14185 ResultType = ResultType.getNonLValueExprType(Context); 14186 14187 assert(Method && "Member call to something that isn't a method?"); 14188 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14189 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14190 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14191 CurFPFeatureOverrides(), Proto->getNumParams()); 14192 14193 // Check for a valid return type. 14194 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14195 TheCall, Method)) 14196 return ExprError(); 14197 14198 // Convert the object argument (for a non-static member function call). 14199 // We only need to do this if there was actually an overload; otherwise 14200 // it was done at lookup. 14201 if (!Method->isStatic()) { 14202 ExprResult ObjectArg = 14203 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14204 FoundDecl, Method); 14205 if (ObjectArg.isInvalid()) 14206 return ExprError(); 14207 MemExpr->setBase(ObjectArg.get()); 14208 } 14209 14210 // Convert the rest of the arguments 14211 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14212 RParenLoc)) 14213 return ExprError(); 14214 14215 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14216 14217 if (CheckFunctionCall(Method, TheCall, Proto)) 14218 return ExprError(); 14219 14220 // In the case the method to call was not selected by the overloading 14221 // resolution process, we still need to handle the enable_if attribute. Do 14222 // that here, so it will not hide previous -- and more relevant -- errors. 14223 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14224 if (const EnableIfAttr *Attr = 14225 CheckEnableIf(Method, LParenLoc, Args, true)) { 14226 Diag(MemE->getMemberLoc(), 14227 diag::err_ovl_no_viable_member_function_in_call) 14228 << Method << Method->getSourceRange(); 14229 Diag(Method->getLocation(), 14230 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14231 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14232 return ExprError(); 14233 } 14234 } 14235 14236 if ((isa<CXXConstructorDecl>(CurContext) || 14237 isa<CXXDestructorDecl>(CurContext)) && 14238 TheCall->getMethodDecl()->isPure()) { 14239 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14240 14241 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14242 MemExpr->performsVirtualDispatch(getLangOpts())) { 14243 Diag(MemExpr->getBeginLoc(), 14244 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14245 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14246 << MD->getParent(); 14247 14248 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14249 if (getLangOpts().AppleKext) 14250 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14251 << MD->getParent() << MD->getDeclName(); 14252 } 14253 } 14254 14255 if (CXXDestructorDecl *DD = 14256 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14257 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14258 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14259 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14260 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14261 MemExpr->getMemberLoc()); 14262 } 14263 14264 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14265 TheCall->getMethodDecl()); 14266 } 14267 14268 /// BuildCallToObjectOfClassType - Build a call to an object of class 14269 /// type (C++ [over.call.object]), which can end up invoking an 14270 /// overloaded function call operator (@c operator()) or performing a 14271 /// user-defined conversion on the object argument. 14272 ExprResult 14273 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14274 SourceLocation LParenLoc, 14275 MultiExprArg Args, 14276 SourceLocation RParenLoc) { 14277 if (checkPlaceholderForOverload(*this, Obj)) 14278 return ExprError(); 14279 ExprResult Object = Obj; 14280 14281 UnbridgedCastsSet UnbridgedCasts; 14282 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14283 return ExprError(); 14284 14285 assert(Object.get()->getType()->isRecordType() && 14286 "Requires object type argument"); 14287 14288 // C++ [over.call.object]p1: 14289 // If the primary-expression E in the function call syntax 14290 // evaluates to a class object of type "cv T", then the set of 14291 // candidate functions includes at least the function call 14292 // operators of T. The function call operators of T are obtained by 14293 // ordinary lookup of the name operator() in the context of 14294 // (E).operator(). 14295 OverloadCandidateSet CandidateSet(LParenLoc, 14296 OverloadCandidateSet::CSK_Operator); 14297 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14298 14299 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14300 diag::err_incomplete_object_call, Object.get())) 14301 return true; 14302 14303 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14304 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14305 LookupQualifiedName(R, Record->getDecl()); 14306 R.suppressDiagnostics(); 14307 14308 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14309 Oper != OperEnd; ++Oper) { 14310 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14311 Object.get()->Classify(Context), Args, CandidateSet, 14312 /*SuppressUserConversion=*/false); 14313 } 14314 14315 // C++ [over.call.object]p2: 14316 // In addition, for each (non-explicit in C++0x) conversion function 14317 // declared in T of the form 14318 // 14319 // operator conversion-type-id () cv-qualifier; 14320 // 14321 // where cv-qualifier is the same cv-qualification as, or a 14322 // greater cv-qualification than, cv, and where conversion-type-id 14323 // denotes the type "pointer to function of (P1,...,Pn) returning 14324 // R", or the type "reference to pointer to function of 14325 // (P1,...,Pn) returning R", or the type "reference to function 14326 // of (P1,...,Pn) returning R", a surrogate call function [...] 14327 // is also considered as a candidate function. Similarly, 14328 // surrogate call functions are added to the set of candidate 14329 // functions for each conversion function declared in an 14330 // accessible base class provided the function is not hidden 14331 // within T by another intervening declaration. 14332 const auto &Conversions = 14333 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14334 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14335 NamedDecl *D = *I; 14336 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14337 if (isa<UsingShadowDecl>(D)) 14338 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14339 14340 // Skip over templated conversion functions; they aren't 14341 // surrogates. 14342 if (isa<FunctionTemplateDecl>(D)) 14343 continue; 14344 14345 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14346 if (!Conv->isExplicit()) { 14347 // Strip the reference type (if any) and then the pointer type (if 14348 // any) to get down to what might be a function type. 14349 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14350 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14351 ConvType = ConvPtrType->getPointeeType(); 14352 14353 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14354 { 14355 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14356 Object.get(), Args, CandidateSet); 14357 } 14358 } 14359 } 14360 14361 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14362 14363 // Perform overload resolution. 14364 OverloadCandidateSet::iterator Best; 14365 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14366 Best)) { 14367 case OR_Success: 14368 // Overload resolution succeeded; we'll build the appropriate call 14369 // below. 14370 break; 14371 14372 case OR_No_Viable_Function: { 14373 PartialDiagnostic PD = 14374 CandidateSet.empty() 14375 ? (PDiag(diag::err_ovl_no_oper) 14376 << Object.get()->getType() << /*call*/ 1 14377 << Object.get()->getSourceRange()) 14378 : (PDiag(diag::err_ovl_no_viable_object_call) 14379 << Object.get()->getType() << Object.get()->getSourceRange()); 14380 CandidateSet.NoteCandidates( 14381 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14382 OCD_AllCandidates, Args); 14383 break; 14384 } 14385 case OR_Ambiguous: 14386 CandidateSet.NoteCandidates( 14387 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14388 PDiag(diag::err_ovl_ambiguous_object_call) 14389 << Object.get()->getType() 14390 << Object.get()->getSourceRange()), 14391 *this, OCD_AmbiguousCandidates, Args); 14392 break; 14393 14394 case OR_Deleted: 14395 CandidateSet.NoteCandidates( 14396 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14397 PDiag(diag::err_ovl_deleted_object_call) 14398 << Object.get()->getType() 14399 << Object.get()->getSourceRange()), 14400 *this, OCD_AllCandidates, Args); 14401 break; 14402 } 14403 14404 if (Best == CandidateSet.end()) 14405 return true; 14406 14407 UnbridgedCasts.restore(); 14408 14409 if (Best->Function == nullptr) { 14410 // Since there is no function declaration, this is one of the 14411 // surrogate candidates. Dig out the conversion function. 14412 CXXConversionDecl *Conv 14413 = cast<CXXConversionDecl>( 14414 Best->Conversions[0].UserDefined.ConversionFunction); 14415 14416 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14417 Best->FoundDecl); 14418 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14419 return ExprError(); 14420 assert(Conv == Best->FoundDecl.getDecl() && 14421 "Found Decl & conversion-to-functionptr should be same, right?!"); 14422 // We selected one of the surrogate functions that converts the 14423 // object parameter to a function pointer. Perform the conversion 14424 // on the object argument, then let BuildCallExpr finish the job. 14425 14426 // Create an implicit member expr to refer to the conversion operator. 14427 // and then call it. 14428 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14429 Conv, HadMultipleCandidates); 14430 if (Call.isInvalid()) 14431 return ExprError(); 14432 // Record usage of conversion in an implicit cast. 14433 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14434 CK_UserDefinedConversion, Call.get(), 14435 nullptr, VK_RValue); 14436 14437 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14438 } 14439 14440 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14441 14442 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14443 // that calls this method, using Object for the implicit object 14444 // parameter and passing along the remaining arguments. 14445 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14446 14447 // An error diagnostic has already been printed when parsing the declaration. 14448 if (Method->isInvalidDecl()) 14449 return ExprError(); 14450 14451 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14452 unsigned NumParams = Proto->getNumParams(); 14453 14454 DeclarationNameInfo OpLocInfo( 14455 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14456 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14457 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14458 Obj, HadMultipleCandidates, 14459 OpLocInfo.getLoc(), 14460 OpLocInfo.getInfo()); 14461 if (NewFn.isInvalid()) 14462 return true; 14463 14464 // The number of argument slots to allocate in the call. If we have default 14465 // arguments we need to allocate space for them as well. We additionally 14466 // need one more slot for the object parameter. 14467 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14468 14469 // Build the full argument list for the method call (the implicit object 14470 // parameter is placed at the beginning of the list). 14471 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14472 14473 bool IsError = false; 14474 14475 // Initialize the implicit object parameter. 14476 ExprResult ObjRes = 14477 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14478 Best->FoundDecl, Method); 14479 if (ObjRes.isInvalid()) 14480 IsError = true; 14481 else 14482 Object = ObjRes; 14483 MethodArgs[0] = Object.get(); 14484 14485 // Check the argument types. 14486 for (unsigned i = 0; i != NumParams; i++) { 14487 Expr *Arg; 14488 if (i < Args.size()) { 14489 Arg = Args[i]; 14490 14491 // Pass the argument. 14492 14493 ExprResult InputInit 14494 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14495 Context, 14496 Method->getParamDecl(i)), 14497 SourceLocation(), Arg); 14498 14499 IsError |= InputInit.isInvalid(); 14500 Arg = InputInit.getAs<Expr>(); 14501 } else { 14502 ExprResult DefArg 14503 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14504 if (DefArg.isInvalid()) { 14505 IsError = true; 14506 break; 14507 } 14508 14509 Arg = DefArg.getAs<Expr>(); 14510 } 14511 14512 MethodArgs[i + 1] = Arg; 14513 } 14514 14515 // If this is a variadic call, handle args passed through "...". 14516 if (Proto->isVariadic()) { 14517 // Promote the arguments (C99 6.5.2.2p7). 14518 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14519 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14520 nullptr); 14521 IsError |= Arg.isInvalid(); 14522 MethodArgs[i + 1] = Arg.get(); 14523 } 14524 } 14525 14526 if (IsError) 14527 return true; 14528 14529 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14530 14531 // Once we've built TheCall, all of the expressions are properly owned. 14532 QualType ResultTy = Method->getReturnType(); 14533 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14534 ResultTy = ResultTy.getNonLValueExprType(Context); 14535 14536 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14537 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14538 CurFPFeatureOverrides()); 14539 14540 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14541 return true; 14542 14543 if (CheckFunctionCall(Method, TheCall, Proto)) 14544 return true; 14545 14546 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14547 } 14548 14549 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14550 /// (if one exists), where @c Base is an expression of class type and 14551 /// @c Member is the name of the member we're trying to find. 14552 ExprResult 14553 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14554 bool *NoArrowOperatorFound) { 14555 assert(Base->getType()->isRecordType() && 14556 "left-hand side must have class type"); 14557 14558 if (checkPlaceholderForOverload(*this, Base)) 14559 return ExprError(); 14560 14561 SourceLocation Loc = Base->getExprLoc(); 14562 14563 // C++ [over.ref]p1: 14564 // 14565 // [...] An expression x->m is interpreted as (x.operator->())->m 14566 // for a class object x of type T if T::operator->() exists and if 14567 // the operator is selected as the best match function by the 14568 // overload resolution mechanism (13.3). 14569 DeclarationName OpName = 14570 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14571 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14572 14573 if (RequireCompleteType(Loc, Base->getType(), 14574 diag::err_typecheck_incomplete_tag, Base)) 14575 return ExprError(); 14576 14577 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14578 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14579 R.suppressDiagnostics(); 14580 14581 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14582 Oper != OperEnd; ++Oper) { 14583 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14584 None, CandidateSet, /*SuppressUserConversion=*/false); 14585 } 14586 14587 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14588 14589 // Perform overload resolution. 14590 OverloadCandidateSet::iterator Best; 14591 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14592 case OR_Success: 14593 // Overload resolution succeeded; we'll build the call below. 14594 break; 14595 14596 case OR_No_Viable_Function: { 14597 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14598 if (CandidateSet.empty()) { 14599 QualType BaseType = Base->getType(); 14600 if (NoArrowOperatorFound) { 14601 // Report this specific error to the caller instead of emitting a 14602 // diagnostic, as requested. 14603 *NoArrowOperatorFound = true; 14604 return ExprError(); 14605 } 14606 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14607 << BaseType << Base->getSourceRange(); 14608 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14609 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14610 << FixItHint::CreateReplacement(OpLoc, "."); 14611 } 14612 } else 14613 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14614 << "operator->" << Base->getSourceRange(); 14615 CandidateSet.NoteCandidates(*this, Base, Cands); 14616 return ExprError(); 14617 } 14618 case OR_Ambiguous: 14619 CandidateSet.NoteCandidates( 14620 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14621 << "->" << Base->getType() 14622 << Base->getSourceRange()), 14623 *this, OCD_AmbiguousCandidates, Base); 14624 return ExprError(); 14625 14626 case OR_Deleted: 14627 CandidateSet.NoteCandidates( 14628 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14629 << "->" << Base->getSourceRange()), 14630 *this, OCD_AllCandidates, Base); 14631 return ExprError(); 14632 } 14633 14634 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14635 14636 // Convert the object parameter. 14637 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14638 ExprResult BaseResult = 14639 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14640 Best->FoundDecl, Method); 14641 if (BaseResult.isInvalid()) 14642 return ExprError(); 14643 Base = BaseResult.get(); 14644 14645 // Build the operator call. 14646 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14647 Base, HadMultipleCandidates, OpLoc); 14648 if (FnExpr.isInvalid()) 14649 return ExprError(); 14650 14651 QualType ResultTy = Method->getReturnType(); 14652 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14653 ResultTy = ResultTy.getNonLValueExprType(Context); 14654 CXXOperatorCallExpr *TheCall = 14655 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14656 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14657 14658 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14659 return ExprError(); 14660 14661 if (CheckFunctionCall(Method, TheCall, 14662 Method->getType()->castAs<FunctionProtoType>())) 14663 return ExprError(); 14664 14665 return MaybeBindToTemporary(TheCall); 14666 } 14667 14668 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14669 /// a literal operator described by the provided lookup results. 14670 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14671 DeclarationNameInfo &SuffixInfo, 14672 ArrayRef<Expr*> Args, 14673 SourceLocation LitEndLoc, 14674 TemplateArgumentListInfo *TemplateArgs) { 14675 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14676 14677 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14678 OverloadCandidateSet::CSK_Normal); 14679 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14680 TemplateArgs); 14681 14682 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14683 14684 // Perform overload resolution. This will usually be trivial, but might need 14685 // to perform substitutions for a literal operator template. 14686 OverloadCandidateSet::iterator Best; 14687 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14688 case OR_Success: 14689 case OR_Deleted: 14690 break; 14691 14692 case OR_No_Viable_Function: 14693 CandidateSet.NoteCandidates( 14694 PartialDiagnosticAt(UDSuffixLoc, 14695 PDiag(diag::err_ovl_no_viable_function_in_call) 14696 << R.getLookupName()), 14697 *this, OCD_AllCandidates, Args); 14698 return ExprError(); 14699 14700 case OR_Ambiguous: 14701 CandidateSet.NoteCandidates( 14702 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14703 << R.getLookupName()), 14704 *this, OCD_AmbiguousCandidates, Args); 14705 return ExprError(); 14706 } 14707 14708 FunctionDecl *FD = Best->Function; 14709 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14710 nullptr, HadMultipleCandidates, 14711 SuffixInfo.getLoc(), 14712 SuffixInfo.getInfo()); 14713 if (Fn.isInvalid()) 14714 return true; 14715 14716 // Check the argument types. This should almost always be a no-op, except 14717 // that array-to-pointer decay is applied to string literals. 14718 Expr *ConvArgs[2]; 14719 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14720 ExprResult InputInit = PerformCopyInitialization( 14721 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14722 SourceLocation(), Args[ArgIdx]); 14723 if (InputInit.isInvalid()) 14724 return true; 14725 ConvArgs[ArgIdx] = InputInit.get(); 14726 } 14727 14728 QualType ResultTy = FD->getReturnType(); 14729 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14730 ResultTy = ResultTy.getNonLValueExprType(Context); 14731 14732 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14733 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14734 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14735 14736 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14737 return ExprError(); 14738 14739 if (CheckFunctionCall(FD, UDL, nullptr)) 14740 return ExprError(); 14741 14742 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14743 } 14744 14745 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14746 /// given LookupResult is non-empty, it is assumed to describe a member which 14747 /// will be invoked. Otherwise, the function will be found via argument 14748 /// dependent lookup. 14749 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14750 /// otherwise CallExpr is set to ExprError() and some non-success value 14751 /// is returned. 14752 Sema::ForRangeStatus 14753 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14754 SourceLocation RangeLoc, 14755 const DeclarationNameInfo &NameInfo, 14756 LookupResult &MemberLookup, 14757 OverloadCandidateSet *CandidateSet, 14758 Expr *Range, ExprResult *CallExpr) { 14759 Scope *S = nullptr; 14760 14761 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14762 if (!MemberLookup.empty()) { 14763 ExprResult MemberRef = 14764 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14765 /*IsPtr=*/false, CXXScopeSpec(), 14766 /*TemplateKWLoc=*/SourceLocation(), 14767 /*FirstQualifierInScope=*/nullptr, 14768 MemberLookup, 14769 /*TemplateArgs=*/nullptr, S); 14770 if (MemberRef.isInvalid()) { 14771 *CallExpr = ExprError(); 14772 return FRS_DiagnosticIssued; 14773 } 14774 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14775 if (CallExpr->isInvalid()) { 14776 *CallExpr = ExprError(); 14777 return FRS_DiagnosticIssued; 14778 } 14779 } else { 14780 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14781 NestedNameSpecifierLoc(), 14782 NameInfo, UnresolvedSet<0>()); 14783 if (FnR.isInvalid()) 14784 return FRS_DiagnosticIssued; 14785 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14786 14787 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14788 CandidateSet, CallExpr); 14789 if (CandidateSet->empty() || CandidateSetError) { 14790 *CallExpr = ExprError(); 14791 return FRS_NoViableFunction; 14792 } 14793 OverloadCandidateSet::iterator Best; 14794 OverloadingResult OverloadResult = 14795 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14796 14797 if (OverloadResult == OR_No_Viable_Function) { 14798 *CallExpr = ExprError(); 14799 return FRS_NoViableFunction; 14800 } 14801 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14802 Loc, nullptr, CandidateSet, &Best, 14803 OverloadResult, 14804 /*AllowTypoCorrection=*/false); 14805 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14806 *CallExpr = ExprError(); 14807 return FRS_DiagnosticIssued; 14808 } 14809 } 14810 return FRS_Success; 14811 } 14812 14813 14814 /// FixOverloadedFunctionReference - E is an expression that refers to 14815 /// a C++ overloaded function (possibly with some parentheses and 14816 /// perhaps a '&' around it). We have resolved the overloaded function 14817 /// to the function declaration Fn, so patch up the expression E to 14818 /// refer (possibly indirectly) to Fn. Returns the new expr. 14819 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14820 FunctionDecl *Fn) { 14821 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14822 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14823 Found, Fn); 14824 if (SubExpr == PE->getSubExpr()) 14825 return PE; 14826 14827 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14828 } 14829 14830 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14831 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14832 Found, Fn); 14833 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14834 SubExpr->getType()) && 14835 "Implicit cast type cannot be determined from overload"); 14836 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14837 if (SubExpr == ICE->getSubExpr()) 14838 return ICE; 14839 14840 return ImplicitCastExpr::Create(Context, ICE->getType(), 14841 ICE->getCastKind(), 14842 SubExpr, nullptr, 14843 ICE->getValueKind()); 14844 } 14845 14846 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14847 if (!GSE->isResultDependent()) { 14848 Expr *SubExpr = 14849 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14850 if (SubExpr == GSE->getResultExpr()) 14851 return GSE; 14852 14853 // Replace the resulting type information before rebuilding the generic 14854 // selection expression. 14855 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14856 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14857 unsigned ResultIdx = GSE->getResultIndex(); 14858 AssocExprs[ResultIdx] = SubExpr; 14859 14860 return GenericSelectionExpr::Create( 14861 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14862 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14863 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14864 ResultIdx); 14865 } 14866 // Rather than fall through to the unreachable, return the original generic 14867 // selection expression. 14868 return GSE; 14869 } 14870 14871 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14872 assert(UnOp->getOpcode() == UO_AddrOf && 14873 "Can only take the address of an overloaded function"); 14874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14875 if (Method->isStatic()) { 14876 // Do nothing: static member functions aren't any different 14877 // from non-member functions. 14878 } else { 14879 // Fix the subexpression, which really has to be an 14880 // UnresolvedLookupExpr holding an overloaded member function 14881 // or template. 14882 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14883 Found, Fn); 14884 if (SubExpr == UnOp->getSubExpr()) 14885 return UnOp; 14886 14887 assert(isa<DeclRefExpr>(SubExpr) 14888 && "fixed to something other than a decl ref"); 14889 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14890 && "fixed to a member ref with no nested name qualifier"); 14891 14892 // We have taken the address of a pointer to member 14893 // function. Perform the computation here so that we get the 14894 // appropriate pointer to member type. 14895 QualType ClassType 14896 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14897 QualType MemPtrType 14898 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14899 // Under the MS ABI, lock down the inheritance model now. 14900 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14901 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14902 14903 return UnaryOperator::Create( 14904 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 14905 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 14906 } 14907 } 14908 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14909 Found, Fn); 14910 if (SubExpr == UnOp->getSubExpr()) 14911 return UnOp; 14912 14913 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf, 14914 Context.getPointerType(SubExpr->getType()), 14915 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), 14916 false, CurFPFeatureOverrides()); 14917 } 14918 14919 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14920 // FIXME: avoid copy. 14921 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14922 if (ULE->hasExplicitTemplateArgs()) { 14923 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14924 TemplateArgs = &TemplateArgsBuffer; 14925 } 14926 14927 DeclRefExpr *DRE = 14928 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14929 ULE->getQualifierLoc(), Found.getDecl(), 14930 ULE->getTemplateKeywordLoc(), TemplateArgs); 14931 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14932 return DRE; 14933 } 14934 14935 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14936 // FIXME: avoid copy. 14937 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14938 if (MemExpr->hasExplicitTemplateArgs()) { 14939 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14940 TemplateArgs = &TemplateArgsBuffer; 14941 } 14942 14943 Expr *Base; 14944 14945 // If we're filling in a static method where we used to have an 14946 // implicit member access, rewrite to a simple decl ref. 14947 if (MemExpr->isImplicitAccess()) { 14948 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14949 DeclRefExpr *DRE = BuildDeclRefExpr( 14950 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14951 MemExpr->getQualifierLoc(), Found.getDecl(), 14952 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14953 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14954 return DRE; 14955 } else { 14956 SourceLocation Loc = MemExpr->getMemberLoc(); 14957 if (MemExpr->getQualifier()) 14958 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14959 Base = 14960 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14961 } 14962 } else 14963 Base = MemExpr->getBase(); 14964 14965 ExprValueKind valueKind; 14966 QualType type; 14967 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14968 valueKind = VK_LValue; 14969 type = Fn->getType(); 14970 } else { 14971 valueKind = VK_RValue; 14972 type = Context.BoundMemberTy; 14973 } 14974 14975 return BuildMemberExpr( 14976 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14977 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14978 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14979 type, valueKind, OK_Ordinary, TemplateArgs); 14980 } 14981 14982 llvm_unreachable("Invalid reference to overloaded function"); 14983 } 14984 14985 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14986 DeclAccessPair Found, 14987 FunctionDecl *Fn) { 14988 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14989 } 14990