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 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1498 AssignmentAction Action, 1499 bool AllowExplicit) { 1500 if (checkPlaceholderForOverload(*this, From)) 1501 return ExprError(); 1502 1503 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1504 bool AllowObjCWritebackConversion 1505 = getLangOpts().ObjCAutoRefCount && 1506 (Action == AA_Passing || Action == AA_Sending); 1507 if (getLangOpts().ObjC) 1508 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1509 From->getType(), From); 1510 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1511 *this, From, ToType, 1512 /*SuppressUserConversions=*/false, 1513 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1514 /*InOverloadResolution=*/false, 1515 /*CStyle=*/false, AllowObjCWritebackConversion, 1516 /*AllowObjCConversionOnExplicit=*/false); 1517 return PerformImplicitConversion(From, ToType, ICS, Action); 1518 } 1519 1520 /// Determine whether the conversion from FromType to ToType is a valid 1521 /// conversion that strips "noexcept" or "noreturn" off the nested function 1522 /// type. 1523 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1524 QualType &ResultTy) { 1525 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1526 return false; 1527 1528 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1529 // or F(t noexcept) -> F(t) 1530 // where F adds one of the following at most once: 1531 // - a pointer 1532 // - a member pointer 1533 // - a block pointer 1534 // Changes here need matching changes in FindCompositePointerType. 1535 CanQualType CanTo = Context.getCanonicalType(ToType); 1536 CanQualType CanFrom = Context.getCanonicalType(FromType); 1537 Type::TypeClass TyClass = CanTo->getTypeClass(); 1538 if (TyClass != CanFrom->getTypeClass()) return false; 1539 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1540 if (TyClass == Type::Pointer) { 1541 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1542 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1543 } else if (TyClass == Type::BlockPointer) { 1544 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1545 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1546 } else if (TyClass == Type::MemberPointer) { 1547 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1548 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1549 // A function pointer conversion cannot change the class of the function. 1550 if (ToMPT->getClass() != FromMPT->getClass()) 1551 return false; 1552 CanTo = ToMPT->getPointeeType(); 1553 CanFrom = FromMPT->getPointeeType(); 1554 } else { 1555 return false; 1556 } 1557 1558 TyClass = CanTo->getTypeClass(); 1559 if (TyClass != CanFrom->getTypeClass()) return false; 1560 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1561 return false; 1562 } 1563 1564 const auto *FromFn = cast<FunctionType>(CanFrom); 1565 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1566 1567 const auto *ToFn = cast<FunctionType>(CanTo); 1568 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1569 1570 bool Changed = false; 1571 1572 // Drop 'noreturn' if not present in target type. 1573 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1574 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1575 Changed = true; 1576 } 1577 1578 // Drop 'noexcept' if not present in target type. 1579 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1580 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1581 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1582 FromFn = cast<FunctionType>( 1583 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1584 EST_None) 1585 .getTypePtr()); 1586 Changed = true; 1587 } 1588 1589 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1590 // only if the ExtParameterInfo lists of the two function prototypes can be 1591 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1592 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1593 bool CanUseToFPT, CanUseFromFPT; 1594 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1595 CanUseFromFPT, NewParamInfos) && 1596 CanUseToFPT && !CanUseFromFPT) { 1597 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1598 ExtInfo.ExtParameterInfos = 1599 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1600 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1601 FromFPT->getParamTypes(), ExtInfo); 1602 FromFn = QT->getAs<FunctionType>(); 1603 Changed = true; 1604 } 1605 } 1606 1607 if (!Changed) 1608 return false; 1609 1610 assert(QualType(FromFn, 0).isCanonical()); 1611 if (QualType(FromFn, 0) != CanTo) return false; 1612 1613 ResultTy = ToType; 1614 return true; 1615 } 1616 1617 /// Determine whether the conversion from FromType to ToType is a valid 1618 /// vector conversion. 1619 /// 1620 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1621 /// conversion. 1622 static bool IsVectorConversion(Sema &S, QualType FromType, 1623 QualType ToType, ImplicitConversionKind &ICK) { 1624 // We need at least one of these types to be a vector type to have a vector 1625 // conversion. 1626 if (!ToType->isVectorType() && !FromType->isVectorType()) 1627 return false; 1628 1629 // Identical types require no conversions. 1630 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1631 return false; 1632 1633 // There are no conversions between extended vector types, only identity. 1634 if (ToType->isExtVectorType()) { 1635 // There are no conversions between extended vector types other than the 1636 // identity conversion. 1637 if (FromType->isExtVectorType()) 1638 return false; 1639 1640 // Vector splat from any arithmetic type to a vector. 1641 if (FromType->isArithmeticType()) { 1642 ICK = ICK_Vector_Splat; 1643 return true; 1644 } 1645 } 1646 1647 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1648 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1649 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1650 ICK = ICK_SVE_Vector_Conversion; 1651 return true; 1652 } 1653 1654 // We can perform the conversion between vector types in the following cases: 1655 // 1)vector types are equivalent AltiVec and GCC vector types 1656 // 2)lax vector conversions are permitted and the vector types are of the 1657 // same size 1658 // 3)the destination type does not have the ARM MVE strict-polymorphism 1659 // attribute, which inhibits lax vector conversion for overload resolution 1660 // only 1661 if (ToType->isVectorType() && FromType->isVectorType()) { 1662 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1663 (S.isLaxVectorConversion(FromType, ToType) && 1664 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1665 ICK = ICK_Vector_Conversion; 1666 return true; 1667 } 1668 } 1669 1670 return false; 1671 } 1672 1673 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1674 bool InOverloadResolution, 1675 StandardConversionSequence &SCS, 1676 bool CStyle); 1677 1678 /// IsStandardConversion - Determines whether there is a standard 1679 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1680 /// expression From to the type ToType. Standard conversion sequences 1681 /// only consider non-class types; for conversions that involve class 1682 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1683 /// contain the standard conversion sequence required to perform this 1684 /// conversion and this routine will return true. Otherwise, this 1685 /// routine will return false and the value of SCS is unspecified. 1686 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1687 bool InOverloadResolution, 1688 StandardConversionSequence &SCS, 1689 bool CStyle, 1690 bool AllowObjCWritebackConversion) { 1691 QualType FromType = From->getType(); 1692 1693 // Standard conversions (C++ [conv]) 1694 SCS.setAsIdentityConversion(); 1695 SCS.IncompatibleObjC = false; 1696 SCS.setFromType(FromType); 1697 SCS.CopyConstructor = nullptr; 1698 1699 // There are no standard conversions for class types in C++, so 1700 // abort early. When overloading in C, however, we do permit them. 1701 if (S.getLangOpts().CPlusPlus && 1702 (FromType->isRecordType() || ToType->isRecordType())) 1703 return false; 1704 1705 // The first conversion can be an lvalue-to-rvalue conversion, 1706 // array-to-pointer conversion, or function-to-pointer conversion 1707 // (C++ 4p1). 1708 1709 if (FromType == S.Context.OverloadTy) { 1710 DeclAccessPair AccessPair; 1711 if (FunctionDecl *Fn 1712 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1713 AccessPair)) { 1714 // We were able to resolve the address of the overloaded function, 1715 // so we can convert to the type of that function. 1716 FromType = Fn->getType(); 1717 SCS.setFromType(FromType); 1718 1719 // we can sometimes resolve &foo<int> regardless of ToType, so check 1720 // if the type matches (identity) or we are converting to bool 1721 if (!S.Context.hasSameUnqualifiedType( 1722 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1723 QualType resultTy; 1724 // if the function type matches except for [[noreturn]], it's ok 1725 if (!S.IsFunctionConversion(FromType, 1726 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1727 // otherwise, only a boolean conversion is standard 1728 if (!ToType->isBooleanType()) 1729 return false; 1730 } 1731 1732 // Check if the "from" expression is taking the address of an overloaded 1733 // function and recompute the FromType accordingly. Take advantage of the 1734 // fact that non-static member functions *must* have such an address-of 1735 // expression. 1736 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1737 if (Method && !Method->isStatic()) { 1738 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1739 "Non-unary operator on non-static member address"); 1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1741 == UO_AddrOf && 1742 "Non-address-of operator on non-static member address"); 1743 const Type *ClassType 1744 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1745 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1746 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1748 UO_AddrOf && 1749 "Non-address-of operator for overloaded function expression"); 1750 FromType = S.Context.getPointerType(FromType); 1751 } 1752 1753 // Check that we've computed the proper type after overload resolution. 1754 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1755 // be calling it from within an NDEBUG block. 1756 assert(S.Context.hasSameType( 1757 FromType, 1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1759 } else { 1760 return false; 1761 } 1762 } 1763 // Lvalue-to-rvalue conversion (C++11 4.1): 1764 // A glvalue (3.10) of a non-function, non-array type T can 1765 // be converted to a prvalue. 1766 bool argIsLValue = From->isGLValue(); 1767 if (argIsLValue && 1768 !FromType->isFunctionType() && !FromType->isArrayType() && 1769 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1770 SCS.First = ICK_Lvalue_To_Rvalue; 1771 1772 // C11 6.3.2.1p2: 1773 // ... if the lvalue has atomic type, the value has the non-atomic version 1774 // of the type of the lvalue ... 1775 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1776 FromType = Atomic->getValueType(); 1777 1778 // If T is a non-class type, the type of the rvalue is the 1779 // cv-unqualified version of T. Otherwise, the type of the rvalue 1780 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1781 // just strip the qualifiers because they don't matter. 1782 FromType = FromType.getUnqualifiedType(); 1783 } else if (FromType->isArrayType()) { 1784 // Array-to-pointer conversion (C++ 4.2) 1785 SCS.First = ICK_Array_To_Pointer; 1786 1787 // An lvalue or rvalue of type "array of N T" or "array of unknown 1788 // bound of T" can be converted to an rvalue of type "pointer to 1789 // T" (C++ 4.2p1). 1790 FromType = S.Context.getArrayDecayedType(FromType); 1791 1792 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1793 // This conversion is deprecated in C++03 (D.4) 1794 SCS.DeprecatedStringLiteralToCharPtr = true; 1795 1796 // For the purpose of ranking in overload resolution 1797 // (13.3.3.1.1), this conversion is considered an 1798 // array-to-pointer conversion followed by a qualification 1799 // conversion (4.4). (C++ 4.2p2) 1800 SCS.Second = ICK_Identity; 1801 SCS.Third = ICK_Qualification; 1802 SCS.QualificationIncludesObjCLifetime = false; 1803 SCS.setAllToTypes(FromType); 1804 return true; 1805 } 1806 } else if (FromType->isFunctionType() && argIsLValue) { 1807 // Function-to-pointer conversion (C++ 4.3). 1808 SCS.First = ICK_Function_To_Pointer; 1809 1810 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1811 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1812 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1813 return false; 1814 1815 // An lvalue of function type T can be converted to an rvalue of 1816 // type "pointer to T." The result is a pointer to the 1817 // function. (C++ 4.3p1). 1818 FromType = S.Context.getPointerType(FromType); 1819 } else { 1820 // We don't require any conversions for the first step. 1821 SCS.First = ICK_Identity; 1822 } 1823 SCS.setToType(0, FromType); 1824 1825 // The second conversion can be an integral promotion, floating 1826 // point promotion, integral conversion, floating point conversion, 1827 // floating-integral conversion, pointer conversion, 1828 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1829 // For overloading in C, this can also be a "compatible-type" 1830 // conversion. 1831 bool IncompatibleObjC = false; 1832 ImplicitConversionKind SecondICK = ICK_Identity; 1833 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1834 // The unqualified versions of the types are the same: there's no 1835 // conversion to do. 1836 SCS.Second = ICK_Identity; 1837 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1838 // Integral promotion (C++ 4.5). 1839 SCS.Second = ICK_Integral_Promotion; 1840 FromType = ToType.getUnqualifiedType(); 1841 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1842 // Floating point promotion (C++ 4.6). 1843 SCS.Second = ICK_Floating_Promotion; 1844 FromType = ToType.getUnqualifiedType(); 1845 } else if (S.IsComplexPromotion(FromType, ToType)) { 1846 // Complex promotion (Clang extension) 1847 SCS.Second = ICK_Complex_Promotion; 1848 FromType = ToType.getUnqualifiedType(); 1849 } else if (ToType->isBooleanType() && 1850 (FromType->isArithmeticType() || 1851 FromType->isAnyPointerType() || 1852 FromType->isBlockPointerType() || 1853 FromType->isMemberPointerType())) { 1854 // Boolean conversions (C++ 4.12). 1855 SCS.Second = ICK_Boolean_Conversion; 1856 FromType = S.Context.BoolTy; 1857 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1858 ToType->isIntegralType(S.Context)) { 1859 // Integral conversions (C++ 4.7). 1860 SCS.Second = ICK_Integral_Conversion; 1861 FromType = ToType.getUnqualifiedType(); 1862 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1863 // Complex conversions (C99 6.3.1.6) 1864 SCS.Second = ICK_Complex_Conversion; 1865 FromType = ToType.getUnqualifiedType(); 1866 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1867 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1868 // Complex-real conversions (C99 6.3.1.7) 1869 SCS.Second = ICK_Complex_Real; 1870 FromType = ToType.getUnqualifiedType(); 1871 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1872 // FIXME: disable conversions between long double and __float128 if 1873 // their representation is different until there is back end support 1874 // We of course allow this conversion if long double is really double. 1875 1876 // Conversions between bfloat and other floats are not permitted. 1877 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1878 return false; 1879 if (&S.Context.getFloatTypeSemantics(FromType) != 1880 &S.Context.getFloatTypeSemantics(ToType)) { 1881 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1882 ToType == S.Context.LongDoubleTy) || 1883 (FromType == S.Context.LongDoubleTy && 1884 ToType == S.Context.Float128Ty)); 1885 if (Float128AndLongDouble && 1886 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1887 &llvm::APFloat::PPCDoubleDouble())) 1888 return false; 1889 } 1890 // Floating point conversions (C++ 4.8). 1891 SCS.Second = ICK_Floating_Conversion; 1892 FromType = ToType.getUnqualifiedType(); 1893 } else if ((FromType->isRealFloatingType() && 1894 ToType->isIntegralType(S.Context)) || 1895 (FromType->isIntegralOrUnscopedEnumerationType() && 1896 ToType->isRealFloatingType())) { 1897 // Conversions between bfloat and int are not permitted. 1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1899 return false; 1900 1901 // Floating-integral conversions (C++ 4.9). 1902 SCS.Second = ICK_Floating_Integral; 1903 FromType = ToType.getUnqualifiedType(); 1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1905 SCS.Second = ICK_Block_Pointer_Conversion; 1906 } else if (AllowObjCWritebackConversion && 1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1908 SCS.Second = ICK_Writeback_Conversion; 1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1910 FromType, IncompatibleObjC)) { 1911 // Pointer conversions (C++ 4.10). 1912 SCS.Second = ICK_Pointer_Conversion; 1913 SCS.IncompatibleObjC = IncompatibleObjC; 1914 FromType = FromType.getUnqualifiedType(); 1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1916 InOverloadResolution, FromType)) { 1917 // Pointer to member conversions (4.11). 1918 SCS.Second = ICK_Pointer_Member; 1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1920 SCS.Second = SecondICK; 1921 FromType = ToType.getUnqualifiedType(); 1922 } else if (!S.getLangOpts().CPlusPlus && 1923 S.Context.typesAreCompatible(ToType, FromType)) { 1924 // Compatible conversions (Clang extension for C function overloading) 1925 SCS.Second = ICK_Compatible_Conversion; 1926 FromType = ToType.getUnqualifiedType(); 1927 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1928 InOverloadResolution, 1929 SCS, CStyle)) { 1930 SCS.Second = ICK_TransparentUnionConversion; 1931 FromType = ToType; 1932 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1933 CStyle)) { 1934 // tryAtomicConversion has updated the standard conversion sequence 1935 // appropriately. 1936 return true; 1937 } else if (ToType->isEventT() && 1938 From->isIntegerConstantExpr(S.getASTContext()) && 1939 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1940 SCS.Second = ICK_Zero_Event_Conversion; 1941 FromType = ToType; 1942 } else if (ToType->isQueueT() && 1943 From->isIntegerConstantExpr(S.getASTContext()) && 1944 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1945 SCS.Second = ICK_Zero_Queue_Conversion; 1946 FromType = ToType; 1947 } else if (ToType->isSamplerT() && 1948 From->isIntegerConstantExpr(S.getASTContext())) { 1949 SCS.Second = ICK_Compatible_Conversion; 1950 FromType = ToType; 1951 } else { 1952 // No second conversion required. 1953 SCS.Second = ICK_Identity; 1954 } 1955 SCS.setToType(1, FromType); 1956 1957 // The third conversion can be a function pointer conversion or a 1958 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1959 bool ObjCLifetimeConversion; 1960 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1961 // Function pointer conversions (removing 'noexcept') including removal of 1962 // 'noreturn' (Clang extension). 1963 SCS.Third = ICK_Function_Conversion; 1964 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1965 ObjCLifetimeConversion)) { 1966 SCS.Third = ICK_Qualification; 1967 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1968 FromType = ToType; 1969 } else { 1970 // No conversion required 1971 SCS.Third = ICK_Identity; 1972 } 1973 1974 // C++ [over.best.ics]p6: 1975 // [...] Any difference in top-level cv-qualification is 1976 // subsumed by the initialization itself and does not constitute 1977 // a conversion. [...] 1978 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1979 QualType CanonTo = S.Context.getCanonicalType(ToType); 1980 if (CanonFrom.getLocalUnqualifiedType() 1981 == CanonTo.getLocalUnqualifiedType() && 1982 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1983 FromType = ToType; 1984 CanonFrom = CanonTo; 1985 } 1986 1987 SCS.setToType(2, FromType); 1988 1989 if (CanonFrom == CanonTo) 1990 return true; 1991 1992 // If we have not converted the argument type to the parameter type, 1993 // this is a bad conversion sequence, unless we're resolving an overload in C. 1994 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1995 return false; 1996 1997 ExprResult ER = ExprResult{From}; 1998 Sema::AssignConvertType Conv = 1999 S.CheckSingleAssignmentConstraints(ToType, ER, 2000 /*Diagnose=*/false, 2001 /*DiagnoseCFAudited=*/false, 2002 /*ConvertRHS=*/false); 2003 ImplicitConversionKind SecondConv; 2004 switch (Conv) { 2005 case Sema::Compatible: 2006 SecondConv = ICK_C_Only_Conversion; 2007 break; 2008 // For our purposes, discarding qualifiers is just as bad as using an 2009 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2010 // qualifiers, as well. 2011 case Sema::CompatiblePointerDiscardsQualifiers: 2012 case Sema::IncompatiblePointer: 2013 case Sema::IncompatiblePointerSign: 2014 SecondConv = ICK_Incompatible_Pointer_Conversion; 2015 break; 2016 default: 2017 return false; 2018 } 2019 2020 // First can only be an lvalue conversion, so we pretend that this was the 2021 // second conversion. First should already be valid from earlier in the 2022 // function. 2023 SCS.Second = SecondConv; 2024 SCS.setToType(1, ToType); 2025 2026 // Third is Identity, because Second should rank us worse than any other 2027 // conversion. This could also be ICK_Qualification, but it's simpler to just 2028 // lump everything in with the second conversion, and we don't gain anything 2029 // from making this ICK_Qualification. 2030 SCS.Third = ICK_Identity; 2031 SCS.setToType(2, ToType); 2032 return true; 2033 } 2034 2035 static bool 2036 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2037 QualType &ToType, 2038 bool InOverloadResolution, 2039 StandardConversionSequence &SCS, 2040 bool CStyle) { 2041 2042 const RecordType *UT = ToType->getAsUnionType(); 2043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2044 return false; 2045 // The field to initialize within the transparent union. 2046 RecordDecl *UD = UT->getDecl(); 2047 // It's compatible if the expression matches any of the fields. 2048 for (const auto *it : UD->fields()) { 2049 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2050 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2051 ToType = it->getType(); 2052 return true; 2053 } 2054 } 2055 return false; 2056 } 2057 2058 /// IsIntegralPromotion - Determines whether the conversion from the 2059 /// expression From (whose potentially-adjusted type is FromType) to 2060 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2061 /// sets PromotedType to the promoted type. 2062 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2063 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2064 // All integers are built-in. 2065 if (!To) { 2066 return false; 2067 } 2068 2069 // An rvalue of type char, signed char, unsigned char, short int, or 2070 // unsigned short int can be converted to an rvalue of type int if 2071 // int can represent all the values of the source type; otherwise, 2072 // the source rvalue can be converted to an rvalue of type unsigned 2073 // int (C++ 4.5p1). 2074 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2075 !FromType->isEnumeralType()) { 2076 if (// We can promote any signed, promotable integer type to an int 2077 (FromType->isSignedIntegerType() || 2078 // We can promote any unsigned integer type whose size is 2079 // less than int to an int. 2080 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2081 return To->getKind() == BuiltinType::Int; 2082 } 2083 2084 return To->getKind() == BuiltinType::UInt; 2085 } 2086 2087 // C++11 [conv.prom]p3: 2088 // A prvalue of an unscoped enumeration type whose underlying type is not 2089 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2090 // following types that can represent all the values of the enumeration 2091 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2092 // unsigned int, long int, unsigned long int, long long int, or unsigned 2093 // long long int. If none of the types in that list can represent all the 2094 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2095 // type can be converted to an rvalue a prvalue of the extended integer type 2096 // with lowest integer conversion rank (4.13) greater than the rank of long 2097 // long in which all the values of the enumeration can be represented. If 2098 // there are two such extended types, the signed one is chosen. 2099 // C++11 [conv.prom]p4: 2100 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2101 // can be converted to a prvalue of its underlying type. Moreover, if 2102 // integral promotion can be applied to its underlying type, a prvalue of an 2103 // unscoped enumeration type whose underlying type is fixed can also be 2104 // converted to a prvalue of the promoted underlying type. 2105 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2106 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2107 // provided for a scoped enumeration. 2108 if (FromEnumType->getDecl()->isScoped()) 2109 return false; 2110 2111 // We can perform an integral promotion to the underlying type of the enum, 2112 // even if that's not the promoted type. Note that the check for promoting 2113 // the underlying type is based on the type alone, and does not consider 2114 // the bitfield-ness of the actual source expression. 2115 if (FromEnumType->getDecl()->isFixed()) { 2116 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2117 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2118 IsIntegralPromotion(nullptr, Underlying, ToType); 2119 } 2120 2121 // We have already pre-calculated the promotion type, so this is trivial. 2122 if (ToType->isIntegerType() && 2123 isCompleteType(From->getBeginLoc(), FromType)) 2124 return Context.hasSameUnqualifiedType( 2125 ToType, FromEnumType->getDecl()->getPromotionType()); 2126 2127 // C++ [conv.prom]p5: 2128 // If the bit-field has an enumerated type, it is treated as any other 2129 // value of that type for promotion purposes. 2130 // 2131 // ... so do not fall through into the bit-field checks below in C++. 2132 if (getLangOpts().CPlusPlus) 2133 return false; 2134 } 2135 2136 // C++0x [conv.prom]p2: 2137 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2138 // to an rvalue a prvalue of the first of the following types that can 2139 // represent all the values of its underlying type: int, unsigned int, 2140 // long int, unsigned long int, long long int, or unsigned long long int. 2141 // If none of the types in that list can represent all the values of its 2142 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2143 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2144 // type. 2145 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2146 ToType->isIntegerType()) { 2147 // Determine whether the type we're converting from is signed or 2148 // unsigned. 2149 bool FromIsSigned = FromType->isSignedIntegerType(); 2150 uint64_t FromSize = Context.getTypeSize(FromType); 2151 2152 // The types we'll try to promote to, in the appropriate 2153 // order. Try each of these types. 2154 QualType PromoteTypes[6] = { 2155 Context.IntTy, Context.UnsignedIntTy, 2156 Context.LongTy, Context.UnsignedLongTy , 2157 Context.LongLongTy, Context.UnsignedLongLongTy 2158 }; 2159 for (int Idx = 0; Idx < 6; ++Idx) { 2160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2161 if (FromSize < ToSize || 2162 (FromSize == ToSize && 2163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2164 // We found the type that we can promote to. If this is the 2165 // type we wanted, we have a promotion. Otherwise, no 2166 // promotion. 2167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2168 } 2169 } 2170 } 2171 2172 // An rvalue for an integral bit-field (9.6) can be converted to an 2173 // rvalue of type int if int can represent all the values of the 2174 // bit-field; otherwise, it can be converted to unsigned int if 2175 // unsigned int can represent all the values of the bit-field. If 2176 // the bit-field is larger yet, no integral promotion applies to 2177 // it. If the bit-field has an enumerated type, it is treated as any 2178 // other value of that type for promotion purposes (C++ 4.5p3). 2179 // FIXME: We should delay checking of bit-fields until we actually perform the 2180 // conversion. 2181 // 2182 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2183 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2184 // bit-fields and those whose underlying type is larger than int) for GCC 2185 // compatibility. 2186 if (From) { 2187 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2188 Optional<llvm::APSInt> BitWidth; 2189 if (FromType->isIntegralType(Context) && 2190 (BitWidth = 2191 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2192 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2193 ToSize = Context.getTypeSize(ToType); 2194 2195 // Are we promoting to an int from a bitfield that fits in an int? 2196 if (*BitWidth < ToSize || 2197 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2198 return To->getKind() == BuiltinType::Int; 2199 } 2200 2201 // Are we promoting to an unsigned int from an unsigned bitfield 2202 // that fits into an unsigned int? 2203 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2204 return To->getKind() == BuiltinType::UInt; 2205 } 2206 2207 return false; 2208 } 2209 } 2210 } 2211 2212 // An rvalue of type bool can be converted to an rvalue of type int, 2213 // with false becoming zero and true becoming one (C++ 4.5p4). 2214 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2215 return true; 2216 } 2217 2218 return false; 2219 } 2220 2221 /// IsFloatingPointPromotion - Determines whether the conversion from 2222 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2223 /// returns true and sets PromotedType to the promoted type. 2224 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2227 /// An rvalue of type float can be converted to an rvalue of type 2228 /// double. (C++ 4.6p1). 2229 if (FromBuiltin->getKind() == BuiltinType::Float && 2230 ToBuiltin->getKind() == BuiltinType::Double) 2231 return true; 2232 2233 // C99 6.3.1.5p1: 2234 // When a float is promoted to double or long double, or a 2235 // double is promoted to long double [...]. 2236 if (!getLangOpts().CPlusPlus && 2237 (FromBuiltin->getKind() == BuiltinType::Float || 2238 FromBuiltin->getKind() == BuiltinType::Double) && 2239 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2240 ToBuiltin->getKind() == BuiltinType::Float128)) 2241 return true; 2242 2243 // Half can be promoted to float. 2244 if (!getLangOpts().NativeHalfType && 2245 FromBuiltin->getKind() == BuiltinType::Half && 2246 ToBuiltin->getKind() == BuiltinType::Float) 2247 return true; 2248 } 2249 2250 return false; 2251 } 2252 2253 /// Determine if a conversion is a complex promotion. 2254 /// 2255 /// A complex promotion is defined as a complex -> complex conversion 2256 /// where the conversion between the underlying real types is a 2257 /// floating-point or integral promotion. 2258 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2260 if (!FromComplex) 2261 return false; 2262 2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2264 if (!ToComplex) 2265 return false; 2266 2267 return IsFloatingPointPromotion(FromComplex->getElementType(), 2268 ToComplex->getElementType()) || 2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2270 ToComplex->getElementType()); 2271 } 2272 2273 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2274 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2275 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2276 /// if non-empty, will be a pointer to ToType that may or may not have 2277 /// the right set of qualifiers on its pointee. 2278 /// 2279 static QualType 2280 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2281 QualType ToPointee, QualType ToType, 2282 ASTContext &Context, 2283 bool StripObjCLifetime = false) { 2284 assert((FromPtr->getTypeClass() == Type::Pointer || 2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2286 "Invalid similarly-qualified pointer type"); 2287 2288 /// Conversions to 'id' subsume cv-qualifier conversions. 2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2290 return ToType.getUnqualifiedType(); 2291 2292 QualType CanonFromPointee 2293 = Context.getCanonicalType(FromPtr->getPointeeType()); 2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2295 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2296 2297 if (StripObjCLifetime) 2298 Quals.removeObjCLifetime(); 2299 2300 // Exact qualifier match -> return the pointer type we're converting to. 2301 if (CanonToPointee.getLocalQualifiers() == Quals) { 2302 // ToType is exactly what we need. Return it. 2303 if (!ToType.isNull()) 2304 return ToType.getUnqualifiedType(); 2305 2306 // Build a pointer to ToPointee. It has the right qualifiers 2307 // already. 2308 if (isa<ObjCObjectPointerType>(ToType)) 2309 return Context.getObjCObjectPointerType(ToPointee); 2310 return Context.getPointerType(ToPointee); 2311 } 2312 2313 // Just build a canonical type that has the right qualifiers. 2314 QualType QualifiedCanonToPointee 2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2316 2317 if (isa<ObjCObjectPointerType>(ToType)) 2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2319 return Context.getPointerType(QualifiedCanonToPointee); 2320 } 2321 2322 static bool isNullPointerConstantForConversion(Expr *Expr, 2323 bool InOverloadResolution, 2324 ASTContext &Context) { 2325 // Handle value-dependent integral null pointer constants correctly. 2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2329 return !InOverloadResolution; 2330 2331 return Expr->isNullPointerConstant(Context, 2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2333 : Expr::NPC_ValueDependentIsNull); 2334 } 2335 2336 /// IsPointerConversion - Determines whether the conversion of the 2337 /// expression From, which has the (possibly adjusted) type FromType, 2338 /// can be converted to the type ToType via a pointer conversion (C++ 2339 /// 4.10). If so, returns true and places the converted type (that 2340 /// might differ from ToType in its cv-qualifiers at some level) into 2341 /// ConvertedType. 2342 /// 2343 /// This routine also supports conversions to and from block pointers 2344 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2345 /// pointers to interfaces. FIXME: Once we've determined the 2346 /// appropriate overloading rules for Objective-C, we may want to 2347 /// split the Objective-C checks into a different routine; however, 2348 /// GCC seems to consider all of these conversions to be pointer 2349 /// conversions, so for now they live here. IncompatibleObjC will be 2350 /// set if the conversion is an allowed Objective-C conversion that 2351 /// should result in a warning. 2352 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2353 bool InOverloadResolution, 2354 QualType& ConvertedType, 2355 bool &IncompatibleObjC) { 2356 IncompatibleObjC = false; 2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2358 IncompatibleObjC)) 2359 return true; 2360 2361 // Conversion from a null pointer constant to any Objective-C pointer type. 2362 if (ToType->isObjCObjectPointerType() && 2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2364 ConvertedType = ToType; 2365 return true; 2366 } 2367 2368 // Blocks: Block pointers can be converted to void*. 2369 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2371 ConvertedType = ToType; 2372 return true; 2373 } 2374 // Blocks: A null pointer constant can be converted to a block 2375 // pointer type. 2376 if (ToType->isBlockPointerType() && 2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2378 ConvertedType = ToType; 2379 return true; 2380 } 2381 2382 // If the left-hand-side is nullptr_t, the right side can be a null 2383 // pointer constant. 2384 if (ToType->isNullPtrType() && 2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2386 ConvertedType = ToType; 2387 return true; 2388 } 2389 2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2391 if (!ToTypePtr) 2392 return false; 2393 2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2396 ConvertedType = ToType; 2397 return true; 2398 } 2399 2400 // Beyond this point, both types need to be pointers 2401 // , including objective-c pointers. 2402 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2404 !getLangOpts().ObjCAutoRefCount) { 2405 ConvertedType = BuildSimilarlyQualifiedPointerType( 2406 FromType->getAs<ObjCObjectPointerType>(), 2407 ToPointeeType, 2408 ToType, Context); 2409 return true; 2410 } 2411 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2412 if (!FromTypePtr) 2413 return false; 2414 2415 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2416 2417 // If the unqualified pointee types are the same, this can't be a 2418 // pointer conversion, so don't do all of the work below. 2419 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2420 return false; 2421 2422 // An rvalue of type "pointer to cv T," where T is an object type, 2423 // can be converted to an rvalue of type "pointer to cv void" (C++ 2424 // 4.10p2). 2425 if (FromPointeeType->isIncompleteOrObjectType() && 2426 ToPointeeType->isVoidType()) { 2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2428 ToPointeeType, 2429 ToType, Context, 2430 /*StripObjCLifetime=*/true); 2431 return true; 2432 } 2433 2434 // MSVC allows implicit function to void* type conversion. 2435 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2436 ToPointeeType->isVoidType()) { 2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2438 ToPointeeType, 2439 ToType, Context); 2440 return true; 2441 } 2442 2443 // When we're overloading in C, we allow a special kind of pointer 2444 // conversion for compatible-but-not-identical pointee types. 2445 if (!getLangOpts().CPlusPlus && 2446 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2447 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2448 ToPointeeType, 2449 ToType, Context); 2450 return true; 2451 } 2452 2453 // C++ [conv.ptr]p3: 2454 // 2455 // An rvalue of type "pointer to cv D," where D is a class type, 2456 // can be converted to an rvalue of type "pointer to cv B," where 2457 // B is a base class (clause 10) of D. If B is an inaccessible 2458 // (clause 11) or ambiguous (10.2) base class of D, a program that 2459 // necessitates this conversion is ill-formed. The result of the 2460 // conversion is a pointer to the base class sub-object of the 2461 // derived class object. The null pointer value is converted to 2462 // the null pointer value of the destination type. 2463 // 2464 // Note that we do not check for ambiguity or inaccessibility 2465 // here. That is handled by CheckPointerConversion. 2466 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2467 ToPointeeType->isRecordType() && 2468 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2469 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2470 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2471 ToPointeeType, 2472 ToType, Context); 2473 return true; 2474 } 2475 2476 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2477 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2478 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2479 ToPointeeType, 2480 ToType, Context); 2481 return true; 2482 } 2483 2484 return false; 2485 } 2486 2487 /// Adopt the given qualifiers for the given type. 2488 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2489 Qualifiers TQs = T.getQualifiers(); 2490 2491 // Check whether qualifiers already match. 2492 if (TQs == Qs) 2493 return T; 2494 2495 if (Qs.compatiblyIncludes(TQs)) 2496 return Context.getQualifiedType(T, Qs); 2497 2498 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2499 } 2500 2501 /// isObjCPointerConversion - Determines whether this is an 2502 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2503 /// with the same arguments and return values. 2504 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2505 QualType& ConvertedType, 2506 bool &IncompatibleObjC) { 2507 if (!getLangOpts().ObjC) 2508 return false; 2509 2510 // The set of qualifiers on the type we're converting from. 2511 Qualifiers FromQualifiers = FromType.getQualifiers(); 2512 2513 // First, we handle all conversions on ObjC object pointer types. 2514 const ObjCObjectPointerType* ToObjCPtr = 2515 ToType->getAs<ObjCObjectPointerType>(); 2516 const ObjCObjectPointerType *FromObjCPtr = 2517 FromType->getAs<ObjCObjectPointerType>(); 2518 2519 if (ToObjCPtr && FromObjCPtr) { 2520 // If the pointee types are the same (ignoring qualifications), 2521 // then this is not a pointer conversion. 2522 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2523 FromObjCPtr->getPointeeType())) 2524 return false; 2525 2526 // Conversion between Objective-C pointers. 2527 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2528 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2529 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2530 if (getLangOpts().CPlusPlus && LHS && RHS && 2531 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2532 FromObjCPtr->getPointeeType())) 2533 return false; 2534 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2535 ToObjCPtr->getPointeeType(), 2536 ToType, Context); 2537 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2538 return true; 2539 } 2540 2541 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2542 // Okay: this is some kind of implicit downcast of Objective-C 2543 // interfaces, which is permitted. However, we're going to 2544 // complain about it. 2545 IncompatibleObjC = true; 2546 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2547 ToObjCPtr->getPointeeType(), 2548 ToType, Context); 2549 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2550 return true; 2551 } 2552 } 2553 // Beyond this point, both types need to be C pointers or block pointers. 2554 QualType ToPointeeType; 2555 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2556 ToPointeeType = ToCPtr->getPointeeType(); 2557 else if (const BlockPointerType *ToBlockPtr = 2558 ToType->getAs<BlockPointerType>()) { 2559 // Objective C++: We're able to convert from a pointer to any object 2560 // to a block pointer type. 2561 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2562 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2563 return true; 2564 } 2565 ToPointeeType = ToBlockPtr->getPointeeType(); 2566 } 2567 else if (FromType->getAs<BlockPointerType>() && 2568 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2569 // Objective C++: We're able to convert from a block pointer type to a 2570 // pointer to any object. 2571 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2572 return true; 2573 } 2574 else 2575 return false; 2576 2577 QualType FromPointeeType; 2578 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2579 FromPointeeType = FromCPtr->getPointeeType(); 2580 else if (const BlockPointerType *FromBlockPtr = 2581 FromType->getAs<BlockPointerType>()) 2582 FromPointeeType = FromBlockPtr->getPointeeType(); 2583 else 2584 return false; 2585 2586 // If we have pointers to pointers, recursively check whether this 2587 // is an Objective-C conversion. 2588 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2589 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2590 IncompatibleObjC)) { 2591 // We always complain about this conversion. 2592 IncompatibleObjC = true; 2593 ConvertedType = Context.getPointerType(ConvertedType); 2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2595 return true; 2596 } 2597 // Allow conversion of pointee being objective-c pointer to another one; 2598 // as in I* to id. 2599 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2600 ToPointeeType->getAs<ObjCObjectPointerType>() && 2601 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2602 IncompatibleObjC)) { 2603 2604 ConvertedType = Context.getPointerType(ConvertedType); 2605 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2606 return true; 2607 } 2608 2609 // If we have pointers to functions or blocks, check whether the only 2610 // differences in the argument and result types are in Objective-C 2611 // pointer conversions. If so, we permit the conversion (but 2612 // complain about it). 2613 const FunctionProtoType *FromFunctionType 2614 = FromPointeeType->getAs<FunctionProtoType>(); 2615 const FunctionProtoType *ToFunctionType 2616 = ToPointeeType->getAs<FunctionProtoType>(); 2617 if (FromFunctionType && ToFunctionType) { 2618 // If the function types are exactly the same, this isn't an 2619 // Objective-C pointer conversion. 2620 if (Context.getCanonicalType(FromPointeeType) 2621 == Context.getCanonicalType(ToPointeeType)) 2622 return false; 2623 2624 // Perform the quick checks that will tell us whether these 2625 // function types are obviously different. 2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2628 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2629 return false; 2630 2631 bool HasObjCConversion = false; 2632 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2633 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2634 // Okay, the types match exactly. Nothing to do. 2635 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2636 ToFunctionType->getReturnType(), 2637 ConvertedType, IncompatibleObjC)) { 2638 // Okay, we have an Objective-C pointer conversion. 2639 HasObjCConversion = true; 2640 } else { 2641 // Function types are too different. Abort. 2642 return false; 2643 } 2644 2645 // Check argument types. 2646 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2647 ArgIdx != NumArgs; ++ArgIdx) { 2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2650 if (Context.getCanonicalType(FromArgType) 2651 == Context.getCanonicalType(ToArgType)) { 2652 // Okay, the types match exactly. Nothing to do. 2653 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2654 ConvertedType, IncompatibleObjC)) { 2655 // Okay, we have an Objective-C pointer conversion. 2656 HasObjCConversion = true; 2657 } else { 2658 // Argument types are too different. Abort. 2659 return false; 2660 } 2661 } 2662 2663 if (HasObjCConversion) { 2664 // We had an Objective-C conversion. Allow this pointer 2665 // conversion, but complain about it. 2666 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2667 IncompatibleObjC = true; 2668 return true; 2669 } 2670 } 2671 2672 return false; 2673 } 2674 2675 /// Determine whether this is an Objective-C writeback conversion, 2676 /// used for parameter passing when performing automatic reference counting. 2677 /// 2678 /// \param FromType The type we're converting form. 2679 /// 2680 /// \param ToType The type we're converting to. 2681 /// 2682 /// \param ConvertedType The type that will be produced after applying 2683 /// this conversion. 2684 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2685 QualType &ConvertedType) { 2686 if (!getLangOpts().ObjCAutoRefCount || 2687 Context.hasSameUnqualifiedType(FromType, ToType)) 2688 return false; 2689 2690 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2691 QualType ToPointee; 2692 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2693 ToPointee = ToPointer->getPointeeType(); 2694 else 2695 return false; 2696 2697 Qualifiers ToQuals = ToPointee.getQualifiers(); 2698 if (!ToPointee->isObjCLifetimeType() || 2699 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2700 !ToQuals.withoutObjCLifetime().empty()) 2701 return false; 2702 2703 // Argument must be a pointer to __strong to __weak. 2704 QualType FromPointee; 2705 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2706 FromPointee = FromPointer->getPointeeType(); 2707 else 2708 return false; 2709 2710 Qualifiers FromQuals = FromPointee.getQualifiers(); 2711 if (!FromPointee->isObjCLifetimeType() || 2712 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2713 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2714 return false; 2715 2716 // Make sure that we have compatible qualifiers. 2717 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2718 if (!ToQuals.compatiblyIncludes(FromQuals)) 2719 return false; 2720 2721 // Remove qualifiers from the pointee type we're converting from; they 2722 // aren't used in the compatibility check belong, and we'll be adding back 2723 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2724 FromPointee = FromPointee.getUnqualifiedType(); 2725 2726 // The unqualified form of the pointee types must be compatible. 2727 ToPointee = ToPointee.getUnqualifiedType(); 2728 bool IncompatibleObjC; 2729 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2730 FromPointee = ToPointee; 2731 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2732 IncompatibleObjC)) 2733 return false; 2734 2735 /// Construct the type we're converting to, which is a pointer to 2736 /// __autoreleasing pointee. 2737 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2738 ConvertedType = Context.getPointerType(FromPointee); 2739 return true; 2740 } 2741 2742 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2743 QualType& ConvertedType) { 2744 QualType ToPointeeType; 2745 if (const BlockPointerType *ToBlockPtr = 2746 ToType->getAs<BlockPointerType>()) 2747 ToPointeeType = ToBlockPtr->getPointeeType(); 2748 else 2749 return false; 2750 2751 QualType FromPointeeType; 2752 if (const BlockPointerType *FromBlockPtr = 2753 FromType->getAs<BlockPointerType>()) 2754 FromPointeeType = FromBlockPtr->getPointeeType(); 2755 else 2756 return false; 2757 // We have pointer to blocks, check whether the only 2758 // differences in the argument and result types are in Objective-C 2759 // pointer conversions. If so, we permit the conversion. 2760 2761 const FunctionProtoType *FromFunctionType 2762 = FromPointeeType->getAs<FunctionProtoType>(); 2763 const FunctionProtoType *ToFunctionType 2764 = ToPointeeType->getAs<FunctionProtoType>(); 2765 2766 if (!FromFunctionType || !ToFunctionType) 2767 return false; 2768 2769 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2770 return true; 2771 2772 // Perform the quick checks that will tell us whether these 2773 // function types are obviously different. 2774 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2775 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2776 return false; 2777 2778 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2779 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2780 if (FromEInfo != ToEInfo) 2781 return false; 2782 2783 bool IncompatibleObjC = false; 2784 if (Context.hasSameType(FromFunctionType->getReturnType(), 2785 ToFunctionType->getReturnType())) { 2786 // Okay, the types match exactly. Nothing to do. 2787 } else { 2788 QualType RHS = FromFunctionType->getReturnType(); 2789 QualType LHS = ToFunctionType->getReturnType(); 2790 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2791 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2792 LHS = LHS.getUnqualifiedType(); 2793 2794 if (Context.hasSameType(RHS,LHS)) { 2795 // OK exact match. 2796 } else if (isObjCPointerConversion(RHS, LHS, 2797 ConvertedType, IncompatibleObjC)) { 2798 if (IncompatibleObjC) 2799 return false; 2800 // Okay, we have an Objective-C pointer conversion. 2801 } 2802 else 2803 return false; 2804 } 2805 2806 // Check argument types. 2807 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2808 ArgIdx != NumArgs; ++ArgIdx) { 2809 IncompatibleObjC = false; 2810 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2811 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2812 if (Context.hasSameType(FromArgType, ToArgType)) { 2813 // Okay, the types match exactly. Nothing to do. 2814 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2815 ConvertedType, IncompatibleObjC)) { 2816 if (IncompatibleObjC) 2817 return false; 2818 // Okay, we have an Objective-C pointer conversion. 2819 } else 2820 // Argument types are too different. Abort. 2821 return false; 2822 } 2823 2824 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2825 bool CanUseToFPT, CanUseFromFPT; 2826 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2827 CanUseToFPT, CanUseFromFPT, 2828 NewParamInfos)) 2829 return false; 2830 2831 ConvertedType = ToType; 2832 return true; 2833 } 2834 2835 enum { 2836 ft_default, 2837 ft_different_class, 2838 ft_parameter_arity, 2839 ft_parameter_mismatch, 2840 ft_return_type, 2841 ft_qualifer_mismatch, 2842 ft_noexcept 2843 }; 2844 2845 /// Attempts to get the FunctionProtoType from a Type. Handles 2846 /// MemberFunctionPointers properly. 2847 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2848 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2849 return FPT; 2850 2851 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2852 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2853 2854 return nullptr; 2855 } 2856 2857 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2858 /// function types. Catches different number of parameter, mismatch in 2859 /// parameter types, and different return types. 2860 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2861 QualType FromType, QualType ToType) { 2862 // If either type is not valid, include no extra info. 2863 if (FromType.isNull() || ToType.isNull()) { 2864 PDiag << ft_default; 2865 return; 2866 } 2867 2868 // Get the function type from the pointers. 2869 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2870 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2871 *ToMember = ToType->castAs<MemberPointerType>(); 2872 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2873 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2874 << QualType(FromMember->getClass(), 0); 2875 return; 2876 } 2877 FromType = FromMember->getPointeeType(); 2878 ToType = ToMember->getPointeeType(); 2879 } 2880 2881 if (FromType->isPointerType()) 2882 FromType = FromType->getPointeeType(); 2883 if (ToType->isPointerType()) 2884 ToType = ToType->getPointeeType(); 2885 2886 // Remove references. 2887 FromType = FromType.getNonReferenceType(); 2888 ToType = ToType.getNonReferenceType(); 2889 2890 // Don't print extra info for non-specialized template functions. 2891 if (FromType->isInstantiationDependentType() && 2892 !FromType->getAs<TemplateSpecializationType>()) { 2893 PDiag << ft_default; 2894 return; 2895 } 2896 2897 // No extra info for same types. 2898 if (Context.hasSameType(FromType, ToType)) { 2899 PDiag << ft_default; 2900 return; 2901 } 2902 2903 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2904 *ToFunction = tryGetFunctionProtoType(ToType); 2905 2906 // Both types need to be function types. 2907 if (!FromFunction || !ToFunction) { 2908 PDiag << ft_default; 2909 return; 2910 } 2911 2912 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2913 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2914 << FromFunction->getNumParams(); 2915 return; 2916 } 2917 2918 // Handle different parameter types. 2919 unsigned ArgPos; 2920 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2921 PDiag << ft_parameter_mismatch << ArgPos + 1 2922 << ToFunction->getParamType(ArgPos) 2923 << FromFunction->getParamType(ArgPos); 2924 return; 2925 } 2926 2927 // Handle different return type. 2928 if (!Context.hasSameType(FromFunction->getReturnType(), 2929 ToFunction->getReturnType())) { 2930 PDiag << ft_return_type << ToFunction->getReturnType() 2931 << FromFunction->getReturnType(); 2932 return; 2933 } 2934 2935 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2936 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2937 << FromFunction->getMethodQuals(); 2938 return; 2939 } 2940 2941 // Handle exception specification differences on canonical type (in C++17 2942 // onwards). 2943 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2944 ->isNothrow() != 2945 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2946 ->isNothrow()) { 2947 PDiag << ft_noexcept; 2948 return; 2949 } 2950 2951 // Unable to find a difference, so add no extra info. 2952 PDiag << ft_default; 2953 } 2954 2955 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2956 /// for equality of their argument types. Caller has already checked that 2957 /// they have same number of arguments. If the parameters are different, 2958 /// ArgPos will have the parameter index of the first different parameter. 2959 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2960 const FunctionProtoType *NewType, 2961 unsigned *ArgPos) { 2962 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2963 N = NewType->param_type_begin(), 2964 E = OldType->param_type_end(); 2965 O && (O != E); ++O, ++N) { 2966 // Ignore address spaces in pointee type. This is to disallow overloading 2967 // on __ptr32/__ptr64 address spaces. 2968 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2969 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2970 2971 if (!Context.hasSameType(Old, New)) { 2972 if (ArgPos) 2973 *ArgPos = O - OldType->param_type_begin(); 2974 return false; 2975 } 2976 } 2977 return true; 2978 } 2979 2980 /// CheckPointerConversion - Check the pointer conversion from the 2981 /// expression From to the type ToType. This routine checks for 2982 /// ambiguous or inaccessible derived-to-base pointer 2983 /// conversions for which IsPointerConversion has already returned 2984 /// true. It returns true and produces a diagnostic if there was an 2985 /// error, or returns false otherwise. 2986 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2987 CastKind &Kind, 2988 CXXCastPath& BasePath, 2989 bool IgnoreBaseAccess, 2990 bool Diagnose) { 2991 QualType FromType = From->getType(); 2992 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2993 2994 Kind = CK_BitCast; 2995 2996 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2997 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2998 Expr::NPCK_ZeroExpression) { 2999 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3000 DiagRuntimeBehavior(From->getExprLoc(), From, 3001 PDiag(diag::warn_impcast_bool_to_null_pointer) 3002 << ToType << From->getSourceRange()); 3003 else if (!isUnevaluatedContext()) 3004 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3005 << ToType << From->getSourceRange(); 3006 } 3007 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3008 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3009 QualType FromPointeeType = FromPtrType->getPointeeType(), 3010 ToPointeeType = ToPtrType->getPointeeType(); 3011 3012 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3013 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3014 // We must have a derived-to-base conversion. Check an 3015 // ambiguous or inaccessible conversion. 3016 unsigned InaccessibleID = 0; 3017 unsigned AmbiguousID = 0; 3018 if (Diagnose) { 3019 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3020 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3021 } 3022 if (CheckDerivedToBaseConversion( 3023 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3024 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3025 &BasePath, IgnoreBaseAccess)) 3026 return true; 3027 3028 // The conversion was successful. 3029 Kind = CK_DerivedToBase; 3030 } 3031 3032 if (Diagnose && !IsCStyleOrFunctionalCast && 3033 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3034 assert(getLangOpts().MSVCCompat && 3035 "this should only be possible with MSVCCompat!"); 3036 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3037 << From->getSourceRange(); 3038 } 3039 } 3040 } else if (const ObjCObjectPointerType *ToPtrType = 3041 ToType->getAs<ObjCObjectPointerType>()) { 3042 if (const ObjCObjectPointerType *FromPtrType = 3043 FromType->getAs<ObjCObjectPointerType>()) { 3044 // Objective-C++ conversions are always okay. 3045 // FIXME: We should have a different class of conversions for the 3046 // Objective-C++ implicit conversions. 3047 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3048 return false; 3049 } else if (FromType->isBlockPointerType()) { 3050 Kind = CK_BlockPointerToObjCPointerCast; 3051 } else { 3052 Kind = CK_CPointerToObjCPointerCast; 3053 } 3054 } else if (ToType->isBlockPointerType()) { 3055 if (!FromType->isBlockPointerType()) 3056 Kind = CK_AnyPointerToBlockPointerCast; 3057 } 3058 3059 // We shouldn't fall into this case unless it's valid for other 3060 // reasons. 3061 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3062 Kind = CK_NullToPointer; 3063 3064 return false; 3065 } 3066 3067 /// IsMemberPointerConversion - Determines whether the conversion of the 3068 /// expression From, which has the (possibly adjusted) type FromType, can be 3069 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3070 /// If so, returns true and places the converted type (that might differ from 3071 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3072 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3073 QualType ToType, 3074 bool InOverloadResolution, 3075 QualType &ConvertedType) { 3076 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3077 if (!ToTypePtr) 3078 return false; 3079 3080 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3081 if (From->isNullPointerConstant(Context, 3082 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3083 : Expr::NPC_ValueDependentIsNull)) { 3084 ConvertedType = ToType; 3085 return true; 3086 } 3087 3088 // Otherwise, both types have to be member pointers. 3089 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3090 if (!FromTypePtr) 3091 return false; 3092 3093 // A pointer to member of B can be converted to a pointer to member of D, 3094 // where D is derived from B (C++ 4.11p2). 3095 QualType FromClass(FromTypePtr->getClass(), 0); 3096 QualType ToClass(ToTypePtr->getClass(), 0); 3097 3098 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3099 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3100 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3101 ToClass.getTypePtr()); 3102 return true; 3103 } 3104 3105 return false; 3106 } 3107 3108 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3109 /// expression From to the type ToType. This routine checks for ambiguous or 3110 /// virtual or inaccessible base-to-derived member pointer conversions 3111 /// for which IsMemberPointerConversion has already returned true. It returns 3112 /// true and produces a diagnostic if there was an error, or returns false 3113 /// otherwise. 3114 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3115 CastKind &Kind, 3116 CXXCastPath &BasePath, 3117 bool IgnoreBaseAccess) { 3118 QualType FromType = From->getType(); 3119 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3120 if (!FromPtrType) { 3121 // This must be a null pointer to member pointer conversion 3122 assert(From->isNullPointerConstant(Context, 3123 Expr::NPC_ValueDependentIsNull) && 3124 "Expr must be null pointer constant!"); 3125 Kind = CK_NullToMemberPointer; 3126 return false; 3127 } 3128 3129 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3130 assert(ToPtrType && "No member pointer cast has a target type " 3131 "that is not a member pointer."); 3132 3133 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3134 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3135 3136 // FIXME: What about dependent types? 3137 assert(FromClass->isRecordType() && "Pointer into non-class."); 3138 assert(ToClass->isRecordType() && "Pointer into non-class."); 3139 3140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3141 /*DetectVirtual=*/true); 3142 bool DerivationOkay = 3143 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3144 assert(DerivationOkay && 3145 "Should not have been called if derivation isn't OK."); 3146 (void)DerivationOkay; 3147 3148 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3149 getUnqualifiedType())) { 3150 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3151 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3152 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3153 return true; 3154 } 3155 3156 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3157 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3158 << FromClass << ToClass << QualType(VBase, 0) 3159 << From->getSourceRange(); 3160 return true; 3161 } 3162 3163 if (!IgnoreBaseAccess) 3164 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3165 Paths.front(), 3166 diag::err_downcast_from_inaccessible_base); 3167 3168 // Must be a base to derived member conversion. 3169 BuildBasePathArray(Paths, BasePath); 3170 Kind = CK_BaseToDerivedMemberPointer; 3171 return false; 3172 } 3173 3174 /// Determine whether the lifetime conversion between the two given 3175 /// qualifiers sets is nontrivial. 3176 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3177 Qualifiers ToQuals) { 3178 // Converting anything to const __unsafe_unretained is trivial. 3179 if (ToQuals.hasConst() && 3180 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3181 return false; 3182 3183 return true; 3184 } 3185 3186 /// Perform a single iteration of the loop for checking if a qualification 3187 /// conversion is valid. 3188 /// 3189 /// Specifically, check whether any change between the qualifiers of \p 3190 /// FromType and \p ToType is permissible, given knowledge about whether every 3191 /// outer layer is const-qualified. 3192 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3193 bool CStyle, bool IsTopLevel, 3194 bool &PreviousToQualsIncludeConst, 3195 bool &ObjCLifetimeConversion) { 3196 Qualifiers FromQuals = FromType.getQualifiers(); 3197 Qualifiers ToQuals = ToType.getQualifiers(); 3198 3199 // Ignore __unaligned qualifier if this type is void. 3200 if (ToType.getUnqualifiedType()->isVoidType()) 3201 FromQuals.removeUnaligned(); 3202 3203 // Objective-C ARC: 3204 // Check Objective-C lifetime conversions. 3205 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3206 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3207 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3208 ObjCLifetimeConversion = true; 3209 FromQuals.removeObjCLifetime(); 3210 ToQuals.removeObjCLifetime(); 3211 } else { 3212 // Qualification conversions cannot cast between different 3213 // Objective-C lifetime qualifiers. 3214 return false; 3215 } 3216 } 3217 3218 // Allow addition/removal of GC attributes but not changing GC attributes. 3219 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3220 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3221 FromQuals.removeObjCGCAttr(); 3222 ToQuals.removeObjCGCAttr(); 3223 } 3224 3225 // -- for every j > 0, if const is in cv 1,j then const is in cv 3226 // 2,j, and similarly for volatile. 3227 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3228 return false; 3229 3230 // If address spaces mismatch: 3231 // - in top level it is only valid to convert to addr space that is a 3232 // superset in all cases apart from C-style casts where we allow 3233 // conversions between overlapping address spaces. 3234 // - in non-top levels it is not a valid conversion. 3235 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3236 (!IsTopLevel || 3237 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3238 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3239 return false; 3240 3241 // -- if the cv 1,j and cv 2,j are different, then const is in 3242 // every cv for 0 < k < j. 3243 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3244 !PreviousToQualsIncludeConst) 3245 return false; 3246 3247 // Keep track of whether all prior cv-qualifiers in the "to" type 3248 // include const. 3249 PreviousToQualsIncludeConst = 3250 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3251 return true; 3252 } 3253 3254 /// IsQualificationConversion - Determines whether the conversion from 3255 /// an rvalue of type FromType to ToType is a qualification conversion 3256 /// (C++ 4.4). 3257 /// 3258 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3259 /// when the qualification conversion involves a change in the Objective-C 3260 /// object lifetime. 3261 bool 3262 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3263 bool CStyle, bool &ObjCLifetimeConversion) { 3264 FromType = Context.getCanonicalType(FromType); 3265 ToType = Context.getCanonicalType(ToType); 3266 ObjCLifetimeConversion = false; 3267 3268 // If FromType and ToType are the same type, this is not a 3269 // qualification conversion. 3270 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3271 return false; 3272 3273 // (C++ 4.4p4): 3274 // A conversion can add cv-qualifiers at levels other than the first 3275 // in multi-level pointers, subject to the following rules: [...] 3276 bool PreviousToQualsIncludeConst = true; 3277 bool UnwrappedAnyPointer = false; 3278 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3279 if (!isQualificationConversionStep( 3280 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3281 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3282 return false; 3283 UnwrappedAnyPointer = true; 3284 } 3285 3286 // We are left with FromType and ToType being the pointee types 3287 // after unwrapping the original FromType and ToType the same number 3288 // of times. If we unwrapped any pointers, and if FromType and 3289 // ToType have the same unqualified type (since we checked 3290 // qualifiers above), then this is a qualification conversion. 3291 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3292 } 3293 3294 /// - Determine whether this is a conversion from a scalar type to an 3295 /// atomic type. 3296 /// 3297 /// If successful, updates \c SCS's second and third steps in the conversion 3298 /// sequence to finish the conversion. 3299 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3300 bool InOverloadResolution, 3301 StandardConversionSequence &SCS, 3302 bool CStyle) { 3303 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3304 if (!ToAtomic) 3305 return false; 3306 3307 StandardConversionSequence InnerSCS; 3308 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3309 InOverloadResolution, InnerSCS, 3310 CStyle, /*AllowObjCWritebackConversion=*/false)) 3311 return false; 3312 3313 SCS.Second = InnerSCS.Second; 3314 SCS.setToType(1, InnerSCS.getToType(1)); 3315 SCS.Third = InnerSCS.Third; 3316 SCS.QualificationIncludesObjCLifetime 3317 = InnerSCS.QualificationIncludesObjCLifetime; 3318 SCS.setToType(2, InnerSCS.getToType(2)); 3319 return true; 3320 } 3321 3322 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3323 CXXConstructorDecl *Constructor, 3324 QualType Type) { 3325 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3326 if (CtorType->getNumParams() > 0) { 3327 QualType FirstArg = CtorType->getParamType(0); 3328 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3329 return true; 3330 } 3331 return false; 3332 } 3333 3334 static OverloadingResult 3335 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3336 CXXRecordDecl *To, 3337 UserDefinedConversionSequence &User, 3338 OverloadCandidateSet &CandidateSet, 3339 bool AllowExplicit) { 3340 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3341 for (auto *D : S.LookupConstructors(To)) { 3342 auto Info = getConstructorInfo(D); 3343 if (!Info) 3344 continue; 3345 3346 bool Usable = !Info.Constructor->isInvalidDecl() && 3347 S.isInitListConstructor(Info.Constructor); 3348 if (Usable) { 3349 bool SuppressUserConversions = false; 3350 if (Info.ConstructorTmpl) 3351 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3352 /*ExplicitArgs*/ nullptr, From, 3353 CandidateSet, SuppressUserConversions, 3354 /*PartialOverloading*/ false, 3355 AllowExplicit); 3356 else 3357 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3358 CandidateSet, SuppressUserConversions, 3359 /*PartialOverloading*/ false, AllowExplicit); 3360 } 3361 } 3362 3363 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3364 3365 OverloadCandidateSet::iterator Best; 3366 switch (auto Result = 3367 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3368 case OR_Deleted: 3369 case OR_Success: { 3370 // Record the standard conversion we used and the conversion function. 3371 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3372 QualType ThisType = Constructor->getThisType(); 3373 // Initializer lists don't have conversions as such. 3374 User.Before.setAsIdentityConversion(); 3375 User.HadMultipleCandidates = HadMultipleCandidates; 3376 User.ConversionFunction = Constructor; 3377 User.FoundConversionFunction = Best->FoundDecl; 3378 User.After.setAsIdentityConversion(); 3379 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3380 User.After.setAllToTypes(ToType); 3381 return Result; 3382 } 3383 3384 case OR_No_Viable_Function: 3385 return OR_No_Viable_Function; 3386 case OR_Ambiguous: 3387 return OR_Ambiguous; 3388 } 3389 3390 llvm_unreachable("Invalid OverloadResult!"); 3391 } 3392 3393 /// Determines whether there is a user-defined conversion sequence 3394 /// (C++ [over.ics.user]) that converts expression From to the type 3395 /// ToType. If such a conversion exists, User will contain the 3396 /// user-defined conversion sequence that performs such a conversion 3397 /// and this routine will return true. Otherwise, this routine returns 3398 /// false and User is unspecified. 3399 /// 3400 /// \param AllowExplicit true if the conversion should consider C++0x 3401 /// "explicit" conversion functions as well as non-explicit conversion 3402 /// functions (C++0x [class.conv.fct]p2). 3403 /// 3404 /// \param AllowObjCConversionOnExplicit true if the conversion should 3405 /// allow an extra Objective-C pointer conversion on uses of explicit 3406 /// constructors. Requires \c AllowExplicit to also be set. 3407 static OverloadingResult 3408 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3409 UserDefinedConversionSequence &User, 3410 OverloadCandidateSet &CandidateSet, 3411 AllowedExplicit AllowExplicit, 3412 bool AllowObjCConversionOnExplicit) { 3413 assert(AllowExplicit != AllowedExplicit::None || 3414 !AllowObjCConversionOnExplicit); 3415 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3416 3417 // Whether we will only visit constructors. 3418 bool ConstructorsOnly = false; 3419 3420 // If the type we are conversion to is a class type, enumerate its 3421 // constructors. 3422 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3423 // C++ [over.match.ctor]p1: 3424 // When objects of class type are direct-initialized (8.5), or 3425 // copy-initialized from an expression of the same or a 3426 // derived class type (8.5), overload resolution selects the 3427 // constructor. [...] For copy-initialization, the candidate 3428 // functions are all the converting constructors (12.3.1) of 3429 // that class. The argument list is the expression-list within 3430 // the parentheses of the initializer. 3431 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3432 (From->getType()->getAs<RecordType>() && 3433 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3434 ConstructorsOnly = true; 3435 3436 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3437 // We're not going to find any constructors. 3438 } else if (CXXRecordDecl *ToRecordDecl 3439 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3440 3441 Expr **Args = &From; 3442 unsigned NumArgs = 1; 3443 bool ListInitializing = false; 3444 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3445 // But first, see if there is an init-list-constructor that will work. 3446 OverloadingResult Result = IsInitializerListConstructorConversion( 3447 S, From, ToType, ToRecordDecl, User, CandidateSet, 3448 AllowExplicit == AllowedExplicit::All); 3449 if (Result != OR_No_Viable_Function) 3450 return Result; 3451 // Never mind. 3452 CandidateSet.clear( 3453 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3454 3455 // If we're list-initializing, we pass the individual elements as 3456 // arguments, not the entire list. 3457 Args = InitList->getInits(); 3458 NumArgs = InitList->getNumInits(); 3459 ListInitializing = true; 3460 } 3461 3462 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3463 auto Info = getConstructorInfo(D); 3464 if (!Info) 3465 continue; 3466 3467 bool Usable = !Info.Constructor->isInvalidDecl(); 3468 if (!ListInitializing) 3469 Usable = Usable && Info.Constructor->isConvertingConstructor( 3470 /*AllowExplicit*/ true); 3471 if (Usable) { 3472 bool SuppressUserConversions = !ConstructorsOnly; 3473 // C++20 [over.best.ics.general]/4.5: 3474 // if the target is the first parameter of a constructor [of class 3475 // X] and the constructor [...] is a candidate by [...] the second 3476 // phase of [over.match.list] when the initializer list has exactly 3477 // one element that is itself an initializer list, [...] and the 3478 // conversion is to X or reference to cv X, user-defined conversion 3479 // sequences are not cnosidered. 3480 if (SuppressUserConversions && ListInitializing) { 3481 SuppressUserConversions = 3482 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3483 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3484 ToType); 3485 } 3486 if (Info.ConstructorTmpl) 3487 S.AddTemplateOverloadCandidate( 3488 Info.ConstructorTmpl, Info.FoundDecl, 3489 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3490 CandidateSet, SuppressUserConversions, 3491 /*PartialOverloading*/ false, 3492 AllowExplicit == AllowedExplicit::All); 3493 else 3494 // Allow one user-defined conversion when user specifies a 3495 // From->ToType conversion via an static cast (c-style, etc). 3496 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3497 llvm::makeArrayRef(Args, NumArgs), 3498 CandidateSet, SuppressUserConversions, 3499 /*PartialOverloading*/ false, 3500 AllowExplicit == AllowedExplicit::All); 3501 } 3502 } 3503 } 3504 } 3505 3506 // Enumerate conversion functions, if we're allowed to. 3507 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3508 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3509 // No conversion functions from incomplete types. 3510 } else if (const RecordType *FromRecordType = 3511 From->getType()->getAs<RecordType>()) { 3512 if (CXXRecordDecl *FromRecordDecl 3513 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3514 // Add all of the conversion functions as candidates. 3515 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3516 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3517 DeclAccessPair FoundDecl = I.getPair(); 3518 NamedDecl *D = FoundDecl.getDecl(); 3519 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3520 if (isa<UsingShadowDecl>(D)) 3521 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3522 3523 CXXConversionDecl *Conv; 3524 FunctionTemplateDecl *ConvTemplate; 3525 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3526 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3527 else 3528 Conv = cast<CXXConversionDecl>(D); 3529 3530 if (ConvTemplate) 3531 S.AddTemplateConversionCandidate( 3532 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3533 CandidateSet, AllowObjCConversionOnExplicit, 3534 AllowExplicit != AllowedExplicit::None); 3535 else 3536 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3537 CandidateSet, AllowObjCConversionOnExplicit, 3538 AllowExplicit != AllowedExplicit::None); 3539 } 3540 } 3541 } 3542 3543 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3544 3545 OverloadCandidateSet::iterator Best; 3546 switch (auto Result = 3547 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3548 case OR_Success: 3549 case OR_Deleted: 3550 // Record the standard conversion we used and the conversion function. 3551 if (CXXConstructorDecl *Constructor 3552 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3553 // C++ [over.ics.user]p1: 3554 // If the user-defined conversion is specified by a 3555 // constructor (12.3.1), the initial standard conversion 3556 // sequence converts the source type to the type required by 3557 // the argument of the constructor. 3558 // 3559 QualType ThisType = Constructor->getThisType(); 3560 if (isa<InitListExpr>(From)) { 3561 // Initializer lists don't have conversions as such. 3562 User.Before.setAsIdentityConversion(); 3563 } else { 3564 if (Best->Conversions[0].isEllipsis()) 3565 User.EllipsisConversion = true; 3566 else { 3567 User.Before = Best->Conversions[0].Standard; 3568 User.EllipsisConversion = false; 3569 } 3570 } 3571 User.HadMultipleCandidates = HadMultipleCandidates; 3572 User.ConversionFunction = Constructor; 3573 User.FoundConversionFunction = Best->FoundDecl; 3574 User.After.setAsIdentityConversion(); 3575 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3576 User.After.setAllToTypes(ToType); 3577 return Result; 3578 } 3579 if (CXXConversionDecl *Conversion 3580 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3581 // C++ [over.ics.user]p1: 3582 // 3583 // [...] If the user-defined conversion is specified by a 3584 // conversion function (12.3.2), the initial standard 3585 // conversion sequence converts the source type to the 3586 // implicit object parameter of the conversion function. 3587 User.Before = Best->Conversions[0].Standard; 3588 User.HadMultipleCandidates = HadMultipleCandidates; 3589 User.ConversionFunction = Conversion; 3590 User.FoundConversionFunction = Best->FoundDecl; 3591 User.EllipsisConversion = false; 3592 3593 // C++ [over.ics.user]p2: 3594 // The second standard conversion sequence converts the 3595 // result of the user-defined conversion to the target type 3596 // for the sequence. Since an implicit conversion sequence 3597 // is an initialization, the special rules for 3598 // initialization by user-defined conversion apply when 3599 // selecting the best user-defined conversion for a 3600 // user-defined conversion sequence (see 13.3.3 and 3601 // 13.3.3.1). 3602 User.After = Best->FinalConversion; 3603 return Result; 3604 } 3605 llvm_unreachable("Not a constructor or conversion function?"); 3606 3607 case OR_No_Viable_Function: 3608 return OR_No_Viable_Function; 3609 3610 case OR_Ambiguous: 3611 return OR_Ambiguous; 3612 } 3613 3614 llvm_unreachable("Invalid OverloadResult!"); 3615 } 3616 3617 bool 3618 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3619 ImplicitConversionSequence ICS; 3620 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3621 OverloadCandidateSet::CSK_Normal); 3622 OverloadingResult OvResult = 3623 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3624 CandidateSet, AllowedExplicit::None, false); 3625 3626 if (!(OvResult == OR_Ambiguous || 3627 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3628 return false; 3629 3630 auto Cands = CandidateSet.CompleteCandidates( 3631 *this, 3632 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3633 From); 3634 if (OvResult == OR_Ambiguous) 3635 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3636 << From->getType() << ToType << From->getSourceRange(); 3637 else { // OR_No_Viable_Function && !CandidateSet.empty() 3638 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3639 diag::err_typecheck_nonviable_condition_incomplete, 3640 From->getType(), From->getSourceRange())) 3641 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3642 << false << From->getType() << From->getSourceRange() << ToType; 3643 } 3644 3645 CandidateSet.NoteCandidates( 3646 *this, From, Cands); 3647 return true; 3648 } 3649 3650 // Helper for compareConversionFunctions that gets the FunctionType that the 3651 // conversion-operator return value 'points' to, or nullptr. 3652 static const FunctionType * 3653 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3654 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3655 const PointerType *RetPtrTy = 3656 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3657 3658 if (!RetPtrTy) 3659 return nullptr; 3660 3661 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3662 } 3663 3664 /// Compare the user-defined conversion functions or constructors 3665 /// of two user-defined conversion sequences to determine whether any ordering 3666 /// is possible. 3667 static ImplicitConversionSequence::CompareKind 3668 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3669 FunctionDecl *Function2) { 3670 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3671 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3672 if (!Conv1 || !Conv2) 3673 return ImplicitConversionSequence::Indistinguishable; 3674 3675 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3676 return ImplicitConversionSequence::Indistinguishable; 3677 3678 // Objective-C++: 3679 // If both conversion functions are implicitly-declared conversions from 3680 // a lambda closure type to a function pointer and a block pointer, 3681 // respectively, always prefer the conversion to a function pointer, 3682 // because the function pointer is more lightweight and is more likely 3683 // to keep code working. 3684 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3685 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3686 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3687 if (Block1 != Block2) 3688 return Block1 ? ImplicitConversionSequence::Worse 3689 : ImplicitConversionSequence::Better; 3690 } 3691 3692 // In order to support multiple calling conventions for the lambda conversion 3693 // operator (such as when the free and member function calling convention is 3694 // different), prefer the 'free' mechanism, followed by the calling-convention 3695 // of operator(). The latter is in place to support the MSVC-like solution of 3696 // defining ALL of the possible conversions in regards to calling-convention. 3697 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3698 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3699 3700 if (Conv1FuncRet && Conv2FuncRet && 3701 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3702 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3703 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3704 3705 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3706 const FunctionProtoType *CallOpProto = 3707 CallOp->getType()->getAs<FunctionProtoType>(); 3708 3709 CallingConv CallOpCC = 3710 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3711 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3712 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3713 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3714 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3715 3716 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3717 for (CallingConv CC : PrefOrder) { 3718 if (Conv1CC == CC) 3719 return ImplicitConversionSequence::Better; 3720 if (Conv2CC == CC) 3721 return ImplicitConversionSequence::Worse; 3722 } 3723 } 3724 3725 return ImplicitConversionSequence::Indistinguishable; 3726 } 3727 3728 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3729 const ImplicitConversionSequence &ICS) { 3730 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3731 (ICS.isUserDefined() && 3732 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3733 } 3734 3735 /// CompareImplicitConversionSequences - Compare two implicit 3736 /// conversion sequences to determine whether one is better than the 3737 /// other or if they are indistinguishable (C++ 13.3.3.2). 3738 static ImplicitConversionSequence::CompareKind 3739 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3740 const ImplicitConversionSequence& ICS1, 3741 const ImplicitConversionSequence& ICS2) 3742 { 3743 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3744 // conversion sequences (as defined in 13.3.3.1) 3745 // -- a standard conversion sequence (13.3.3.1.1) is a better 3746 // conversion sequence than a user-defined conversion sequence or 3747 // an ellipsis conversion sequence, and 3748 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3749 // conversion sequence than an ellipsis conversion sequence 3750 // (13.3.3.1.3). 3751 // 3752 // C++0x [over.best.ics]p10: 3753 // For the purpose of ranking implicit conversion sequences as 3754 // described in 13.3.3.2, the ambiguous conversion sequence is 3755 // treated as a user-defined sequence that is indistinguishable 3756 // from any other user-defined conversion sequence. 3757 3758 // String literal to 'char *' conversion has been deprecated in C++03. It has 3759 // been removed from C++11. We still accept this conversion, if it happens at 3760 // the best viable function. Otherwise, this conversion is considered worse 3761 // than ellipsis conversion. Consider this as an extension; this is not in the 3762 // standard. For example: 3763 // 3764 // int &f(...); // #1 3765 // void f(char*); // #2 3766 // void g() { int &r = f("foo"); } 3767 // 3768 // In C++03, we pick #2 as the best viable function. 3769 // In C++11, we pick #1 as the best viable function, because ellipsis 3770 // conversion is better than string-literal to char* conversion (since there 3771 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3772 // convert arguments, #2 would be the best viable function in C++11. 3773 // If the best viable function has this conversion, a warning will be issued 3774 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3775 3776 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3777 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3778 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3779 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3780 ? ImplicitConversionSequence::Worse 3781 : ImplicitConversionSequence::Better; 3782 3783 if (ICS1.getKindRank() < ICS2.getKindRank()) 3784 return ImplicitConversionSequence::Better; 3785 if (ICS2.getKindRank() < ICS1.getKindRank()) 3786 return ImplicitConversionSequence::Worse; 3787 3788 // The following checks require both conversion sequences to be of 3789 // the same kind. 3790 if (ICS1.getKind() != ICS2.getKind()) 3791 return ImplicitConversionSequence::Indistinguishable; 3792 3793 ImplicitConversionSequence::CompareKind Result = 3794 ImplicitConversionSequence::Indistinguishable; 3795 3796 // Two implicit conversion sequences of the same form are 3797 // indistinguishable conversion sequences unless one of the 3798 // following rules apply: (C++ 13.3.3.2p3): 3799 3800 // List-initialization sequence L1 is a better conversion sequence than 3801 // list-initialization sequence L2 if: 3802 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3803 // if not that, 3804 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3805 // and N1 is smaller than N2., 3806 // even if one of the other rules in this paragraph would otherwise apply. 3807 if (!ICS1.isBad()) { 3808 if (ICS1.isStdInitializerListElement() && 3809 !ICS2.isStdInitializerListElement()) 3810 return ImplicitConversionSequence::Better; 3811 if (!ICS1.isStdInitializerListElement() && 3812 ICS2.isStdInitializerListElement()) 3813 return ImplicitConversionSequence::Worse; 3814 } 3815 3816 if (ICS1.isStandard()) 3817 // Standard conversion sequence S1 is a better conversion sequence than 3818 // standard conversion sequence S2 if [...] 3819 Result = CompareStandardConversionSequences(S, Loc, 3820 ICS1.Standard, ICS2.Standard); 3821 else if (ICS1.isUserDefined()) { 3822 // User-defined conversion sequence U1 is a better conversion 3823 // sequence than another user-defined conversion sequence U2 if 3824 // they contain the same user-defined conversion function or 3825 // constructor and if the second standard conversion sequence of 3826 // U1 is better than the second standard conversion sequence of 3827 // U2 (C++ 13.3.3.2p3). 3828 if (ICS1.UserDefined.ConversionFunction == 3829 ICS2.UserDefined.ConversionFunction) 3830 Result = CompareStandardConversionSequences(S, Loc, 3831 ICS1.UserDefined.After, 3832 ICS2.UserDefined.After); 3833 else 3834 Result = compareConversionFunctions(S, 3835 ICS1.UserDefined.ConversionFunction, 3836 ICS2.UserDefined.ConversionFunction); 3837 } 3838 3839 return Result; 3840 } 3841 3842 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3843 // determine if one is a proper subset of the other. 3844 static ImplicitConversionSequence::CompareKind 3845 compareStandardConversionSubsets(ASTContext &Context, 3846 const StandardConversionSequence& SCS1, 3847 const StandardConversionSequence& SCS2) { 3848 ImplicitConversionSequence::CompareKind Result 3849 = ImplicitConversionSequence::Indistinguishable; 3850 3851 // the identity conversion sequence is considered to be a subsequence of 3852 // any non-identity conversion sequence 3853 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3854 return ImplicitConversionSequence::Better; 3855 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3856 return ImplicitConversionSequence::Worse; 3857 3858 if (SCS1.Second != SCS2.Second) { 3859 if (SCS1.Second == ICK_Identity) 3860 Result = ImplicitConversionSequence::Better; 3861 else if (SCS2.Second == ICK_Identity) 3862 Result = ImplicitConversionSequence::Worse; 3863 else 3864 return ImplicitConversionSequence::Indistinguishable; 3865 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3866 return ImplicitConversionSequence::Indistinguishable; 3867 3868 if (SCS1.Third == SCS2.Third) { 3869 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3870 : ImplicitConversionSequence::Indistinguishable; 3871 } 3872 3873 if (SCS1.Third == ICK_Identity) 3874 return Result == ImplicitConversionSequence::Worse 3875 ? ImplicitConversionSequence::Indistinguishable 3876 : ImplicitConversionSequence::Better; 3877 3878 if (SCS2.Third == ICK_Identity) 3879 return Result == ImplicitConversionSequence::Better 3880 ? ImplicitConversionSequence::Indistinguishable 3881 : ImplicitConversionSequence::Worse; 3882 3883 return ImplicitConversionSequence::Indistinguishable; 3884 } 3885 3886 /// Determine whether one of the given reference bindings is better 3887 /// than the other based on what kind of bindings they are. 3888 static bool 3889 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3890 const StandardConversionSequence &SCS2) { 3891 // C++0x [over.ics.rank]p3b4: 3892 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3893 // implicit object parameter of a non-static member function declared 3894 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3895 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3896 // lvalue reference to a function lvalue and S2 binds an rvalue 3897 // reference*. 3898 // 3899 // FIXME: Rvalue references. We're going rogue with the above edits, 3900 // because the semantics in the current C++0x working paper (N3225 at the 3901 // time of this writing) break the standard definition of std::forward 3902 // and std::reference_wrapper when dealing with references to functions. 3903 // Proposed wording changes submitted to CWG for consideration. 3904 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3905 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3906 return false; 3907 3908 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3909 SCS2.IsLvalueReference) || 3910 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3911 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3912 } 3913 3914 enum class FixedEnumPromotion { 3915 None, 3916 ToUnderlyingType, 3917 ToPromotedUnderlyingType 3918 }; 3919 3920 /// Returns kind of fixed enum promotion the \a SCS uses. 3921 static FixedEnumPromotion 3922 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3923 3924 if (SCS.Second != ICK_Integral_Promotion) 3925 return FixedEnumPromotion::None; 3926 3927 QualType FromType = SCS.getFromType(); 3928 if (!FromType->isEnumeralType()) 3929 return FixedEnumPromotion::None; 3930 3931 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 3932 if (!Enum->isFixed()) 3933 return FixedEnumPromotion::None; 3934 3935 QualType UnderlyingType = Enum->getIntegerType(); 3936 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3937 return FixedEnumPromotion::ToUnderlyingType; 3938 3939 return FixedEnumPromotion::ToPromotedUnderlyingType; 3940 } 3941 3942 /// CompareStandardConversionSequences - Compare two standard 3943 /// conversion sequences to determine whether one is better than the 3944 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3945 static ImplicitConversionSequence::CompareKind 3946 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3947 const StandardConversionSequence& SCS1, 3948 const StandardConversionSequence& SCS2) 3949 { 3950 // Standard conversion sequence S1 is a better conversion sequence 3951 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3952 3953 // -- S1 is a proper subsequence of S2 (comparing the conversion 3954 // sequences in the canonical form defined by 13.3.3.1.1, 3955 // excluding any Lvalue Transformation; the identity conversion 3956 // sequence is considered to be a subsequence of any 3957 // non-identity conversion sequence) or, if not that, 3958 if (ImplicitConversionSequence::CompareKind CK 3959 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3960 return CK; 3961 3962 // -- the rank of S1 is better than the rank of S2 (by the rules 3963 // defined below), or, if not that, 3964 ImplicitConversionRank Rank1 = SCS1.getRank(); 3965 ImplicitConversionRank Rank2 = SCS2.getRank(); 3966 if (Rank1 < Rank2) 3967 return ImplicitConversionSequence::Better; 3968 else if (Rank2 < Rank1) 3969 return ImplicitConversionSequence::Worse; 3970 3971 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3972 // are indistinguishable unless one of the following rules 3973 // applies: 3974 3975 // A conversion that is not a conversion of a pointer, or 3976 // pointer to member, to bool is better than another conversion 3977 // that is such a conversion. 3978 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3979 return SCS2.isPointerConversionToBool() 3980 ? ImplicitConversionSequence::Better 3981 : ImplicitConversionSequence::Worse; 3982 3983 // C++14 [over.ics.rank]p4b2: 3984 // This is retroactively applied to C++11 by CWG 1601. 3985 // 3986 // A conversion that promotes an enumeration whose underlying type is fixed 3987 // to its underlying type is better than one that promotes to the promoted 3988 // underlying type, if the two are different. 3989 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3990 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3991 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3992 FEP1 != FEP2) 3993 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3994 ? ImplicitConversionSequence::Better 3995 : ImplicitConversionSequence::Worse; 3996 3997 // C++ [over.ics.rank]p4b2: 3998 // 3999 // If class B is derived directly or indirectly from class A, 4000 // conversion of B* to A* is better than conversion of B* to 4001 // void*, and conversion of A* to void* is better than conversion 4002 // of B* to void*. 4003 bool SCS1ConvertsToVoid 4004 = SCS1.isPointerConversionToVoidPointer(S.Context); 4005 bool SCS2ConvertsToVoid 4006 = SCS2.isPointerConversionToVoidPointer(S.Context); 4007 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4008 // Exactly one of the conversion sequences is a conversion to 4009 // a void pointer; it's the worse conversion. 4010 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4011 : ImplicitConversionSequence::Worse; 4012 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4013 // Neither conversion sequence converts to a void pointer; compare 4014 // their derived-to-base conversions. 4015 if (ImplicitConversionSequence::CompareKind DerivedCK 4016 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4017 return DerivedCK; 4018 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4019 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4020 // Both conversion sequences are conversions to void 4021 // pointers. Compare the source types to determine if there's an 4022 // inheritance relationship in their sources. 4023 QualType FromType1 = SCS1.getFromType(); 4024 QualType FromType2 = SCS2.getFromType(); 4025 4026 // Adjust the types we're converting from via the array-to-pointer 4027 // conversion, if we need to. 4028 if (SCS1.First == ICK_Array_To_Pointer) 4029 FromType1 = S.Context.getArrayDecayedType(FromType1); 4030 if (SCS2.First == ICK_Array_To_Pointer) 4031 FromType2 = S.Context.getArrayDecayedType(FromType2); 4032 4033 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4034 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4035 4036 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4037 return ImplicitConversionSequence::Better; 4038 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4039 return ImplicitConversionSequence::Worse; 4040 4041 // Objective-C++: If one interface is more specific than the 4042 // other, it is the better one. 4043 const ObjCObjectPointerType* FromObjCPtr1 4044 = FromType1->getAs<ObjCObjectPointerType>(); 4045 const ObjCObjectPointerType* FromObjCPtr2 4046 = FromType2->getAs<ObjCObjectPointerType>(); 4047 if (FromObjCPtr1 && FromObjCPtr2) { 4048 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4049 FromObjCPtr2); 4050 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4051 FromObjCPtr1); 4052 if (AssignLeft != AssignRight) { 4053 return AssignLeft? ImplicitConversionSequence::Better 4054 : ImplicitConversionSequence::Worse; 4055 } 4056 } 4057 } 4058 4059 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4060 // Check for a better reference binding based on the kind of bindings. 4061 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4062 return ImplicitConversionSequence::Better; 4063 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4064 return ImplicitConversionSequence::Worse; 4065 } 4066 4067 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4068 // bullet 3). 4069 if (ImplicitConversionSequence::CompareKind QualCK 4070 = CompareQualificationConversions(S, SCS1, SCS2)) 4071 return QualCK; 4072 4073 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4074 // C++ [over.ics.rank]p3b4: 4075 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4076 // which the references refer are the same type except for 4077 // top-level cv-qualifiers, and the type to which the reference 4078 // initialized by S2 refers is more cv-qualified than the type 4079 // to which the reference initialized by S1 refers. 4080 QualType T1 = SCS1.getToType(2); 4081 QualType T2 = SCS2.getToType(2); 4082 T1 = S.Context.getCanonicalType(T1); 4083 T2 = S.Context.getCanonicalType(T2); 4084 Qualifiers T1Quals, T2Quals; 4085 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4086 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4087 if (UnqualT1 == UnqualT2) { 4088 // Objective-C++ ARC: If the references refer to objects with different 4089 // lifetimes, prefer bindings that don't change lifetime. 4090 if (SCS1.ObjCLifetimeConversionBinding != 4091 SCS2.ObjCLifetimeConversionBinding) { 4092 return SCS1.ObjCLifetimeConversionBinding 4093 ? ImplicitConversionSequence::Worse 4094 : ImplicitConversionSequence::Better; 4095 } 4096 4097 // If the type is an array type, promote the element qualifiers to the 4098 // type for comparison. 4099 if (isa<ArrayType>(T1) && T1Quals) 4100 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4101 if (isa<ArrayType>(T2) && T2Quals) 4102 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4103 if (T2.isMoreQualifiedThan(T1)) 4104 return ImplicitConversionSequence::Better; 4105 if (T1.isMoreQualifiedThan(T2)) 4106 return ImplicitConversionSequence::Worse; 4107 } 4108 } 4109 4110 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4111 // floating-to-integral conversion if the integral conversion 4112 // is between types of the same size. 4113 // For example: 4114 // void f(float); 4115 // void f(int); 4116 // int main { 4117 // long a; 4118 // f(a); 4119 // } 4120 // Here, MSVC will call f(int) instead of generating a compile error 4121 // as clang will do in standard mode. 4122 if (S.getLangOpts().MSVCCompat && 4123 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4124 SCS1.Second == ICK_Integral_Conversion && 4125 SCS2.Second == ICK_Floating_Integral && 4126 S.Context.getTypeSize(SCS1.getFromType()) == 4127 S.Context.getTypeSize(SCS1.getToType(2))) 4128 return ImplicitConversionSequence::Better; 4129 4130 // Prefer a compatible vector conversion over a lax vector conversion 4131 // For example: 4132 // 4133 // typedef float __v4sf __attribute__((__vector_size__(16))); 4134 // void f(vector float); 4135 // void f(vector signed int); 4136 // int main() { 4137 // __v4sf a; 4138 // f(a); 4139 // } 4140 // Here, we'd like to choose f(vector float) and not 4141 // report an ambiguous call error 4142 if (SCS1.Second == ICK_Vector_Conversion && 4143 SCS2.Second == ICK_Vector_Conversion) { 4144 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4145 SCS1.getFromType(), SCS1.getToType(2)); 4146 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4147 SCS2.getFromType(), SCS2.getToType(2)); 4148 4149 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4150 return SCS1IsCompatibleVectorConversion 4151 ? ImplicitConversionSequence::Better 4152 : ImplicitConversionSequence::Worse; 4153 } 4154 4155 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4156 SCS2.Second == ICK_SVE_Vector_Conversion) { 4157 bool SCS1IsCompatibleSVEVectorConversion = 4158 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4159 bool SCS2IsCompatibleSVEVectorConversion = 4160 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4161 4162 if (SCS1IsCompatibleSVEVectorConversion != 4163 SCS2IsCompatibleSVEVectorConversion) 4164 return SCS1IsCompatibleSVEVectorConversion 4165 ? ImplicitConversionSequence::Better 4166 : ImplicitConversionSequence::Worse; 4167 } 4168 4169 return ImplicitConversionSequence::Indistinguishable; 4170 } 4171 4172 /// CompareQualificationConversions - Compares two standard conversion 4173 /// sequences to determine whether they can be ranked based on their 4174 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4175 static ImplicitConversionSequence::CompareKind 4176 CompareQualificationConversions(Sema &S, 4177 const StandardConversionSequence& SCS1, 4178 const StandardConversionSequence& SCS2) { 4179 // C++ 13.3.3.2p3: 4180 // -- S1 and S2 differ only in their qualification conversion and 4181 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4182 // cv-qualification signature of type T1 is a proper subset of 4183 // the cv-qualification signature of type T2, and S1 is not the 4184 // deprecated string literal array-to-pointer conversion (4.2). 4185 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4186 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4187 return ImplicitConversionSequence::Indistinguishable; 4188 4189 // FIXME: the example in the standard doesn't use a qualification 4190 // conversion (!) 4191 QualType T1 = SCS1.getToType(2); 4192 QualType T2 = SCS2.getToType(2); 4193 T1 = S.Context.getCanonicalType(T1); 4194 T2 = S.Context.getCanonicalType(T2); 4195 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4196 Qualifiers T1Quals, T2Quals; 4197 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4198 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4199 4200 // If the types are the same, we won't learn anything by unwrapping 4201 // them. 4202 if (UnqualT1 == UnqualT2) 4203 return ImplicitConversionSequence::Indistinguishable; 4204 4205 ImplicitConversionSequence::CompareKind Result 4206 = ImplicitConversionSequence::Indistinguishable; 4207 4208 // Objective-C++ ARC: 4209 // Prefer qualification conversions not involving a change in lifetime 4210 // to qualification conversions that do not change lifetime. 4211 if (SCS1.QualificationIncludesObjCLifetime != 4212 SCS2.QualificationIncludesObjCLifetime) { 4213 Result = SCS1.QualificationIncludesObjCLifetime 4214 ? ImplicitConversionSequence::Worse 4215 : ImplicitConversionSequence::Better; 4216 } 4217 4218 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4219 // Within each iteration of the loop, we check the qualifiers to 4220 // determine if this still looks like a qualification 4221 // conversion. Then, if all is well, we unwrap one more level of 4222 // pointers or pointers-to-members and do it all again 4223 // until there are no more pointers or pointers-to-members left 4224 // to unwrap. This essentially mimics what 4225 // IsQualificationConversion does, but here we're checking for a 4226 // strict subset of qualifiers. 4227 if (T1.getQualifiers().withoutObjCLifetime() == 4228 T2.getQualifiers().withoutObjCLifetime()) 4229 // The qualifiers are the same, so this doesn't tell us anything 4230 // about how the sequences rank. 4231 // ObjC ownership quals are omitted above as they interfere with 4232 // the ARC overload rule. 4233 ; 4234 else if (T2.isMoreQualifiedThan(T1)) { 4235 // T1 has fewer qualifiers, so it could be the better sequence. 4236 if (Result == ImplicitConversionSequence::Worse) 4237 // Neither has qualifiers that are a subset of the other's 4238 // qualifiers. 4239 return ImplicitConversionSequence::Indistinguishable; 4240 4241 Result = ImplicitConversionSequence::Better; 4242 } else if (T1.isMoreQualifiedThan(T2)) { 4243 // T2 has fewer qualifiers, so it could be the better sequence. 4244 if (Result == ImplicitConversionSequence::Better) 4245 // Neither has qualifiers that are a subset of the other's 4246 // qualifiers. 4247 return ImplicitConversionSequence::Indistinguishable; 4248 4249 Result = ImplicitConversionSequence::Worse; 4250 } else { 4251 // Qualifiers are disjoint. 4252 return ImplicitConversionSequence::Indistinguishable; 4253 } 4254 4255 // If the types after this point are equivalent, we're done. 4256 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4257 break; 4258 } 4259 4260 // Check that the winning standard conversion sequence isn't using 4261 // the deprecated string literal array to pointer conversion. 4262 switch (Result) { 4263 case ImplicitConversionSequence::Better: 4264 if (SCS1.DeprecatedStringLiteralToCharPtr) 4265 Result = ImplicitConversionSequence::Indistinguishable; 4266 break; 4267 4268 case ImplicitConversionSequence::Indistinguishable: 4269 break; 4270 4271 case ImplicitConversionSequence::Worse: 4272 if (SCS2.DeprecatedStringLiteralToCharPtr) 4273 Result = ImplicitConversionSequence::Indistinguishable; 4274 break; 4275 } 4276 4277 return Result; 4278 } 4279 4280 /// CompareDerivedToBaseConversions - Compares two standard conversion 4281 /// sequences to determine whether they can be ranked based on their 4282 /// various kinds of derived-to-base conversions (C++ 4283 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4284 /// conversions between Objective-C interface types. 4285 static ImplicitConversionSequence::CompareKind 4286 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4287 const StandardConversionSequence& SCS1, 4288 const StandardConversionSequence& SCS2) { 4289 QualType FromType1 = SCS1.getFromType(); 4290 QualType ToType1 = SCS1.getToType(1); 4291 QualType FromType2 = SCS2.getFromType(); 4292 QualType ToType2 = SCS2.getToType(1); 4293 4294 // Adjust the types we're converting from via the array-to-pointer 4295 // conversion, if we need to. 4296 if (SCS1.First == ICK_Array_To_Pointer) 4297 FromType1 = S.Context.getArrayDecayedType(FromType1); 4298 if (SCS2.First == ICK_Array_To_Pointer) 4299 FromType2 = S.Context.getArrayDecayedType(FromType2); 4300 4301 // Canonicalize all of the types. 4302 FromType1 = S.Context.getCanonicalType(FromType1); 4303 ToType1 = S.Context.getCanonicalType(ToType1); 4304 FromType2 = S.Context.getCanonicalType(FromType2); 4305 ToType2 = S.Context.getCanonicalType(ToType2); 4306 4307 // C++ [over.ics.rank]p4b3: 4308 // 4309 // If class B is derived directly or indirectly from class A and 4310 // class C is derived directly or indirectly from B, 4311 // 4312 // Compare based on pointer conversions. 4313 if (SCS1.Second == ICK_Pointer_Conversion && 4314 SCS2.Second == ICK_Pointer_Conversion && 4315 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4316 FromType1->isPointerType() && FromType2->isPointerType() && 4317 ToType1->isPointerType() && ToType2->isPointerType()) { 4318 QualType FromPointee1 = 4319 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4320 QualType ToPointee1 = 4321 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4322 QualType FromPointee2 = 4323 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4324 QualType ToPointee2 = 4325 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4326 4327 // -- conversion of C* to B* is better than conversion of C* to A*, 4328 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4329 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4330 return ImplicitConversionSequence::Better; 4331 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4332 return ImplicitConversionSequence::Worse; 4333 } 4334 4335 // -- conversion of B* to A* is better than conversion of C* to A*, 4336 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4337 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4338 return ImplicitConversionSequence::Better; 4339 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4340 return ImplicitConversionSequence::Worse; 4341 } 4342 } else if (SCS1.Second == ICK_Pointer_Conversion && 4343 SCS2.Second == ICK_Pointer_Conversion) { 4344 const ObjCObjectPointerType *FromPtr1 4345 = FromType1->getAs<ObjCObjectPointerType>(); 4346 const ObjCObjectPointerType *FromPtr2 4347 = FromType2->getAs<ObjCObjectPointerType>(); 4348 const ObjCObjectPointerType *ToPtr1 4349 = ToType1->getAs<ObjCObjectPointerType>(); 4350 const ObjCObjectPointerType *ToPtr2 4351 = ToType2->getAs<ObjCObjectPointerType>(); 4352 4353 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4354 // Apply the same conversion ranking rules for Objective-C pointer types 4355 // that we do for C++ pointers to class types. However, we employ the 4356 // Objective-C pseudo-subtyping relationship used for assignment of 4357 // Objective-C pointer types. 4358 bool FromAssignLeft 4359 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4360 bool FromAssignRight 4361 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4362 bool ToAssignLeft 4363 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4364 bool ToAssignRight 4365 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4366 4367 // A conversion to an a non-id object pointer type or qualified 'id' 4368 // type is better than a conversion to 'id'. 4369 if (ToPtr1->isObjCIdType() && 4370 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4371 return ImplicitConversionSequence::Worse; 4372 if (ToPtr2->isObjCIdType() && 4373 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4374 return ImplicitConversionSequence::Better; 4375 4376 // A conversion to a non-id object pointer type is better than a 4377 // conversion to a qualified 'id' type 4378 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4379 return ImplicitConversionSequence::Worse; 4380 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4381 return ImplicitConversionSequence::Better; 4382 4383 // A conversion to an a non-Class object pointer type or qualified 'Class' 4384 // type is better than a conversion to 'Class'. 4385 if (ToPtr1->isObjCClassType() && 4386 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4387 return ImplicitConversionSequence::Worse; 4388 if (ToPtr2->isObjCClassType() && 4389 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4390 return ImplicitConversionSequence::Better; 4391 4392 // A conversion to a non-Class object pointer type is better than a 4393 // conversion to a qualified 'Class' type. 4394 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4395 return ImplicitConversionSequence::Worse; 4396 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4397 return ImplicitConversionSequence::Better; 4398 4399 // -- "conversion of C* to B* is better than conversion of C* to A*," 4400 if (S.Context.hasSameType(FromType1, FromType2) && 4401 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4402 (ToAssignLeft != ToAssignRight)) { 4403 if (FromPtr1->isSpecialized()) { 4404 // "conversion of B<A> * to B * is better than conversion of B * to 4405 // C *. 4406 bool IsFirstSame = 4407 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4408 bool IsSecondSame = 4409 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4410 if (IsFirstSame) { 4411 if (!IsSecondSame) 4412 return ImplicitConversionSequence::Better; 4413 } else if (IsSecondSame) 4414 return ImplicitConversionSequence::Worse; 4415 } 4416 return ToAssignLeft? ImplicitConversionSequence::Worse 4417 : ImplicitConversionSequence::Better; 4418 } 4419 4420 // -- "conversion of B* to A* is better than conversion of C* to A*," 4421 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4422 (FromAssignLeft != FromAssignRight)) 4423 return FromAssignLeft? ImplicitConversionSequence::Better 4424 : ImplicitConversionSequence::Worse; 4425 } 4426 } 4427 4428 // Ranking of member-pointer types. 4429 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4430 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4431 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4432 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4433 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4434 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4435 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4436 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4437 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4438 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4439 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4440 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4441 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4442 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4443 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4444 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4445 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4446 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4447 return ImplicitConversionSequence::Worse; 4448 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4449 return ImplicitConversionSequence::Better; 4450 } 4451 // conversion of B::* to C::* is better than conversion of A::* to C::* 4452 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4453 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4454 return ImplicitConversionSequence::Better; 4455 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4456 return ImplicitConversionSequence::Worse; 4457 } 4458 } 4459 4460 if (SCS1.Second == ICK_Derived_To_Base) { 4461 // -- conversion of C to B is better than conversion of C to A, 4462 // -- binding of an expression of type C to a reference of type 4463 // B& is better than binding an expression of type C to a 4464 // reference of type A&, 4465 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4466 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4467 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4468 return ImplicitConversionSequence::Better; 4469 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4470 return ImplicitConversionSequence::Worse; 4471 } 4472 4473 // -- conversion of B to A is better than conversion of C to A. 4474 // -- binding of an expression of type B to a reference of type 4475 // A& is better than binding an expression of type C to a 4476 // reference of type A&, 4477 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4478 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4479 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4480 return ImplicitConversionSequence::Better; 4481 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4482 return ImplicitConversionSequence::Worse; 4483 } 4484 } 4485 4486 return ImplicitConversionSequence::Indistinguishable; 4487 } 4488 4489 /// Determine whether the given type is valid, e.g., it is not an invalid 4490 /// C++ class. 4491 static bool isTypeValid(QualType T) { 4492 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4493 return !Record->isInvalidDecl(); 4494 4495 return true; 4496 } 4497 4498 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4499 if (!T.getQualifiers().hasUnaligned()) 4500 return T; 4501 4502 Qualifiers Q; 4503 T = Ctx.getUnqualifiedArrayType(T, Q); 4504 Q.removeUnaligned(); 4505 return Ctx.getQualifiedType(T, Q); 4506 } 4507 4508 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4509 /// determine whether they are reference-compatible, 4510 /// reference-related, or incompatible, for use in C++ initialization by 4511 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4512 /// type, and the first type (T1) is the pointee type of the reference 4513 /// type being initialized. 4514 Sema::ReferenceCompareResult 4515 Sema::CompareReferenceRelationship(SourceLocation Loc, 4516 QualType OrigT1, QualType OrigT2, 4517 ReferenceConversions *ConvOut) { 4518 assert(!OrigT1->isReferenceType() && 4519 "T1 must be the pointee type of the reference type"); 4520 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4521 4522 QualType T1 = Context.getCanonicalType(OrigT1); 4523 QualType T2 = Context.getCanonicalType(OrigT2); 4524 Qualifiers T1Quals, T2Quals; 4525 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4526 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4527 4528 ReferenceConversions ConvTmp; 4529 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4530 Conv = ReferenceConversions(); 4531 4532 // C++2a [dcl.init.ref]p4: 4533 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4534 // reference-related to "cv2 T2" if T1 is similar to T2, or 4535 // T1 is a base class of T2. 4536 // "cv1 T1" is reference-compatible with "cv2 T2" if 4537 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4538 // "pointer to cv1 T1" via a standard conversion sequence. 4539 4540 // Check for standard conversions we can apply to pointers: derived-to-base 4541 // conversions, ObjC pointer conversions, and function pointer conversions. 4542 // (Qualification conversions are checked last.) 4543 QualType ConvertedT2; 4544 if (UnqualT1 == UnqualT2) { 4545 // Nothing to do. 4546 } else if (isCompleteType(Loc, OrigT2) && 4547 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4548 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4549 Conv |= ReferenceConversions::DerivedToBase; 4550 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4551 UnqualT2->isObjCObjectOrInterfaceType() && 4552 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4553 Conv |= ReferenceConversions::ObjC; 4554 else if (UnqualT2->isFunctionType() && 4555 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4556 Conv |= ReferenceConversions::Function; 4557 // No need to check qualifiers; function types don't have them. 4558 return Ref_Compatible; 4559 } 4560 bool ConvertedReferent = Conv != 0; 4561 4562 // We can have a qualification conversion. Compute whether the types are 4563 // similar at the same time. 4564 bool PreviousToQualsIncludeConst = true; 4565 bool TopLevel = true; 4566 do { 4567 if (T1 == T2) 4568 break; 4569 4570 // We will need a qualification conversion. 4571 Conv |= ReferenceConversions::Qualification; 4572 4573 // Track whether we performed a qualification conversion anywhere other 4574 // than the top level. This matters for ranking reference bindings in 4575 // overload resolution. 4576 if (!TopLevel) 4577 Conv |= ReferenceConversions::NestedQualification; 4578 4579 // MS compiler ignores __unaligned qualifier for references; do the same. 4580 T1 = withoutUnaligned(Context, T1); 4581 T2 = withoutUnaligned(Context, T2); 4582 4583 // If we find a qualifier mismatch, the types are not reference-compatible, 4584 // but are still be reference-related if they're similar. 4585 bool ObjCLifetimeConversion = false; 4586 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4587 PreviousToQualsIncludeConst, 4588 ObjCLifetimeConversion)) 4589 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4590 ? Ref_Related 4591 : Ref_Incompatible; 4592 4593 // FIXME: Should we track this for any level other than the first? 4594 if (ObjCLifetimeConversion) 4595 Conv |= ReferenceConversions::ObjCLifetime; 4596 4597 TopLevel = false; 4598 } while (Context.UnwrapSimilarTypes(T1, T2)); 4599 4600 // At this point, if the types are reference-related, we must either have the 4601 // same inner type (ignoring qualifiers), or must have already worked out how 4602 // to convert the referent. 4603 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4604 ? Ref_Compatible 4605 : Ref_Incompatible; 4606 } 4607 4608 /// Look for a user-defined conversion to a value reference-compatible 4609 /// with DeclType. Return true if something definite is found. 4610 static bool 4611 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4612 QualType DeclType, SourceLocation DeclLoc, 4613 Expr *Init, QualType T2, bool AllowRvalues, 4614 bool AllowExplicit) { 4615 assert(T2->isRecordType() && "Can only find conversions of record types."); 4616 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4617 4618 OverloadCandidateSet CandidateSet( 4619 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4620 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4621 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4622 NamedDecl *D = *I; 4623 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4624 if (isa<UsingShadowDecl>(D)) 4625 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4626 4627 FunctionTemplateDecl *ConvTemplate 4628 = dyn_cast<FunctionTemplateDecl>(D); 4629 CXXConversionDecl *Conv; 4630 if (ConvTemplate) 4631 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4632 else 4633 Conv = cast<CXXConversionDecl>(D); 4634 4635 if (AllowRvalues) { 4636 // If we are initializing an rvalue reference, don't permit conversion 4637 // functions that return lvalues. 4638 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4639 const ReferenceType *RefType 4640 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4641 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4642 continue; 4643 } 4644 4645 if (!ConvTemplate && 4646 S.CompareReferenceRelationship( 4647 DeclLoc, 4648 Conv->getConversionType() 4649 .getNonReferenceType() 4650 .getUnqualifiedType(), 4651 DeclType.getNonReferenceType().getUnqualifiedType()) == 4652 Sema::Ref_Incompatible) 4653 continue; 4654 } else { 4655 // If the conversion function doesn't return a reference type, 4656 // it can't be considered for this conversion. An rvalue reference 4657 // is only acceptable if its referencee is a function type. 4658 4659 const ReferenceType *RefType = 4660 Conv->getConversionType()->getAs<ReferenceType>(); 4661 if (!RefType || 4662 (!RefType->isLValueReferenceType() && 4663 !RefType->getPointeeType()->isFunctionType())) 4664 continue; 4665 } 4666 4667 if (ConvTemplate) 4668 S.AddTemplateConversionCandidate( 4669 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4670 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4671 else 4672 S.AddConversionCandidate( 4673 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4674 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4675 } 4676 4677 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4678 4679 OverloadCandidateSet::iterator Best; 4680 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4681 case OR_Success: 4682 // C++ [over.ics.ref]p1: 4683 // 4684 // [...] If the parameter binds directly to the result of 4685 // applying a conversion function to the argument 4686 // expression, the implicit conversion sequence is a 4687 // user-defined conversion sequence (13.3.3.1.2), with the 4688 // second standard conversion sequence either an identity 4689 // conversion or, if the conversion function returns an 4690 // entity of a type that is a derived class of the parameter 4691 // type, a derived-to-base Conversion. 4692 if (!Best->FinalConversion.DirectBinding) 4693 return false; 4694 4695 ICS.setUserDefined(); 4696 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4697 ICS.UserDefined.After = Best->FinalConversion; 4698 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4699 ICS.UserDefined.ConversionFunction = Best->Function; 4700 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4701 ICS.UserDefined.EllipsisConversion = false; 4702 assert(ICS.UserDefined.After.ReferenceBinding && 4703 ICS.UserDefined.After.DirectBinding && 4704 "Expected a direct reference binding!"); 4705 return true; 4706 4707 case OR_Ambiguous: 4708 ICS.setAmbiguous(); 4709 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4710 Cand != CandidateSet.end(); ++Cand) 4711 if (Cand->Best) 4712 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4713 return true; 4714 4715 case OR_No_Viable_Function: 4716 case OR_Deleted: 4717 // There was no suitable conversion, or we found a deleted 4718 // conversion; continue with other checks. 4719 return false; 4720 } 4721 4722 llvm_unreachable("Invalid OverloadResult!"); 4723 } 4724 4725 /// Compute an implicit conversion sequence for reference 4726 /// initialization. 4727 static ImplicitConversionSequence 4728 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4729 SourceLocation DeclLoc, 4730 bool SuppressUserConversions, 4731 bool AllowExplicit) { 4732 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4733 4734 // Most paths end in a failed conversion. 4735 ImplicitConversionSequence ICS; 4736 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4737 4738 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4739 QualType T2 = Init->getType(); 4740 4741 // If the initializer is the address of an overloaded function, try 4742 // to resolve the overloaded function. If all goes well, T2 is the 4743 // type of the resulting function. 4744 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4745 DeclAccessPair Found; 4746 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4747 false, Found)) 4748 T2 = Fn->getType(); 4749 } 4750 4751 // Compute some basic properties of the types and the initializer. 4752 bool isRValRef = DeclType->isRValueReferenceType(); 4753 Expr::Classification InitCategory = Init->Classify(S.Context); 4754 4755 Sema::ReferenceConversions RefConv; 4756 Sema::ReferenceCompareResult RefRelationship = 4757 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4758 4759 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4760 ICS.setStandard(); 4761 ICS.Standard.First = ICK_Identity; 4762 // FIXME: A reference binding can be a function conversion too. We should 4763 // consider that when ordering reference-to-function bindings. 4764 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4765 ? ICK_Derived_To_Base 4766 : (RefConv & Sema::ReferenceConversions::ObjC) 4767 ? ICK_Compatible_Conversion 4768 : ICK_Identity; 4769 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4770 // a reference binding that performs a non-top-level qualification 4771 // conversion as a qualification conversion, not as an identity conversion. 4772 ICS.Standard.Third = (RefConv & 4773 Sema::ReferenceConversions::NestedQualification) 4774 ? ICK_Qualification 4775 : ICK_Identity; 4776 ICS.Standard.setFromType(T2); 4777 ICS.Standard.setToType(0, T2); 4778 ICS.Standard.setToType(1, T1); 4779 ICS.Standard.setToType(2, T1); 4780 ICS.Standard.ReferenceBinding = true; 4781 ICS.Standard.DirectBinding = BindsDirectly; 4782 ICS.Standard.IsLvalueReference = !isRValRef; 4783 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4784 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4785 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4786 ICS.Standard.ObjCLifetimeConversionBinding = 4787 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4788 ICS.Standard.CopyConstructor = nullptr; 4789 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4790 }; 4791 4792 // C++0x [dcl.init.ref]p5: 4793 // A reference to type "cv1 T1" is initialized by an expression 4794 // of type "cv2 T2" as follows: 4795 4796 // -- If reference is an lvalue reference and the initializer expression 4797 if (!isRValRef) { 4798 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4799 // reference-compatible with "cv2 T2," or 4800 // 4801 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4802 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4803 // C++ [over.ics.ref]p1: 4804 // When a parameter of reference type binds directly (8.5.3) 4805 // to an argument expression, the implicit conversion sequence 4806 // is the identity conversion, unless the argument expression 4807 // has a type that is a derived class of the parameter type, 4808 // in which case the implicit conversion sequence is a 4809 // derived-to-base Conversion (13.3.3.1). 4810 SetAsReferenceBinding(/*BindsDirectly=*/true); 4811 4812 // Nothing more to do: the inaccessibility/ambiguity check for 4813 // derived-to-base conversions is suppressed when we're 4814 // computing the implicit conversion sequence (C++ 4815 // [over.best.ics]p2). 4816 return ICS; 4817 } 4818 4819 // -- has a class type (i.e., T2 is a class type), where T1 is 4820 // not reference-related to T2, and can be implicitly 4821 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4822 // is reference-compatible with "cv3 T3" 92) (this 4823 // conversion is selected by enumerating the applicable 4824 // conversion functions (13.3.1.6) and choosing the best 4825 // one through overload resolution (13.3)), 4826 if (!SuppressUserConversions && T2->isRecordType() && 4827 S.isCompleteType(DeclLoc, T2) && 4828 RefRelationship == Sema::Ref_Incompatible) { 4829 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4830 Init, T2, /*AllowRvalues=*/false, 4831 AllowExplicit)) 4832 return ICS; 4833 } 4834 } 4835 4836 // -- Otherwise, the reference shall be an lvalue reference to a 4837 // non-volatile const type (i.e., cv1 shall be const), or the reference 4838 // shall be an rvalue reference. 4839 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4840 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4841 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4842 return ICS; 4843 } 4844 4845 // -- If the initializer expression 4846 // 4847 // -- is an xvalue, class prvalue, array prvalue or function 4848 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4849 if (RefRelationship == Sema::Ref_Compatible && 4850 (InitCategory.isXValue() || 4851 (InitCategory.isPRValue() && 4852 (T2->isRecordType() || T2->isArrayType())) || 4853 (InitCategory.isLValue() && T2->isFunctionType()))) { 4854 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4855 // binding unless we're binding to a class prvalue. 4856 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4857 // allow the use of rvalue references in C++98/03 for the benefit of 4858 // standard library implementors; therefore, we need the xvalue check here. 4859 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4860 !(InitCategory.isPRValue() || T2->isRecordType())); 4861 return ICS; 4862 } 4863 4864 // -- has a class type (i.e., T2 is a class type), where T1 is not 4865 // reference-related to T2, and can be implicitly converted to 4866 // an xvalue, class prvalue, or function lvalue of type 4867 // "cv3 T3", where "cv1 T1" is reference-compatible with 4868 // "cv3 T3", 4869 // 4870 // then the reference is bound to the value of the initializer 4871 // expression in the first case and to the result of the conversion 4872 // in the second case (or, in either case, to an appropriate base 4873 // class subobject). 4874 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4875 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4876 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4877 Init, T2, /*AllowRvalues=*/true, 4878 AllowExplicit)) { 4879 // In the second case, if the reference is an rvalue reference 4880 // and the second standard conversion sequence of the 4881 // user-defined conversion sequence includes an lvalue-to-rvalue 4882 // conversion, the program is ill-formed. 4883 if (ICS.isUserDefined() && isRValRef && 4884 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4885 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4886 4887 return ICS; 4888 } 4889 4890 // A temporary of function type cannot be created; don't even try. 4891 if (T1->isFunctionType()) 4892 return ICS; 4893 4894 // -- Otherwise, a temporary of type "cv1 T1" is created and 4895 // initialized from the initializer expression using the 4896 // rules for a non-reference copy initialization (8.5). The 4897 // reference is then bound to the temporary. If T1 is 4898 // reference-related to T2, cv1 must be the same 4899 // cv-qualification as, or greater cv-qualification than, 4900 // cv2; otherwise, the program is ill-formed. 4901 if (RefRelationship == Sema::Ref_Related) { 4902 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4903 // we would be reference-compatible or reference-compatible with 4904 // added qualification. But that wasn't the case, so the reference 4905 // initialization fails. 4906 // 4907 // Note that we only want to check address spaces and cvr-qualifiers here. 4908 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4909 Qualifiers T1Quals = T1.getQualifiers(); 4910 Qualifiers T2Quals = T2.getQualifiers(); 4911 T1Quals.removeObjCGCAttr(); 4912 T1Quals.removeObjCLifetime(); 4913 T2Quals.removeObjCGCAttr(); 4914 T2Quals.removeObjCLifetime(); 4915 // MS compiler ignores __unaligned qualifier for references; do the same. 4916 T1Quals.removeUnaligned(); 4917 T2Quals.removeUnaligned(); 4918 if (!T1Quals.compatiblyIncludes(T2Quals)) 4919 return ICS; 4920 } 4921 4922 // If at least one of the types is a class type, the types are not 4923 // related, and we aren't allowed any user conversions, the 4924 // reference binding fails. This case is important for breaking 4925 // recursion, since TryImplicitConversion below will attempt to 4926 // create a temporary through the use of a copy constructor. 4927 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4928 (T1->isRecordType() || T2->isRecordType())) 4929 return ICS; 4930 4931 // If T1 is reference-related to T2 and the reference is an rvalue 4932 // reference, the initializer expression shall not be an lvalue. 4933 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4934 Init->Classify(S.Context).isLValue()) { 4935 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4936 return ICS; 4937 } 4938 4939 // C++ [over.ics.ref]p2: 4940 // When a parameter of reference type is not bound directly to 4941 // an argument expression, the conversion sequence is the one 4942 // required to convert the argument expression to the 4943 // underlying type of the reference according to 4944 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4945 // to copy-initializing a temporary of the underlying type with 4946 // the argument expression. Any difference in top-level 4947 // cv-qualification is subsumed by the initialization itself 4948 // and does not constitute a conversion. 4949 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4950 AllowedExplicit::None, 4951 /*InOverloadResolution=*/false, 4952 /*CStyle=*/false, 4953 /*AllowObjCWritebackConversion=*/false, 4954 /*AllowObjCConversionOnExplicit=*/false); 4955 4956 // Of course, that's still a reference binding. 4957 if (ICS.isStandard()) { 4958 ICS.Standard.ReferenceBinding = true; 4959 ICS.Standard.IsLvalueReference = !isRValRef; 4960 ICS.Standard.BindsToFunctionLvalue = false; 4961 ICS.Standard.BindsToRvalue = true; 4962 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4963 ICS.Standard.ObjCLifetimeConversionBinding = false; 4964 } else if (ICS.isUserDefined()) { 4965 const ReferenceType *LValRefType = 4966 ICS.UserDefined.ConversionFunction->getReturnType() 4967 ->getAs<LValueReferenceType>(); 4968 4969 // C++ [over.ics.ref]p3: 4970 // Except for an implicit object parameter, for which see 13.3.1, a 4971 // standard conversion sequence cannot be formed if it requires [...] 4972 // binding an rvalue reference to an lvalue other than a function 4973 // lvalue. 4974 // Note that the function case is not possible here. 4975 if (isRValRef && LValRefType) { 4976 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4977 return ICS; 4978 } 4979 4980 ICS.UserDefined.After.ReferenceBinding = true; 4981 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4982 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4983 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4984 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4985 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4986 } 4987 4988 return ICS; 4989 } 4990 4991 static ImplicitConversionSequence 4992 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4993 bool SuppressUserConversions, 4994 bool InOverloadResolution, 4995 bool AllowObjCWritebackConversion, 4996 bool AllowExplicit = false); 4997 4998 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4999 /// initializer list From. 5000 static ImplicitConversionSequence 5001 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5002 bool SuppressUserConversions, 5003 bool InOverloadResolution, 5004 bool AllowObjCWritebackConversion) { 5005 // C++11 [over.ics.list]p1: 5006 // When an argument is an initializer list, it is not an expression and 5007 // special rules apply for converting it to a parameter type. 5008 5009 ImplicitConversionSequence Result; 5010 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5011 5012 // We need a complete type for what follows. Incomplete types can never be 5013 // initialized from init lists. 5014 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 5015 return Result; 5016 5017 // Per DR1467: 5018 // If the parameter type is a class X and the initializer list has a single 5019 // element of type cv U, where U is X or a class derived from X, the 5020 // implicit conversion sequence is the one required to convert the element 5021 // to the parameter type. 5022 // 5023 // Otherwise, if the parameter type is a character array [... ] 5024 // and the initializer list has a single element that is an 5025 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5026 // implicit conversion sequence is the identity conversion. 5027 if (From->getNumInits() == 1) { 5028 if (ToType->isRecordType()) { 5029 QualType InitType = From->getInit(0)->getType(); 5030 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5031 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5032 return TryCopyInitialization(S, From->getInit(0), ToType, 5033 SuppressUserConversions, 5034 InOverloadResolution, 5035 AllowObjCWritebackConversion); 5036 } 5037 5038 if (const auto *AT = S.Context.getAsArrayType(ToType)) { 5039 if (S.IsStringInit(From->getInit(0), AT)) { 5040 InitializedEntity Entity = 5041 InitializedEntity::InitializeParameter(S.Context, ToType, 5042 /*Consumed=*/false); 5043 if (S.CanPerformCopyInitialization(Entity, From)) { 5044 Result.setStandard(); 5045 Result.Standard.setAsIdentityConversion(); 5046 Result.Standard.setFromType(ToType); 5047 Result.Standard.setAllToTypes(ToType); 5048 return Result; 5049 } 5050 } 5051 } 5052 } 5053 5054 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5055 // C++11 [over.ics.list]p2: 5056 // If the parameter type is std::initializer_list<X> or "array of X" and 5057 // all the elements can be implicitly converted to X, the implicit 5058 // conversion sequence is the worst conversion necessary to convert an 5059 // element of the list to X. 5060 // 5061 // C++14 [over.ics.list]p3: 5062 // Otherwise, if the parameter type is "array of N X", if the initializer 5063 // list has exactly N elements or if it has fewer than N elements and X is 5064 // default-constructible, and if all the elements of the initializer list 5065 // can be implicitly converted to X, the implicit conversion sequence is 5066 // the worst conversion necessary to convert an element of the list to X. 5067 // 5068 // FIXME: We're missing a lot of these checks. 5069 bool toStdInitializerList = false; 5070 QualType X; 5071 if (ToType->isArrayType()) 5072 X = S.Context.getAsArrayType(ToType)->getElementType(); 5073 else 5074 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5075 if (!X.isNull()) { 5076 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5077 Expr *Init = From->getInit(i); 5078 ImplicitConversionSequence ICS = 5079 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5080 InOverloadResolution, 5081 AllowObjCWritebackConversion); 5082 // If a single element isn't convertible, fail. 5083 if (ICS.isBad()) { 5084 Result = ICS; 5085 break; 5086 } 5087 // Otherwise, look for the worst conversion. 5088 if (Result.isBad() || CompareImplicitConversionSequences( 5089 S, From->getBeginLoc(), ICS, Result) == 5090 ImplicitConversionSequence::Worse) 5091 Result = ICS; 5092 } 5093 5094 // For an empty list, we won't have computed any conversion sequence. 5095 // Introduce the identity conversion sequence. 5096 if (From->getNumInits() == 0) { 5097 Result.setStandard(); 5098 Result.Standard.setAsIdentityConversion(); 5099 Result.Standard.setFromType(ToType); 5100 Result.Standard.setAllToTypes(ToType); 5101 } 5102 5103 Result.setStdInitializerListElement(toStdInitializerList); 5104 return Result; 5105 } 5106 5107 // C++14 [over.ics.list]p4: 5108 // C++11 [over.ics.list]p3: 5109 // Otherwise, if the parameter is a non-aggregate class X and overload 5110 // resolution chooses a single best constructor [...] the implicit 5111 // conversion sequence is a user-defined conversion sequence. If multiple 5112 // constructors are viable but none is better than the others, the 5113 // implicit conversion sequence is a user-defined conversion sequence. 5114 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5115 // This function can deal with initializer lists. 5116 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5117 AllowedExplicit::None, 5118 InOverloadResolution, /*CStyle=*/false, 5119 AllowObjCWritebackConversion, 5120 /*AllowObjCConversionOnExplicit=*/false); 5121 } 5122 5123 // C++14 [over.ics.list]p5: 5124 // C++11 [over.ics.list]p4: 5125 // Otherwise, if the parameter has an aggregate type which can be 5126 // initialized from the initializer list [...] the implicit conversion 5127 // sequence is a user-defined conversion sequence. 5128 if (ToType->isAggregateType()) { 5129 // Type is an aggregate, argument is an init list. At this point it comes 5130 // down to checking whether the initialization works. 5131 // FIXME: Find out whether this parameter is consumed or not. 5132 InitializedEntity Entity = 5133 InitializedEntity::InitializeParameter(S.Context, ToType, 5134 /*Consumed=*/false); 5135 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5136 From)) { 5137 Result.setUserDefined(); 5138 Result.UserDefined.Before.setAsIdentityConversion(); 5139 // Initializer lists don't have a type. 5140 Result.UserDefined.Before.setFromType(QualType()); 5141 Result.UserDefined.Before.setAllToTypes(QualType()); 5142 5143 Result.UserDefined.After.setAsIdentityConversion(); 5144 Result.UserDefined.After.setFromType(ToType); 5145 Result.UserDefined.After.setAllToTypes(ToType); 5146 Result.UserDefined.ConversionFunction = nullptr; 5147 } 5148 return Result; 5149 } 5150 5151 // C++14 [over.ics.list]p6: 5152 // C++11 [over.ics.list]p5: 5153 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5154 if (ToType->isReferenceType()) { 5155 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5156 // mention initializer lists in any way. So we go by what list- 5157 // initialization would do and try to extrapolate from that. 5158 5159 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5160 5161 // If the initializer list has a single element that is reference-related 5162 // to the parameter type, we initialize the reference from that. 5163 if (From->getNumInits() == 1) { 5164 Expr *Init = From->getInit(0); 5165 5166 QualType T2 = Init->getType(); 5167 5168 // If the initializer is the address of an overloaded function, try 5169 // to resolve the overloaded function. If all goes well, T2 is the 5170 // type of the resulting function. 5171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5172 DeclAccessPair Found; 5173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5174 Init, ToType, false, Found)) 5175 T2 = Fn->getType(); 5176 } 5177 5178 // Compute some basic properties of the types and the initializer. 5179 Sema::ReferenceCompareResult RefRelationship = 5180 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5181 5182 if (RefRelationship >= Sema::Ref_Related) { 5183 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5184 SuppressUserConversions, 5185 /*AllowExplicit=*/false); 5186 } 5187 } 5188 5189 // Otherwise, we bind the reference to a temporary created from the 5190 // initializer list. 5191 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5192 InOverloadResolution, 5193 AllowObjCWritebackConversion); 5194 if (Result.isFailure()) 5195 return Result; 5196 assert(!Result.isEllipsis() && 5197 "Sub-initialization cannot result in ellipsis conversion."); 5198 5199 // Can we even bind to a temporary? 5200 if (ToType->isRValueReferenceType() || 5201 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5202 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5203 Result.UserDefined.After; 5204 SCS.ReferenceBinding = true; 5205 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5206 SCS.BindsToRvalue = true; 5207 SCS.BindsToFunctionLvalue = false; 5208 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5209 SCS.ObjCLifetimeConversionBinding = false; 5210 } else 5211 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5212 From, ToType); 5213 return Result; 5214 } 5215 5216 // C++14 [over.ics.list]p7: 5217 // C++11 [over.ics.list]p6: 5218 // Otherwise, if the parameter type is not a class: 5219 if (!ToType->isRecordType()) { 5220 // - if the initializer list has one element that is not itself an 5221 // initializer list, the implicit conversion sequence is the one 5222 // required to convert the element to the parameter type. 5223 unsigned NumInits = From->getNumInits(); 5224 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5225 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5226 SuppressUserConversions, 5227 InOverloadResolution, 5228 AllowObjCWritebackConversion); 5229 // - if the initializer list has no elements, the implicit conversion 5230 // sequence is the identity conversion. 5231 else if (NumInits == 0) { 5232 Result.setStandard(); 5233 Result.Standard.setAsIdentityConversion(); 5234 Result.Standard.setFromType(ToType); 5235 Result.Standard.setAllToTypes(ToType); 5236 } 5237 return Result; 5238 } 5239 5240 // C++14 [over.ics.list]p8: 5241 // C++11 [over.ics.list]p7: 5242 // In all cases other than those enumerated above, no conversion is possible 5243 return Result; 5244 } 5245 5246 /// TryCopyInitialization - Try to copy-initialize a value of type 5247 /// ToType from the expression From. Return the implicit conversion 5248 /// sequence required to pass this argument, which may be a bad 5249 /// conversion sequence (meaning that the argument cannot be passed to 5250 /// a parameter of this type). If @p SuppressUserConversions, then we 5251 /// do not permit any user-defined conversion sequences. 5252 static ImplicitConversionSequence 5253 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5254 bool SuppressUserConversions, 5255 bool InOverloadResolution, 5256 bool AllowObjCWritebackConversion, 5257 bool AllowExplicit) { 5258 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5259 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5260 InOverloadResolution,AllowObjCWritebackConversion); 5261 5262 if (ToType->isReferenceType()) 5263 return TryReferenceInit(S, From, ToType, 5264 /*FIXME:*/ From->getBeginLoc(), 5265 SuppressUserConversions, AllowExplicit); 5266 5267 return TryImplicitConversion(S, From, ToType, 5268 SuppressUserConversions, 5269 AllowedExplicit::None, 5270 InOverloadResolution, 5271 /*CStyle=*/false, 5272 AllowObjCWritebackConversion, 5273 /*AllowObjCConversionOnExplicit=*/false); 5274 } 5275 5276 static bool TryCopyInitialization(const CanQualType FromQTy, 5277 const CanQualType ToQTy, 5278 Sema &S, 5279 SourceLocation Loc, 5280 ExprValueKind FromVK) { 5281 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5282 ImplicitConversionSequence ICS = 5283 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5284 5285 return !ICS.isBad(); 5286 } 5287 5288 /// TryObjectArgumentInitialization - Try to initialize the object 5289 /// parameter of the given member function (@c Method) from the 5290 /// expression @p From. 5291 static ImplicitConversionSequence 5292 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5293 Expr::Classification FromClassification, 5294 CXXMethodDecl *Method, 5295 CXXRecordDecl *ActingContext) { 5296 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5297 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5298 // const volatile object. 5299 Qualifiers Quals = Method->getMethodQualifiers(); 5300 if (isa<CXXDestructorDecl>(Method)) { 5301 Quals.addConst(); 5302 Quals.addVolatile(); 5303 } 5304 5305 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5306 5307 // Set up the conversion sequence as a "bad" conversion, to allow us 5308 // to exit early. 5309 ImplicitConversionSequence ICS; 5310 5311 // We need to have an object of class type. 5312 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5313 FromType = PT->getPointeeType(); 5314 5315 // When we had a pointer, it's implicitly dereferenced, so we 5316 // better have an lvalue. 5317 assert(FromClassification.isLValue()); 5318 } 5319 5320 assert(FromType->isRecordType()); 5321 5322 // C++0x [over.match.funcs]p4: 5323 // For non-static member functions, the type of the implicit object 5324 // parameter is 5325 // 5326 // - "lvalue reference to cv X" for functions declared without a 5327 // ref-qualifier or with the & ref-qualifier 5328 // - "rvalue reference to cv X" for functions declared with the && 5329 // ref-qualifier 5330 // 5331 // where X is the class of which the function is a member and cv is the 5332 // cv-qualification on the member function declaration. 5333 // 5334 // However, when finding an implicit conversion sequence for the argument, we 5335 // are not allowed to perform user-defined conversions 5336 // (C++ [over.match.funcs]p5). We perform a simplified version of 5337 // reference binding here, that allows class rvalues to bind to 5338 // non-constant references. 5339 5340 // First check the qualifiers. 5341 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5342 if (ImplicitParamType.getCVRQualifiers() 5343 != FromTypeCanon.getLocalCVRQualifiers() && 5344 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5345 ICS.setBad(BadConversionSequence::bad_qualifiers, 5346 FromType, ImplicitParamType); 5347 return ICS; 5348 } 5349 5350 if (FromTypeCanon.hasAddressSpace()) { 5351 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5352 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5353 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5354 ICS.setBad(BadConversionSequence::bad_qualifiers, 5355 FromType, ImplicitParamType); 5356 return ICS; 5357 } 5358 } 5359 5360 // Check that we have either the same type or a derived type. It 5361 // affects the conversion rank. 5362 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5363 ImplicitConversionKind SecondKind; 5364 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5365 SecondKind = ICK_Identity; 5366 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5367 SecondKind = ICK_Derived_To_Base; 5368 else { 5369 ICS.setBad(BadConversionSequence::unrelated_class, 5370 FromType, ImplicitParamType); 5371 return ICS; 5372 } 5373 5374 // Check the ref-qualifier. 5375 switch (Method->getRefQualifier()) { 5376 case RQ_None: 5377 // Do nothing; we don't care about lvalueness or rvalueness. 5378 break; 5379 5380 case RQ_LValue: 5381 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5382 // non-const lvalue reference cannot bind to an rvalue 5383 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5384 ImplicitParamType); 5385 return ICS; 5386 } 5387 break; 5388 5389 case RQ_RValue: 5390 if (!FromClassification.isRValue()) { 5391 // rvalue reference cannot bind to an lvalue 5392 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5393 ImplicitParamType); 5394 return ICS; 5395 } 5396 break; 5397 } 5398 5399 // Success. Mark this as a reference binding. 5400 ICS.setStandard(); 5401 ICS.Standard.setAsIdentityConversion(); 5402 ICS.Standard.Second = SecondKind; 5403 ICS.Standard.setFromType(FromType); 5404 ICS.Standard.setAllToTypes(ImplicitParamType); 5405 ICS.Standard.ReferenceBinding = true; 5406 ICS.Standard.DirectBinding = true; 5407 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5408 ICS.Standard.BindsToFunctionLvalue = false; 5409 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5410 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5411 = (Method->getRefQualifier() == RQ_None); 5412 return ICS; 5413 } 5414 5415 /// PerformObjectArgumentInitialization - Perform initialization of 5416 /// the implicit object parameter for the given Method with the given 5417 /// expression. 5418 ExprResult 5419 Sema::PerformObjectArgumentInitialization(Expr *From, 5420 NestedNameSpecifier *Qualifier, 5421 NamedDecl *FoundDecl, 5422 CXXMethodDecl *Method) { 5423 QualType FromRecordType, DestType; 5424 QualType ImplicitParamRecordType = 5425 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5426 5427 Expr::Classification FromClassification; 5428 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5429 FromRecordType = PT->getPointeeType(); 5430 DestType = Method->getThisType(); 5431 FromClassification = Expr::Classification::makeSimpleLValue(); 5432 } else { 5433 FromRecordType = From->getType(); 5434 DestType = ImplicitParamRecordType; 5435 FromClassification = From->Classify(Context); 5436 5437 // When performing member access on an rvalue, materialize a temporary. 5438 if (From->isRValue()) { 5439 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5440 Method->getRefQualifier() != 5441 RefQualifierKind::RQ_RValue); 5442 } 5443 } 5444 5445 // Note that we always use the true parent context when performing 5446 // the actual argument initialization. 5447 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5448 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5449 Method->getParent()); 5450 if (ICS.isBad()) { 5451 switch (ICS.Bad.Kind) { 5452 case BadConversionSequence::bad_qualifiers: { 5453 Qualifiers FromQs = FromRecordType.getQualifiers(); 5454 Qualifiers ToQs = DestType.getQualifiers(); 5455 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5456 if (CVR) { 5457 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5458 << Method->getDeclName() << FromRecordType << (CVR - 1) 5459 << From->getSourceRange(); 5460 Diag(Method->getLocation(), diag::note_previous_decl) 5461 << Method->getDeclName(); 5462 return ExprError(); 5463 } 5464 break; 5465 } 5466 5467 case BadConversionSequence::lvalue_ref_to_rvalue: 5468 case BadConversionSequence::rvalue_ref_to_lvalue: { 5469 bool IsRValueQualified = 5470 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5471 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5472 << Method->getDeclName() << FromClassification.isRValue() 5473 << IsRValueQualified; 5474 Diag(Method->getLocation(), diag::note_previous_decl) 5475 << Method->getDeclName(); 5476 return ExprError(); 5477 } 5478 5479 case BadConversionSequence::no_conversion: 5480 case BadConversionSequence::unrelated_class: 5481 break; 5482 } 5483 5484 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5485 << ImplicitParamRecordType << FromRecordType 5486 << From->getSourceRange(); 5487 } 5488 5489 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5490 ExprResult FromRes = 5491 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5492 if (FromRes.isInvalid()) 5493 return ExprError(); 5494 From = FromRes.get(); 5495 } 5496 5497 if (!Context.hasSameType(From->getType(), DestType)) { 5498 CastKind CK; 5499 QualType PteeTy = DestType->getPointeeType(); 5500 LangAS DestAS = 5501 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5502 if (FromRecordType.getAddressSpace() != DestAS) 5503 CK = CK_AddressSpaceConversion; 5504 else 5505 CK = CK_NoOp; 5506 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5507 } 5508 return From; 5509 } 5510 5511 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5512 /// expression From to bool (C++0x [conv]p3). 5513 static ImplicitConversionSequence 5514 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5515 // C++ [dcl.init]/17.8: 5516 // - Otherwise, if the initialization is direct-initialization, the source 5517 // type is std::nullptr_t, and the destination type is bool, the initial 5518 // value of the object being initialized is false. 5519 if (From->getType()->isNullPtrType()) 5520 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5521 S.Context.BoolTy, 5522 From->isGLValue()); 5523 5524 // All other direct-initialization of bool is equivalent to an implicit 5525 // conversion to bool in which explicit conversions are permitted. 5526 return TryImplicitConversion(S, From, S.Context.BoolTy, 5527 /*SuppressUserConversions=*/false, 5528 AllowedExplicit::Conversions, 5529 /*InOverloadResolution=*/false, 5530 /*CStyle=*/false, 5531 /*AllowObjCWritebackConversion=*/false, 5532 /*AllowObjCConversionOnExplicit=*/false); 5533 } 5534 5535 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5536 /// of the expression From to bool (C++0x [conv]p3). 5537 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5538 if (checkPlaceholderForOverload(*this, From)) 5539 return ExprError(); 5540 5541 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5542 if (!ICS.isBad()) 5543 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5544 5545 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5546 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5547 << From->getType() << From->getSourceRange(); 5548 return ExprError(); 5549 } 5550 5551 /// Check that the specified conversion is permitted in a converted constant 5552 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5553 /// is acceptable. 5554 static bool CheckConvertedConstantConversions(Sema &S, 5555 StandardConversionSequence &SCS) { 5556 // Since we know that the target type is an integral or unscoped enumeration 5557 // type, most conversion kinds are impossible. All possible First and Third 5558 // conversions are fine. 5559 switch (SCS.Second) { 5560 case ICK_Identity: 5561 case ICK_Integral_Promotion: 5562 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5563 case ICK_Zero_Queue_Conversion: 5564 return true; 5565 5566 case ICK_Boolean_Conversion: 5567 // Conversion from an integral or unscoped enumeration type to bool is 5568 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5569 // conversion, so we allow it in a converted constant expression. 5570 // 5571 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5572 // a lot of popular code. We should at least add a warning for this 5573 // (non-conforming) extension. 5574 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5575 SCS.getToType(2)->isBooleanType(); 5576 5577 case ICK_Pointer_Conversion: 5578 case ICK_Pointer_Member: 5579 // C++1z: null pointer conversions and null member pointer conversions are 5580 // only permitted if the source type is std::nullptr_t. 5581 return SCS.getFromType()->isNullPtrType(); 5582 5583 case ICK_Floating_Promotion: 5584 case ICK_Complex_Promotion: 5585 case ICK_Floating_Conversion: 5586 case ICK_Complex_Conversion: 5587 case ICK_Floating_Integral: 5588 case ICK_Compatible_Conversion: 5589 case ICK_Derived_To_Base: 5590 case ICK_Vector_Conversion: 5591 case ICK_SVE_Vector_Conversion: 5592 case ICK_Vector_Splat: 5593 case ICK_Complex_Real: 5594 case ICK_Block_Pointer_Conversion: 5595 case ICK_TransparentUnionConversion: 5596 case ICK_Writeback_Conversion: 5597 case ICK_Zero_Event_Conversion: 5598 case ICK_C_Only_Conversion: 5599 case ICK_Incompatible_Pointer_Conversion: 5600 return false; 5601 5602 case ICK_Lvalue_To_Rvalue: 5603 case ICK_Array_To_Pointer: 5604 case ICK_Function_To_Pointer: 5605 llvm_unreachable("found a first conversion kind in Second"); 5606 5607 case ICK_Function_Conversion: 5608 case ICK_Qualification: 5609 llvm_unreachable("found a third conversion kind in Second"); 5610 5611 case ICK_Num_Conversion_Kinds: 5612 break; 5613 } 5614 5615 llvm_unreachable("unknown conversion kind"); 5616 } 5617 5618 /// CheckConvertedConstantExpression - Check that the expression From is a 5619 /// converted constant expression of type T, perform the conversion and produce 5620 /// the converted expression, per C++11 [expr.const]p3. 5621 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5622 QualType T, APValue &Value, 5623 Sema::CCEKind CCE, 5624 bool RequireInt, 5625 NamedDecl *Dest) { 5626 assert(S.getLangOpts().CPlusPlus11 && 5627 "converted constant expression outside C++11"); 5628 5629 if (checkPlaceholderForOverload(S, From)) 5630 return ExprError(); 5631 5632 // C++1z [expr.const]p3: 5633 // A converted constant expression of type T is an expression, 5634 // implicitly converted to type T, where the converted 5635 // expression is a constant expression and the implicit conversion 5636 // sequence contains only [... list of conversions ...]. 5637 // C++1z [stmt.if]p2: 5638 // If the if statement is of the form if constexpr, the value of the 5639 // condition shall be a contextually converted constant expression of type 5640 // bool. 5641 ImplicitConversionSequence ICS = 5642 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5643 ? TryContextuallyConvertToBool(S, From) 5644 : TryCopyInitialization(S, From, T, 5645 /*SuppressUserConversions=*/false, 5646 /*InOverloadResolution=*/false, 5647 /*AllowObjCWritebackConversion=*/false, 5648 /*AllowExplicit=*/false); 5649 StandardConversionSequence *SCS = nullptr; 5650 switch (ICS.getKind()) { 5651 case ImplicitConversionSequence::StandardConversion: 5652 SCS = &ICS.Standard; 5653 break; 5654 case ImplicitConversionSequence::UserDefinedConversion: 5655 if (T->isRecordType()) 5656 SCS = &ICS.UserDefined.Before; 5657 else 5658 SCS = &ICS.UserDefined.After; 5659 break; 5660 case ImplicitConversionSequence::AmbiguousConversion: 5661 case ImplicitConversionSequence::BadConversion: 5662 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5663 return S.Diag(From->getBeginLoc(), 5664 diag::err_typecheck_converted_constant_expression) 5665 << From->getType() << From->getSourceRange() << T; 5666 return ExprError(); 5667 5668 case ImplicitConversionSequence::EllipsisConversion: 5669 llvm_unreachable("ellipsis conversion in converted constant expression"); 5670 } 5671 5672 // Check that we would only use permitted conversions. 5673 if (!CheckConvertedConstantConversions(S, *SCS)) { 5674 return S.Diag(From->getBeginLoc(), 5675 diag::err_typecheck_converted_constant_expression_disallowed) 5676 << From->getType() << From->getSourceRange() << T; 5677 } 5678 // [...] and where the reference binding (if any) binds directly. 5679 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5680 return S.Diag(From->getBeginLoc(), 5681 diag::err_typecheck_converted_constant_expression_indirect) 5682 << From->getType() << From->getSourceRange() << T; 5683 } 5684 5685 // Usually we can simply apply the ImplicitConversionSequence we formed 5686 // earlier, but that's not guaranteed to work when initializing an object of 5687 // class type. 5688 ExprResult Result; 5689 if (T->isRecordType()) { 5690 assert(CCE == Sema::CCEK_TemplateArg && 5691 "unexpected class type converted constant expr"); 5692 Result = S.PerformCopyInitialization( 5693 InitializedEntity::InitializeTemplateParameter( 5694 T, cast<NonTypeTemplateParmDecl>(Dest)), 5695 SourceLocation(), From); 5696 } else { 5697 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5698 } 5699 if (Result.isInvalid()) 5700 return Result; 5701 5702 // C++2a [intro.execution]p5: 5703 // A full-expression is [...] a constant-expression [...] 5704 Result = 5705 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5706 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5707 if (Result.isInvalid()) 5708 return Result; 5709 5710 // Check for a narrowing implicit conversion. 5711 bool ReturnPreNarrowingValue = false; 5712 APValue PreNarrowingValue; 5713 QualType PreNarrowingType; 5714 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5715 PreNarrowingType)) { 5716 case NK_Dependent_Narrowing: 5717 // Implicit conversion to a narrower type, but the expression is 5718 // value-dependent so we can't tell whether it's actually narrowing. 5719 case NK_Variable_Narrowing: 5720 // Implicit conversion to a narrower type, and the value is not a constant 5721 // expression. We'll diagnose this in a moment. 5722 case NK_Not_Narrowing: 5723 break; 5724 5725 case NK_Constant_Narrowing: 5726 if (CCE == Sema::CCEK_ArrayBound && 5727 PreNarrowingType->isIntegralOrEnumerationType() && 5728 PreNarrowingValue.isInt()) { 5729 // Don't diagnose array bound narrowing here; we produce more precise 5730 // errors by allowing the un-narrowed value through. 5731 ReturnPreNarrowingValue = true; 5732 break; 5733 } 5734 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5735 << CCE << /*Constant*/ 1 5736 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5737 break; 5738 5739 case NK_Type_Narrowing: 5740 // FIXME: It would be better to diagnose that the expression is not a 5741 // constant expression. 5742 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5743 << CCE << /*Constant*/ 0 << From->getType() << T; 5744 break; 5745 } 5746 5747 if (Result.get()->isValueDependent()) { 5748 Value = APValue(); 5749 return Result; 5750 } 5751 5752 // Check the expression is a constant expression. 5753 SmallVector<PartialDiagnosticAt, 8> Notes; 5754 Expr::EvalResult Eval; 5755 Eval.Diag = &Notes; 5756 5757 ConstantExprKind Kind; 5758 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5759 Kind = ConstantExprKind::ClassTemplateArgument; 5760 else if (CCE == Sema::CCEK_TemplateArg) 5761 Kind = ConstantExprKind::NonClassTemplateArgument; 5762 else 5763 Kind = ConstantExprKind::Normal; 5764 5765 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5766 (RequireInt && !Eval.Val.isInt())) { 5767 // The expression can't be folded, so we can't keep it at this position in 5768 // the AST. 5769 Result = ExprError(); 5770 } else { 5771 Value = Eval.Val; 5772 5773 if (Notes.empty()) { 5774 // It's a constant expression. 5775 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5776 if (ReturnPreNarrowingValue) 5777 Value = std::move(PreNarrowingValue); 5778 return E; 5779 } 5780 } 5781 5782 // It's not a constant expression. Produce an appropriate diagnostic. 5783 if (Notes.size() == 1 && 5784 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5785 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5786 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5787 diag::note_constexpr_invalid_template_arg) { 5788 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5789 for (unsigned I = 0; I < Notes.size(); ++I) 5790 S.Diag(Notes[I].first, Notes[I].second); 5791 } else { 5792 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5793 << CCE << From->getSourceRange(); 5794 for (unsigned I = 0; I < Notes.size(); ++I) 5795 S.Diag(Notes[I].first, Notes[I].second); 5796 } 5797 return ExprError(); 5798 } 5799 5800 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5801 APValue &Value, CCEKind CCE, 5802 NamedDecl *Dest) { 5803 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5804 Dest); 5805 } 5806 5807 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5808 llvm::APSInt &Value, 5809 CCEKind CCE) { 5810 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5811 5812 APValue V; 5813 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5814 /*Dest=*/nullptr); 5815 if (!R.isInvalid() && !R.get()->isValueDependent()) 5816 Value = V.getInt(); 5817 return R; 5818 } 5819 5820 5821 /// dropPointerConversions - If the given standard conversion sequence 5822 /// involves any pointer conversions, remove them. This may change 5823 /// the result type of the conversion sequence. 5824 static void dropPointerConversion(StandardConversionSequence &SCS) { 5825 if (SCS.Second == ICK_Pointer_Conversion) { 5826 SCS.Second = ICK_Identity; 5827 SCS.Third = ICK_Identity; 5828 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5829 } 5830 } 5831 5832 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5833 /// convert the expression From to an Objective-C pointer type. 5834 static ImplicitConversionSequence 5835 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5836 // Do an implicit conversion to 'id'. 5837 QualType Ty = S.Context.getObjCIdType(); 5838 ImplicitConversionSequence ICS 5839 = TryImplicitConversion(S, From, Ty, 5840 // FIXME: Are these flags correct? 5841 /*SuppressUserConversions=*/false, 5842 AllowedExplicit::Conversions, 5843 /*InOverloadResolution=*/false, 5844 /*CStyle=*/false, 5845 /*AllowObjCWritebackConversion=*/false, 5846 /*AllowObjCConversionOnExplicit=*/true); 5847 5848 // Strip off any final conversions to 'id'. 5849 switch (ICS.getKind()) { 5850 case ImplicitConversionSequence::BadConversion: 5851 case ImplicitConversionSequence::AmbiguousConversion: 5852 case ImplicitConversionSequence::EllipsisConversion: 5853 break; 5854 5855 case ImplicitConversionSequence::UserDefinedConversion: 5856 dropPointerConversion(ICS.UserDefined.After); 5857 break; 5858 5859 case ImplicitConversionSequence::StandardConversion: 5860 dropPointerConversion(ICS.Standard); 5861 break; 5862 } 5863 5864 return ICS; 5865 } 5866 5867 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5868 /// conversion of the expression From to an Objective-C pointer type. 5869 /// Returns a valid but null ExprResult if no conversion sequence exists. 5870 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5871 if (checkPlaceholderForOverload(*this, From)) 5872 return ExprError(); 5873 5874 QualType Ty = Context.getObjCIdType(); 5875 ImplicitConversionSequence ICS = 5876 TryContextuallyConvertToObjCPointer(*this, From); 5877 if (!ICS.isBad()) 5878 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5879 return ExprResult(); 5880 } 5881 5882 /// Determine whether the provided type is an integral type, or an enumeration 5883 /// type of a permitted flavor. 5884 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5885 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5886 : T->isIntegralOrUnscopedEnumerationType(); 5887 } 5888 5889 static ExprResult 5890 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5891 Sema::ContextualImplicitConverter &Converter, 5892 QualType T, UnresolvedSetImpl &ViableConversions) { 5893 5894 if (Converter.Suppress) 5895 return ExprError(); 5896 5897 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5898 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5899 CXXConversionDecl *Conv = 5900 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5901 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5902 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5903 } 5904 return From; 5905 } 5906 5907 static bool 5908 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5909 Sema::ContextualImplicitConverter &Converter, 5910 QualType T, bool HadMultipleCandidates, 5911 UnresolvedSetImpl &ExplicitConversions) { 5912 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5913 DeclAccessPair Found = ExplicitConversions[0]; 5914 CXXConversionDecl *Conversion = 5915 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5916 5917 // The user probably meant to invoke the given explicit 5918 // conversion; use it. 5919 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5920 std::string TypeStr; 5921 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5922 5923 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5924 << FixItHint::CreateInsertion(From->getBeginLoc(), 5925 "static_cast<" + TypeStr + ">(") 5926 << FixItHint::CreateInsertion( 5927 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5928 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5929 5930 // If we aren't in a SFINAE context, build a call to the 5931 // explicit conversion function. 5932 if (SemaRef.isSFINAEContext()) 5933 return true; 5934 5935 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5936 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5937 HadMultipleCandidates); 5938 if (Result.isInvalid()) 5939 return true; 5940 // Record usage of conversion in an implicit cast. 5941 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5942 CK_UserDefinedConversion, Result.get(), 5943 nullptr, Result.get()->getValueKind(), 5944 SemaRef.CurFPFeatureOverrides()); 5945 } 5946 return false; 5947 } 5948 5949 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5950 Sema::ContextualImplicitConverter &Converter, 5951 QualType T, bool HadMultipleCandidates, 5952 DeclAccessPair &Found) { 5953 CXXConversionDecl *Conversion = 5954 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5955 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5956 5957 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5958 if (!Converter.SuppressConversion) { 5959 if (SemaRef.isSFINAEContext()) 5960 return true; 5961 5962 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5963 << From->getSourceRange(); 5964 } 5965 5966 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5967 HadMultipleCandidates); 5968 if (Result.isInvalid()) 5969 return true; 5970 // Record usage of conversion in an implicit cast. 5971 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5972 CK_UserDefinedConversion, Result.get(), 5973 nullptr, Result.get()->getValueKind(), 5974 SemaRef.CurFPFeatureOverrides()); 5975 return false; 5976 } 5977 5978 static ExprResult finishContextualImplicitConversion( 5979 Sema &SemaRef, SourceLocation Loc, Expr *From, 5980 Sema::ContextualImplicitConverter &Converter) { 5981 if (!Converter.match(From->getType()) && !Converter.Suppress) 5982 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5983 << From->getSourceRange(); 5984 5985 return SemaRef.DefaultLvalueConversion(From); 5986 } 5987 5988 static void 5989 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5990 UnresolvedSetImpl &ViableConversions, 5991 OverloadCandidateSet &CandidateSet) { 5992 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5993 DeclAccessPair FoundDecl = ViableConversions[I]; 5994 NamedDecl *D = FoundDecl.getDecl(); 5995 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5996 if (isa<UsingShadowDecl>(D)) 5997 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5998 5999 CXXConversionDecl *Conv; 6000 FunctionTemplateDecl *ConvTemplate; 6001 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6002 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6003 else 6004 Conv = cast<CXXConversionDecl>(D); 6005 6006 if (ConvTemplate) 6007 SemaRef.AddTemplateConversionCandidate( 6008 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6009 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6010 else 6011 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6012 ToType, CandidateSet, 6013 /*AllowObjCConversionOnExplicit=*/false, 6014 /*AllowExplicit*/ true); 6015 } 6016 } 6017 6018 /// Attempt to convert the given expression to a type which is accepted 6019 /// by the given converter. 6020 /// 6021 /// This routine will attempt to convert an expression of class type to a 6022 /// type accepted by the specified converter. In C++11 and before, the class 6023 /// must have a single non-explicit conversion function converting to a matching 6024 /// type. In C++1y, there can be multiple such conversion functions, but only 6025 /// one target type. 6026 /// 6027 /// \param Loc The source location of the construct that requires the 6028 /// conversion. 6029 /// 6030 /// \param From The expression we're converting from. 6031 /// 6032 /// \param Converter Used to control and diagnose the conversion process. 6033 /// 6034 /// \returns The expression, converted to an integral or enumeration type if 6035 /// successful. 6036 ExprResult Sema::PerformContextualImplicitConversion( 6037 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6038 // We can't perform any more checking for type-dependent expressions. 6039 if (From->isTypeDependent()) 6040 return From; 6041 6042 // Process placeholders immediately. 6043 if (From->hasPlaceholderType()) { 6044 ExprResult result = CheckPlaceholderExpr(From); 6045 if (result.isInvalid()) 6046 return result; 6047 From = result.get(); 6048 } 6049 6050 // If the expression already has a matching type, we're golden. 6051 QualType T = From->getType(); 6052 if (Converter.match(T)) 6053 return DefaultLvalueConversion(From); 6054 6055 // FIXME: Check for missing '()' if T is a function type? 6056 6057 // We can only perform contextual implicit conversions on objects of class 6058 // type. 6059 const RecordType *RecordTy = T->getAs<RecordType>(); 6060 if (!RecordTy || !getLangOpts().CPlusPlus) { 6061 if (!Converter.Suppress) 6062 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6063 return From; 6064 } 6065 6066 // We must have a complete class type. 6067 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6068 ContextualImplicitConverter &Converter; 6069 Expr *From; 6070 6071 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6072 : Converter(Converter), From(From) {} 6073 6074 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6075 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6076 } 6077 } IncompleteDiagnoser(Converter, From); 6078 6079 if (Converter.Suppress ? !isCompleteType(Loc, T) 6080 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6081 return From; 6082 6083 // Look for a conversion to an integral or enumeration type. 6084 UnresolvedSet<4> 6085 ViableConversions; // These are *potentially* viable in C++1y. 6086 UnresolvedSet<4> ExplicitConversions; 6087 const auto &Conversions = 6088 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6089 6090 bool HadMultipleCandidates = 6091 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6092 6093 // To check that there is only one target type, in C++1y: 6094 QualType ToType; 6095 bool HasUniqueTargetType = true; 6096 6097 // Collect explicit or viable (potentially in C++1y) conversions. 6098 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6099 NamedDecl *D = (*I)->getUnderlyingDecl(); 6100 CXXConversionDecl *Conversion; 6101 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6102 if (ConvTemplate) { 6103 if (getLangOpts().CPlusPlus14) 6104 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6105 else 6106 continue; // C++11 does not consider conversion operator templates(?). 6107 } else 6108 Conversion = cast<CXXConversionDecl>(D); 6109 6110 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6111 "Conversion operator templates are considered potentially " 6112 "viable in C++1y"); 6113 6114 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6115 if (Converter.match(CurToType) || ConvTemplate) { 6116 6117 if (Conversion->isExplicit()) { 6118 // FIXME: For C++1y, do we need this restriction? 6119 // cf. diagnoseNoViableConversion() 6120 if (!ConvTemplate) 6121 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6122 } else { 6123 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6124 if (ToType.isNull()) 6125 ToType = CurToType.getUnqualifiedType(); 6126 else if (HasUniqueTargetType && 6127 (CurToType.getUnqualifiedType() != ToType)) 6128 HasUniqueTargetType = false; 6129 } 6130 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6131 } 6132 } 6133 } 6134 6135 if (getLangOpts().CPlusPlus14) { 6136 // C++1y [conv]p6: 6137 // ... An expression e of class type E appearing in such a context 6138 // is said to be contextually implicitly converted to a specified 6139 // type T and is well-formed if and only if e can be implicitly 6140 // converted to a type T that is determined as follows: E is searched 6141 // for conversion functions whose return type is cv T or reference to 6142 // cv T such that T is allowed by the context. There shall be 6143 // exactly one such T. 6144 6145 // If no unique T is found: 6146 if (ToType.isNull()) { 6147 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6148 HadMultipleCandidates, 6149 ExplicitConversions)) 6150 return ExprError(); 6151 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6152 } 6153 6154 // If more than one unique Ts are found: 6155 if (!HasUniqueTargetType) 6156 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6157 ViableConversions); 6158 6159 // If one unique T is found: 6160 // First, build a candidate set from the previously recorded 6161 // potentially viable conversions. 6162 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6163 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6164 CandidateSet); 6165 6166 // Then, perform overload resolution over the candidate set. 6167 OverloadCandidateSet::iterator Best; 6168 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6169 case OR_Success: { 6170 // Apply this conversion. 6171 DeclAccessPair Found = 6172 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6173 if (recordConversion(*this, Loc, From, Converter, T, 6174 HadMultipleCandidates, Found)) 6175 return ExprError(); 6176 break; 6177 } 6178 case OR_Ambiguous: 6179 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6180 ViableConversions); 6181 case OR_No_Viable_Function: 6182 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6183 HadMultipleCandidates, 6184 ExplicitConversions)) 6185 return ExprError(); 6186 LLVM_FALLTHROUGH; 6187 case OR_Deleted: 6188 // We'll complain below about a non-integral condition type. 6189 break; 6190 } 6191 } else { 6192 switch (ViableConversions.size()) { 6193 case 0: { 6194 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6195 HadMultipleCandidates, 6196 ExplicitConversions)) 6197 return ExprError(); 6198 6199 // We'll complain below about a non-integral condition type. 6200 break; 6201 } 6202 case 1: { 6203 // Apply this conversion. 6204 DeclAccessPair Found = ViableConversions[0]; 6205 if (recordConversion(*this, Loc, From, Converter, T, 6206 HadMultipleCandidates, Found)) 6207 return ExprError(); 6208 break; 6209 } 6210 default: 6211 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6212 ViableConversions); 6213 } 6214 } 6215 6216 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6217 } 6218 6219 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6220 /// an acceptable non-member overloaded operator for a call whose 6221 /// arguments have types T1 (and, if non-empty, T2). This routine 6222 /// implements the check in C++ [over.match.oper]p3b2 concerning 6223 /// enumeration types. 6224 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6225 FunctionDecl *Fn, 6226 ArrayRef<Expr *> Args) { 6227 QualType T1 = Args[0]->getType(); 6228 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6229 6230 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6231 return true; 6232 6233 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6234 return true; 6235 6236 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6237 if (Proto->getNumParams() < 1) 6238 return false; 6239 6240 if (T1->isEnumeralType()) { 6241 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6242 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6243 return true; 6244 } 6245 6246 if (Proto->getNumParams() < 2) 6247 return false; 6248 6249 if (!T2.isNull() && T2->isEnumeralType()) { 6250 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6251 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6252 return true; 6253 } 6254 6255 return false; 6256 } 6257 6258 /// AddOverloadCandidate - Adds the given function to the set of 6259 /// candidate functions, using the given function call arguments. If 6260 /// @p SuppressUserConversions, then don't allow user-defined 6261 /// conversions via constructors or conversion operators. 6262 /// 6263 /// \param PartialOverloading true if we are performing "partial" overloading 6264 /// based on an incomplete set of function arguments. This feature is used by 6265 /// code completion. 6266 void Sema::AddOverloadCandidate( 6267 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6268 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6269 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6270 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6271 OverloadCandidateParamOrder PO) { 6272 const FunctionProtoType *Proto 6273 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6274 assert(Proto && "Functions without a prototype cannot be overloaded"); 6275 assert(!Function->getDescribedFunctionTemplate() && 6276 "Use AddTemplateOverloadCandidate for function templates"); 6277 6278 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6279 if (!isa<CXXConstructorDecl>(Method)) { 6280 // If we get here, it's because we're calling a member function 6281 // that is named without a member access expression (e.g., 6282 // "this->f") that was either written explicitly or created 6283 // implicitly. This can happen with a qualified call to a member 6284 // function, e.g., X::f(). We use an empty type for the implied 6285 // object argument (C++ [over.call.func]p3), and the acting context 6286 // is irrelevant. 6287 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6288 Expr::Classification::makeSimpleLValue(), Args, 6289 CandidateSet, SuppressUserConversions, 6290 PartialOverloading, EarlyConversions, PO); 6291 return; 6292 } 6293 // We treat a constructor like a non-member function, since its object 6294 // argument doesn't participate in overload resolution. 6295 } 6296 6297 if (!CandidateSet.isNewCandidate(Function, PO)) 6298 return; 6299 6300 // C++11 [class.copy]p11: [DR1402] 6301 // A defaulted move constructor that is defined as deleted is ignored by 6302 // overload resolution. 6303 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6304 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6305 Constructor->isMoveConstructor()) 6306 return; 6307 6308 // Overload resolution is always an unevaluated context. 6309 EnterExpressionEvaluationContext Unevaluated( 6310 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6311 6312 // C++ [over.match.oper]p3: 6313 // if no operand has a class type, only those non-member functions in the 6314 // lookup set that have a first parameter of type T1 or "reference to 6315 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6316 // is a right operand) a second parameter of type T2 or "reference to 6317 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6318 // candidate functions. 6319 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6320 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6321 return; 6322 6323 // Add this candidate 6324 OverloadCandidate &Candidate = 6325 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6326 Candidate.FoundDecl = FoundDecl; 6327 Candidate.Function = Function; 6328 Candidate.Viable = true; 6329 Candidate.RewriteKind = 6330 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6331 Candidate.IsSurrogate = false; 6332 Candidate.IsADLCandidate = IsADLCandidate; 6333 Candidate.IgnoreObjectArgument = false; 6334 Candidate.ExplicitCallArguments = Args.size(); 6335 6336 // Explicit functions are not actually candidates at all if we're not 6337 // allowing them in this context, but keep them around so we can point 6338 // to them in diagnostics. 6339 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6340 Candidate.Viable = false; 6341 Candidate.FailureKind = ovl_fail_explicit; 6342 return; 6343 } 6344 6345 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6346 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6347 Candidate.Viable = false; 6348 Candidate.FailureKind = ovl_non_default_multiversion_function; 6349 return; 6350 } 6351 6352 if (Constructor) { 6353 // C++ [class.copy]p3: 6354 // A member function template is never instantiated to perform the copy 6355 // of a class object to an object of its class type. 6356 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6357 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6358 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6359 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6360 ClassType))) { 6361 Candidate.Viable = false; 6362 Candidate.FailureKind = ovl_fail_illegal_constructor; 6363 return; 6364 } 6365 6366 // C++ [over.match.funcs]p8: (proposed DR resolution) 6367 // A constructor inherited from class type C that has a first parameter 6368 // of type "reference to P" (including such a constructor instantiated 6369 // from a template) is excluded from the set of candidate functions when 6370 // constructing an object of type cv D if the argument list has exactly 6371 // one argument and D is reference-related to P and P is reference-related 6372 // to C. 6373 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6374 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6375 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6376 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6377 QualType C = Context.getRecordType(Constructor->getParent()); 6378 QualType D = Context.getRecordType(Shadow->getParent()); 6379 SourceLocation Loc = Args.front()->getExprLoc(); 6380 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6381 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6382 Candidate.Viable = false; 6383 Candidate.FailureKind = ovl_fail_inhctor_slice; 6384 return; 6385 } 6386 } 6387 6388 // Check that the constructor is capable of constructing an object in the 6389 // destination address space. 6390 if (!Qualifiers::isAddressSpaceSupersetOf( 6391 Constructor->getMethodQualifiers().getAddressSpace(), 6392 CandidateSet.getDestAS())) { 6393 Candidate.Viable = false; 6394 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6395 } 6396 } 6397 6398 unsigned NumParams = Proto->getNumParams(); 6399 6400 // (C++ 13.3.2p2): A candidate function having fewer than m 6401 // parameters is viable only if it has an ellipsis in its parameter 6402 // list (8.3.5). 6403 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6404 !Proto->isVariadic()) { 6405 Candidate.Viable = false; 6406 Candidate.FailureKind = ovl_fail_too_many_arguments; 6407 return; 6408 } 6409 6410 // (C++ 13.3.2p2): A candidate function having more than m parameters 6411 // is viable only if the (m+1)st parameter has a default argument 6412 // (8.3.6). For the purposes of overload resolution, the 6413 // parameter list is truncated on the right, so that there are 6414 // exactly m parameters. 6415 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6416 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6417 // Not enough arguments. 6418 Candidate.Viable = false; 6419 Candidate.FailureKind = ovl_fail_too_few_arguments; 6420 return; 6421 } 6422 6423 // (CUDA B.1): Check for invalid calls between targets. 6424 if (getLangOpts().CUDA) 6425 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6426 // Skip the check for callers that are implicit members, because in this 6427 // case we may not yet know what the member's target is; the target is 6428 // inferred for the member automatically, based on the bases and fields of 6429 // the class. 6430 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6431 Candidate.Viable = false; 6432 Candidate.FailureKind = ovl_fail_bad_target; 6433 return; 6434 } 6435 6436 if (Function->getTrailingRequiresClause()) { 6437 ConstraintSatisfaction Satisfaction; 6438 if (CheckFunctionConstraints(Function, Satisfaction) || 6439 !Satisfaction.IsSatisfied) { 6440 Candidate.Viable = false; 6441 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6442 return; 6443 } 6444 } 6445 6446 // Determine the implicit conversion sequences for each of the 6447 // arguments. 6448 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6449 unsigned ConvIdx = 6450 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6451 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6452 // We already formed a conversion sequence for this parameter during 6453 // template argument deduction. 6454 } else if (ArgIdx < NumParams) { 6455 // (C++ 13.3.2p3): for F to be a viable function, there shall 6456 // exist for each argument an implicit conversion sequence 6457 // (13.3.3.1) that converts that argument to the corresponding 6458 // parameter of F. 6459 QualType ParamType = Proto->getParamType(ArgIdx); 6460 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6461 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6462 /*InOverloadResolution=*/true, 6463 /*AllowObjCWritebackConversion=*/ 6464 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6465 if (Candidate.Conversions[ConvIdx].isBad()) { 6466 Candidate.Viable = false; 6467 Candidate.FailureKind = ovl_fail_bad_conversion; 6468 return; 6469 } 6470 } else { 6471 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6472 // argument for which there is no corresponding parameter is 6473 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6474 Candidate.Conversions[ConvIdx].setEllipsis(); 6475 } 6476 } 6477 6478 if (EnableIfAttr *FailedAttr = 6479 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6480 Candidate.Viable = false; 6481 Candidate.FailureKind = ovl_fail_enable_if; 6482 Candidate.DeductionFailure.Data = FailedAttr; 6483 return; 6484 } 6485 6486 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6487 Candidate.Viable = false; 6488 Candidate.FailureKind = ovl_fail_ext_disabled; 6489 return; 6490 } 6491 } 6492 6493 ObjCMethodDecl * 6494 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6495 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6496 if (Methods.size() <= 1) 6497 return nullptr; 6498 6499 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6500 bool Match = true; 6501 ObjCMethodDecl *Method = Methods[b]; 6502 unsigned NumNamedArgs = Sel.getNumArgs(); 6503 // Method might have more arguments than selector indicates. This is due 6504 // to addition of c-style arguments in method. 6505 if (Method->param_size() > NumNamedArgs) 6506 NumNamedArgs = Method->param_size(); 6507 if (Args.size() < NumNamedArgs) 6508 continue; 6509 6510 for (unsigned i = 0; i < NumNamedArgs; i++) { 6511 // We can't do any type-checking on a type-dependent argument. 6512 if (Args[i]->isTypeDependent()) { 6513 Match = false; 6514 break; 6515 } 6516 6517 ParmVarDecl *param = Method->parameters()[i]; 6518 Expr *argExpr = Args[i]; 6519 assert(argExpr && "SelectBestMethod(): missing expression"); 6520 6521 // Strip the unbridged-cast placeholder expression off unless it's 6522 // a consumed argument. 6523 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6524 !param->hasAttr<CFConsumedAttr>()) 6525 argExpr = stripARCUnbridgedCast(argExpr); 6526 6527 // If the parameter is __unknown_anytype, move on to the next method. 6528 if (param->getType() == Context.UnknownAnyTy) { 6529 Match = false; 6530 break; 6531 } 6532 6533 ImplicitConversionSequence ConversionState 6534 = TryCopyInitialization(*this, argExpr, param->getType(), 6535 /*SuppressUserConversions*/false, 6536 /*InOverloadResolution=*/true, 6537 /*AllowObjCWritebackConversion=*/ 6538 getLangOpts().ObjCAutoRefCount, 6539 /*AllowExplicit*/false); 6540 // This function looks for a reasonably-exact match, so we consider 6541 // incompatible pointer conversions to be a failure here. 6542 if (ConversionState.isBad() || 6543 (ConversionState.isStandard() && 6544 ConversionState.Standard.Second == 6545 ICK_Incompatible_Pointer_Conversion)) { 6546 Match = false; 6547 break; 6548 } 6549 } 6550 // Promote additional arguments to variadic methods. 6551 if (Match && Method->isVariadic()) { 6552 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6553 if (Args[i]->isTypeDependent()) { 6554 Match = false; 6555 break; 6556 } 6557 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6558 nullptr); 6559 if (Arg.isInvalid()) { 6560 Match = false; 6561 break; 6562 } 6563 } 6564 } else { 6565 // Check for extra arguments to non-variadic methods. 6566 if (Args.size() != NumNamedArgs) 6567 Match = false; 6568 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6569 // Special case when selectors have no argument. In this case, select 6570 // one with the most general result type of 'id'. 6571 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6572 QualType ReturnT = Methods[b]->getReturnType(); 6573 if (ReturnT->isObjCIdType()) 6574 return Methods[b]; 6575 } 6576 } 6577 } 6578 6579 if (Match) 6580 return Method; 6581 } 6582 return nullptr; 6583 } 6584 6585 static bool convertArgsForAvailabilityChecks( 6586 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6587 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6588 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6589 if (ThisArg) { 6590 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6591 assert(!isa<CXXConstructorDecl>(Method) && 6592 "Shouldn't have `this` for ctors!"); 6593 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6594 ExprResult R = S.PerformObjectArgumentInitialization( 6595 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6596 if (R.isInvalid()) 6597 return false; 6598 ConvertedThis = R.get(); 6599 } else { 6600 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6601 (void)MD; 6602 assert((MissingImplicitThis || MD->isStatic() || 6603 isa<CXXConstructorDecl>(MD)) && 6604 "Expected `this` for non-ctor instance methods"); 6605 } 6606 ConvertedThis = nullptr; 6607 } 6608 6609 // Ignore any variadic arguments. Converting them is pointless, since the 6610 // user can't refer to them in the function condition. 6611 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6612 6613 // Convert the arguments. 6614 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6615 ExprResult R; 6616 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6617 S.Context, Function->getParamDecl(I)), 6618 SourceLocation(), Args[I]); 6619 6620 if (R.isInvalid()) 6621 return false; 6622 6623 ConvertedArgs.push_back(R.get()); 6624 } 6625 6626 if (Trap.hasErrorOccurred()) 6627 return false; 6628 6629 // Push default arguments if needed. 6630 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6631 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6632 ParmVarDecl *P = Function->getParamDecl(i); 6633 if (!P->hasDefaultArg()) 6634 return false; 6635 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6636 if (R.isInvalid()) 6637 return false; 6638 ConvertedArgs.push_back(R.get()); 6639 } 6640 6641 if (Trap.hasErrorOccurred()) 6642 return false; 6643 } 6644 return true; 6645 } 6646 6647 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6648 SourceLocation CallLoc, 6649 ArrayRef<Expr *> Args, 6650 bool MissingImplicitThis) { 6651 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6652 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6653 return nullptr; 6654 6655 SFINAETrap Trap(*this); 6656 SmallVector<Expr *, 16> ConvertedArgs; 6657 // FIXME: We should look into making enable_if late-parsed. 6658 Expr *DiscardedThis; 6659 if (!convertArgsForAvailabilityChecks( 6660 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6661 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6662 return *EnableIfAttrs.begin(); 6663 6664 for (auto *EIA : EnableIfAttrs) { 6665 APValue Result; 6666 // FIXME: This doesn't consider value-dependent cases, because doing so is 6667 // very difficult. Ideally, we should handle them more gracefully. 6668 if (EIA->getCond()->isValueDependent() || 6669 !EIA->getCond()->EvaluateWithSubstitution( 6670 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6671 return EIA; 6672 6673 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6674 return EIA; 6675 } 6676 return nullptr; 6677 } 6678 6679 template <typename CheckFn> 6680 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6681 bool ArgDependent, SourceLocation Loc, 6682 CheckFn &&IsSuccessful) { 6683 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6684 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6685 if (ArgDependent == DIA->getArgDependent()) 6686 Attrs.push_back(DIA); 6687 } 6688 6689 // Common case: No diagnose_if attributes, so we can quit early. 6690 if (Attrs.empty()) 6691 return false; 6692 6693 auto WarningBegin = std::stable_partition( 6694 Attrs.begin(), Attrs.end(), 6695 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6696 6697 // Note that diagnose_if attributes are late-parsed, so they appear in the 6698 // correct order (unlike enable_if attributes). 6699 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6700 IsSuccessful); 6701 if (ErrAttr != WarningBegin) { 6702 const DiagnoseIfAttr *DIA = *ErrAttr; 6703 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6704 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6705 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6706 return true; 6707 } 6708 6709 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6710 if (IsSuccessful(DIA)) { 6711 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6712 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6713 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6714 } 6715 6716 return false; 6717 } 6718 6719 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6720 const Expr *ThisArg, 6721 ArrayRef<const Expr *> Args, 6722 SourceLocation Loc) { 6723 return diagnoseDiagnoseIfAttrsWith( 6724 *this, Function, /*ArgDependent=*/true, Loc, 6725 [&](const DiagnoseIfAttr *DIA) { 6726 APValue Result; 6727 // It's sane to use the same Args for any redecl of this function, since 6728 // EvaluateWithSubstitution only cares about the position of each 6729 // argument in the arg list, not the ParmVarDecl* it maps to. 6730 if (!DIA->getCond()->EvaluateWithSubstitution( 6731 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6732 return false; 6733 return Result.isInt() && Result.getInt().getBoolValue(); 6734 }); 6735 } 6736 6737 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6738 SourceLocation Loc) { 6739 return diagnoseDiagnoseIfAttrsWith( 6740 *this, ND, /*ArgDependent=*/false, Loc, 6741 [&](const DiagnoseIfAttr *DIA) { 6742 bool Result; 6743 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6744 Result; 6745 }); 6746 } 6747 6748 /// Add all of the function declarations in the given function set to 6749 /// the overload candidate set. 6750 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6751 ArrayRef<Expr *> Args, 6752 OverloadCandidateSet &CandidateSet, 6753 TemplateArgumentListInfo *ExplicitTemplateArgs, 6754 bool SuppressUserConversions, 6755 bool PartialOverloading, 6756 bool FirstArgumentIsBase) { 6757 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6758 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6759 ArrayRef<Expr *> FunctionArgs = Args; 6760 6761 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6762 FunctionDecl *FD = 6763 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6764 6765 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6766 QualType ObjectType; 6767 Expr::Classification ObjectClassification; 6768 if (Args.size() > 0) { 6769 if (Expr *E = Args[0]) { 6770 // Use the explicit base to restrict the lookup: 6771 ObjectType = E->getType(); 6772 // Pointers in the object arguments are implicitly dereferenced, so we 6773 // always classify them as l-values. 6774 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6775 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6776 else 6777 ObjectClassification = E->Classify(Context); 6778 } // .. else there is an implicit base. 6779 FunctionArgs = Args.slice(1); 6780 } 6781 if (FunTmpl) { 6782 AddMethodTemplateCandidate( 6783 FunTmpl, F.getPair(), 6784 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6785 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6786 FunctionArgs, CandidateSet, SuppressUserConversions, 6787 PartialOverloading); 6788 } else { 6789 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6790 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6791 ObjectClassification, FunctionArgs, CandidateSet, 6792 SuppressUserConversions, PartialOverloading); 6793 } 6794 } else { 6795 // This branch handles both standalone functions and static methods. 6796 6797 // Slice the first argument (which is the base) when we access 6798 // static method as non-static. 6799 if (Args.size() > 0 && 6800 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6801 !isa<CXXConstructorDecl>(FD)))) { 6802 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6803 FunctionArgs = Args.slice(1); 6804 } 6805 if (FunTmpl) { 6806 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6807 ExplicitTemplateArgs, FunctionArgs, 6808 CandidateSet, SuppressUserConversions, 6809 PartialOverloading); 6810 } else { 6811 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6812 SuppressUserConversions, PartialOverloading); 6813 } 6814 } 6815 } 6816 } 6817 6818 /// AddMethodCandidate - Adds a named decl (which is some kind of 6819 /// method) as a method candidate to the given overload set. 6820 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6821 Expr::Classification ObjectClassification, 6822 ArrayRef<Expr *> Args, 6823 OverloadCandidateSet &CandidateSet, 6824 bool SuppressUserConversions, 6825 OverloadCandidateParamOrder PO) { 6826 NamedDecl *Decl = FoundDecl.getDecl(); 6827 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6828 6829 if (isa<UsingShadowDecl>(Decl)) 6830 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6831 6832 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6833 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6834 "Expected a member function template"); 6835 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6836 /*ExplicitArgs*/ nullptr, ObjectType, 6837 ObjectClassification, Args, CandidateSet, 6838 SuppressUserConversions, false, PO); 6839 } else { 6840 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6841 ObjectType, ObjectClassification, Args, CandidateSet, 6842 SuppressUserConversions, false, None, PO); 6843 } 6844 } 6845 6846 /// AddMethodCandidate - Adds the given C++ member function to the set 6847 /// of candidate functions, using the given function call arguments 6848 /// and the object argument (@c Object). For example, in a call 6849 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6850 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6851 /// allow user-defined conversions via constructors or conversion 6852 /// operators. 6853 void 6854 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6855 CXXRecordDecl *ActingContext, QualType ObjectType, 6856 Expr::Classification ObjectClassification, 6857 ArrayRef<Expr *> Args, 6858 OverloadCandidateSet &CandidateSet, 6859 bool SuppressUserConversions, 6860 bool PartialOverloading, 6861 ConversionSequenceList EarlyConversions, 6862 OverloadCandidateParamOrder PO) { 6863 const FunctionProtoType *Proto 6864 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6865 assert(Proto && "Methods without a prototype cannot be overloaded"); 6866 assert(!isa<CXXConstructorDecl>(Method) && 6867 "Use AddOverloadCandidate for constructors"); 6868 6869 if (!CandidateSet.isNewCandidate(Method, PO)) 6870 return; 6871 6872 // C++11 [class.copy]p23: [DR1402] 6873 // A defaulted move assignment operator that is defined as deleted is 6874 // ignored by overload resolution. 6875 if (Method->isDefaulted() && Method->isDeleted() && 6876 Method->isMoveAssignmentOperator()) 6877 return; 6878 6879 // Overload resolution is always an unevaluated context. 6880 EnterExpressionEvaluationContext Unevaluated( 6881 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6882 6883 // Add this candidate 6884 OverloadCandidate &Candidate = 6885 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6886 Candidate.FoundDecl = FoundDecl; 6887 Candidate.Function = Method; 6888 Candidate.RewriteKind = 6889 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6890 Candidate.IsSurrogate = false; 6891 Candidate.IgnoreObjectArgument = false; 6892 Candidate.ExplicitCallArguments = Args.size(); 6893 6894 unsigned NumParams = Proto->getNumParams(); 6895 6896 // (C++ 13.3.2p2): A candidate function having fewer than m 6897 // parameters is viable only if it has an ellipsis in its parameter 6898 // list (8.3.5). 6899 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6900 !Proto->isVariadic()) { 6901 Candidate.Viable = false; 6902 Candidate.FailureKind = ovl_fail_too_many_arguments; 6903 return; 6904 } 6905 6906 // (C++ 13.3.2p2): A candidate function having more than m parameters 6907 // is viable only if the (m+1)st parameter has a default argument 6908 // (8.3.6). For the purposes of overload resolution, the 6909 // parameter list is truncated on the right, so that there are 6910 // exactly m parameters. 6911 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6912 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6913 // Not enough arguments. 6914 Candidate.Viable = false; 6915 Candidate.FailureKind = ovl_fail_too_few_arguments; 6916 return; 6917 } 6918 6919 Candidate.Viable = true; 6920 6921 if (Method->isStatic() || ObjectType.isNull()) 6922 // The implicit object argument is ignored. 6923 Candidate.IgnoreObjectArgument = true; 6924 else { 6925 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6926 // Determine the implicit conversion sequence for the object 6927 // parameter. 6928 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6929 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6930 Method, ActingContext); 6931 if (Candidate.Conversions[ConvIdx].isBad()) { 6932 Candidate.Viable = false; 6933 Candidate.FailureKind = ovl_fail_bad_conversion; 6934 return; 6935 } 6936 } 6937 6938 // (CUDA B.1): Check for invalid calls between targets. 6939 if (getLangOpts().CUDA) 6940 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6941 if (!IsAllowedCUDACall(Caller, Method)) { 6942 Candidate.Viable = false; 6943 Candidate.FailureKind = ovl_fail_bad_target; 6944 return; 6945 } 6946 6947 if (Method->getTrailingRequiresClause()) { 6948 ConstraintSatisfaction Satisfaction; 6949 if (CheckFunctionConstraints(Method, Satisfaction) || 6950 !Satisfaction.IsSatisfied) { 6951 Candidate.Viable = false; 6952 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6953 return; 6954 } 6955 } 6956 6957 // Determine the implicit conversion sequences for each of the 6958 // arguments. 6959 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6960 unsigned ConvIdx = 6961 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6962 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6963 // We already formed a conversion sequence for this parameter during 6964 // template argument deduction. 6965 } else if (ArgIdx < NumParams) { 6966 // (C++ 13.3.2p3): for F to be a viable function, there shall 6967 // exist for each argument an implicit conversion sequence 6968 // (13.3.3.1) that converts that argument to the corresponding 6969 // parameter of F. 6970 QualType ParamType = Proto->getParamType(ArgIdx); 6971 Candidate.Conversions[ConvIdx] 6972 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6973 SuppressUserConversions, 6974 /*InOverloadResolution=*/true, 6975 /*AllowObjCWritebackConversion=*/ 6976 getLangOpts().ObjCAutoRefCount); 6977 if (Candidate.Conversions[ConvIdx].isBad()) { 6978 Candidate.Viable = false; 6979 Candidate.FailureKind = ovl_fail_bad_conversion; 6980 return; 6981 } 6982 } else { 6983 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6984 // argument for which there is no corresponding parameter is 6985 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6986 Candidate.Conversions[ConvIdx].setEllipsis(); 6987 } 6988 } 6989 6990 if (EnableIfAttr *FailedAttr = 6991 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6992 Candidate.Viable = false; 6993 Candidate.FailureKind = ovl_fail_enable_if; 6994 Candidate.DeductionFailure.Data = FailedAttr; 6995 return; 6996 } 6997 6998 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6999 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 7000 Candidate.Viable = false; 7001 Candidate.FailureKind = ovl_non_default_multiversion_function; 7002 } 7003 } 7004 7005 /// Add a C++ member function template as a candidate to the candidate 7006 /// set, using template argument deduction to produce an appropriate member 7007 /// function template specialization. 7008 void Sema::AddMethodTemplateCandidate( 7009 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7010 CXXRecordDecl *ActingContext, 7011 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7012 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7013 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7014 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7015 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7016 return; 7017 7018 // C++ [over.match.funcs]p7: 7019 // In each case where a candidate is a function template, candidate 7020 // function template specializations are generated using template argument 7021 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7022 // candidate functions in the usual way.113) A given name can refer to one 7023 // or more function templates and also to a set of overloaded non-template 7024 // functions. In such a case, the candidate functions generated from each 7025 // function template are combined with the set of non-template candidate 7026 // functions. 7027 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7028 FunctionDecl *Specialization = nullptr; 7029 ConversionSequenceList Conversions; 7030 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7031 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7032 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7033 return CheckNonDependentConversions( 7034 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7035 SuppressUserConversions, ActingContext, ObjectType, 7036 ObjectClassification, PO); 7037 })) { 7038 OverloadCandidate &Candidate = 7039 CandidateSet.addCandidate(Conversions.size(), Conversions); 7040 Candidate.FoundDecl = FoundDecl; 7041 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7042 Candidate.Viable = false; 7043 Candidate.RewriteKind = 7044 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7045 Candidate.IsSurrogate = false; 7046 Candidate.IgnoreObjectArgument = 7047 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7048 ObjectType.isNull(); 7049 Candidate.ExplicitCallArguments = Args.size(); 7050 if (Result == TDK_NonDependentConversionFailure) 7051 Candidate.FailureKind = ovl_fail_bad_conversion; 7052 else { 7053 Candidate.FailureKind = ovl_fail_bad_deduction; 7054 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7055 Info); 7056 } 7057 return; 7058 } 7059 7060 // Add the function template specialization produced by template argument 7061 // deduction as a candidate. 7062 assert(Specialization && "Missing member function template specialization?"); 7063 assert(isa<CXXMethodDecl>(Specialization) && 7064 "Specialization is not a member function?"); 7065 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7066 ActingContext, ObjectType, ObjectClassification, Args, 7067 CandidateSet, SuppressUserConversions, PartialOverloading, 7068 Conversions, PO); 7069 } 7070 7071 /// Determine whether a given function template has a simple explicit specifier 7072 /// or a non-value-dependent explicit-specification that evaluates to true. 7073 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7074 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7075 } 7076 7077 /// Add a C++ function template specialization as a candidate 7078 /// in the candidate set, using template argument deduction to produce 7079 /// an appropriate function template specialization. 7080 void Sema::AddTemplateOverloadCandidate( 7081 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7082 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7083 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7084 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7085 OverloadCandidateParamOrder PO) { 7086 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7087 return; 7088 7089 // If the function template has a non-dependent explicit specification, 7090 // exclude it now if appropriate; we are not permitted to perform deduction 7091 // and substitution in this case. 7092 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7093 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7094 Candidate.FoundDecl = FoundDecl; 7095 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7096 Candidate.Viable = false; 7097 Candidate.FailureKind = ovl_fail_explicit; 7098 return; 7099 } 7100 7101 // C++ [over.match.funcs]p7: 7102 // In each case where a candidate is a function template, candidate 7103 // function template specializations are generated using template argument 7104 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7105 // candidate functions in the usual way.113) A given name can refer to one 7106 // or more function templates and also to a set of overloaded non-template 7107 // functions. In such a case, the candidate functions generated from each 7108 // function template are combined with the set of non-template candidate 7109 // functions. 7110 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7111 FunctionDecl *Specialization = nullptr; 7112 ConversionSequenceList Conversions; 7113 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7114 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7115 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7116 return CheckNonDependentConversions( 7117 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7118 SuppressUserConversions, nullptr, QualType(), {}, PO); 7119 })) { 7120 OverloadCandidate &Candidate = 7121 CandidateSet.addCandidate(Conversions.size(), Conversions); 7122 Candidate.FoundDecl = FoundDecl; 7123 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7124 Candidate.Viable = false; 7125 Candidate.RewriteKind = 7126 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7127 Candidate.IsSurrogate = false; 7128 Candidate.IsADLCandidate = IsADLCandidate; 7129 // Ignore the object argument if there is one, since we don't have an object 7130 // type. 7131 Candidate.IgnoreObjectArgument = 7132 isa<CXXMethodDecl>(Candidate.Function) && 7133 !isa<CXXConstructorDecl>(Candidate.Function); 7134 Candidate.ExplicitCallArguments = Args.size(); 7135 if (Result == TDK_NonDependentConversionFailure) 7136 Candidate.FailureKind = ovl_fail_bad_conversion; 7137 else { 7138 Candidate.FailureKind = ovl_fail_bad_deduction; 7139 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7140 Info); 7141 } 7142 return; 7143 } 7144 7145 // Add the function template specialization produced by template argument 7146 // deduction as a candidate. 7147 assert(Specialization && "Missing function template specialization?"); 7148 AddOverloadCandidate( 7149 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7150 PartialOverloading, AllowExplicit, 7151 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7152 } 7153 7154 /// Check that implicit conversion sequences can be formed for each argument 7155 /// whose corresponding parameter has a non-dependent type, per DR1391's 7156 /// [temp.deduct.call]p10. 7157 bool Sema::CheckNonDependentConversions( 7158 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7159 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7160 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7161 CXXRecordDecl *ActingContext, QualType ObjectType, 7162 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7163 // FIXME: The cases in which we allow explicit conversions for constructor 7164 // arguments never consider calling a constructor template. It's not clear 7165 // that is correct. 7166 const bool AllowExplicit = false; 7167 7168 auto *FD = FunctionTemplate->getTemplatedDecl(); 7169 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7170 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7171 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7172 7173 Conversions = 7174 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7175 7176 // Overload resolution is always an unevaluated context. 7177 EnterExpressionEvaluationContext Unevaluated( 7178 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7179 7180 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7181 // require that, but this check should never result in a hard error, and 7182 // overload resolution is permitted to sidestep instantiations. 7183 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7184 !ObjectType.isNull()) { 7185 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7186 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7187 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7188 Method, ActingContext); 7189 if (Conversions[ConvIdx].isBad()) 7190 return true; 7191 } 7192 7193 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7194 ++I) { 7195 QualType ParamType = ParamTypes[I]; 7196 if (!ParamType->isDependentType()) { 7197 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7198 ? 0 7199 : (ThisConversions + I); 7200 Conversions[ConvIdx] 7201 = TryCopyInitialization(*this, Args[I], ParamType, 7202 SuppressUserConversions, 7203 /*InOverloadResolution=*/true, 7204 /*AllowObjCWritebackConversion=*/ 7205 getLangOpts().ObjCAutoRefCount, 7206 AllowExplicit); 7207 if (Conversions[ConvIdx].isBad()) 7208 return true; 7209 } 7210 } 7211 7212 return false; 7213 } 7214 7215 /// Determine whether this is an allowable conversion from the result 7216 /// of an explicit conversion operator to the expected type, per C++ 7217 /// [over.match.conv]p1 and [over.match.ref]p1. 7218 /// 7219 /// \param ConvType The return type of the conversion function. 7220 /// 7221 /// \param ToType The type we are converting to. 7222 /// 7223 /// \param AllowObjCPointerConversion Allow a conversion from one 7224 /// Objective-C pointer to another. 7225 /// 7226 /// \returns true if the conversion is allowable, false otherwise. 7227 static bool isAllowableExplicitConversion(Sema &S, 7228 QualType ConvType, QualType ToType, 7229 bool AllowObjCPointerConversion) { 7230 QualType ToNonRefType = ToType.getNonReferenceType(); 7231 7232 // Easy case: the types are the same. 7233 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7234 return true; 7235 7236 // Allow qualification conversions. 7237 bool ObjCLifetimeConversion; 7238 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7239 ObjCLifetimeConversion)) 7240 return true; 7241 7242 // If we're not allowed to consider Objective-C pointer conversions, 7243 // we're done. 7244 if (!AllowObjCPointerConversion) 7245 return false; 7246 7247 // Is this an Objective-C pointer conversion? 7248 bool IncompatibleObjC = false; 7249 QualType ConvertedType; 7250 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7251 IncompatibleObjC); 7252 } 7253 7254 /// AddConversionCandidate - Add a C++ conversion function as a 7255 /// candidate in the candidate set (C++ [over.match.conv], 7256 /// C++ [over.match.copy]). From is the expression we're converting from, 7257 /// and ToType is the type that we're eventually trying to convert to 7258 /// (which may or may not be the same type as the type that the 7259 /// conversion function produces). 7260 void Sema::AddConversionCandidate( 7261 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7262 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7263 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7264 bool AllowExplicit, bool AllowResultConversion) { 7265 assert(!Conversion->getDescribedFunctionTemplate() && 7266 "Conversion function templates use AddTemplateConversionCandidate"); 7267 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7268 if (!CandidateSet.isNewCandidate(Conversion)) 7269 return; 7270 7271 // If the conversion function has an undeduced return type, trigger its 7272 // deduction now. 7273 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7274 if (DeduceReturnType(Conversion, From->getExprLoc())) 7275 return; 7276 ConvType = Conversion->getConversionType().getNonReferenceType(); 7277 } 7278 7279 // If we don't allow any conversion of the result type, ignore conversion 7280 // functions that don't convert to exactly (possibly cv-qualified) T. 7281 if (!AllowResultConversion && 7282 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7283 return; 7284 7285 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7286 // operator is only a candidate if its return type is the target type or 7287 // can be converted to the target type with a qualification conversion. 7288 // 7289 // FIXME: Include such functions in the candidate list and explain why we 7290 // can't select them. 7291 if (Conversion->isExplicit() && 7292 !isAllowableExplicitConversion(*this, ConvType, ToType, 7293 AllowObjCConversionOnExplicit)) 7294 return; 7295 7296 // Overload resolution is always an unevaluated context. 7297 EnterExpressionEvaluationContext Unevaluated( 7298 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7299 7300 // Add this candidate 7301 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7302 Candidate.FoundDecl = FoundDecl; 7303 Candidate.Function = Conversion; 7304 Candidate.IsSurrogate = false; 7305 Candidate.IgnoreObjectArgument = false; 7306 Candidate.FinalConversion.setAsIdentityConversion(); 7307 Candidate.FinalConversion.setFromType(ConvType); 7308 Candidate.FinalConversion.setAllToTypes(ToType); 7309 Candidate.Viable = true; 7310 Candidate.ExplicitCallArguments = 1; 7311 7312 // Explicit functions are not actually candidates at all if we're not 7313 // allowing them in this context, but keep them around so we can point 7314 // to them in diagnostics. 7315 if (!AllowExplicit && Conversion->isExplicit()) { 7316 Candidate.Viable = false; 7317 Candidate.FailureKind = ovl_fail_explicit; 7318 return; 7319 } 7320 7321 // C++ [over.match.funcs]p4: 7322 // For conversion functions, the function is considered to be a member of 7323 // the class of the implicit implied object argument for the purpose of 7324 // defining the type of the implicit object parameter. 7325 // 7326 // Determine the implicit conversion sequence for the implicit 7327 // object parameter. 7328 QualType ImplicitParamType = From->getType(); 7329 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7330 ImplicitParamType = FromPtrType->getPointeeType(); 7331 CXXRecordDecl *ConversionContext 7332 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7333 7334 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7335 *this, CandidateSet.getLocation(), From->getType(), 7336 From->Classify(Context), Conversion, ConversionContext); 7337 7338 if (Candidate.Conversions[0].isBad()) { 7339 Candidate.Viable = false; 7340 Candidate.FailureKind = ovl_fail_bad_conversion; 7341 return; 7342 } 7343 7344 if (Conversion->getTrailingRequiresClause()) { 7345 ConstraintSatisfaction Satisfaction; 7346 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7347 !Satisfaction.IsSatisfied) { 7348 Candidate.Viable = false; 7349 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7350 return; 7351 } 7352 } 7353 7354 // We won't go through a user-defined type conversion function to convert a 7355 // derived to base as such conversions are given Conversion Rank. They only 7356 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7357 QualType FromCanon 7358 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7359 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7360 if (FromCanon == ToCanon || 7361 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7362 Candidate.Viable = false; 7363 Candidate.FailureKind = ovl_fail_trivial_conversion; 7364 return; 7365 } 7366 7367 // To determine what the conversion from the result of calling the 7368 // conversion function to the type we're eventually trying to 7369 // convert to (ToType), we need to synthesize a call to the 7370 // conversion function and attempt copy initialization from it. This 7371 // makes sure that we get the right semantics with respect to 7372 // lvalues/rvalues and the type. Fortunately, we can allocate this 7373 // call on the stack and we don't need its arguments to be 7374 // well-formed. 7375 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7376 VK_LValue, From->getBeginLoc()); 7377 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7378 Context.getPointerType(Conversion->getType()), 7379 CK_FunctionToPointerDecay, &ConversionRef, 7380 VK_RValue, FPOptionsOverride()); 7381 7382 QualType ConversionType = Conversion->getConversionType(); 7383 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7384 Candidate.Viable = false; 7385 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7386 return; 7387 } 7388 7389 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7390 7391 // Note that it is safe to allocate CallExpr on the stack here because 7392 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7393 // allocator). 7394 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7395 7396 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7397 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7398 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7399 7400 ImplicitConversionSequence ICS = 7401 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7402 /*SuppressUserConversions=*/true, 7403 /*InOverloadResolution=*/false, 7404 /*AllowObjCWritebackConversion=*/false); 7405 7406 switch (ICS.getKind()) { 7407 case ImplicitConversionSequence::StandardConversion: 7408 Candidate.FinalConversion = ICS.Standard; 7409 7410 // C++ [over.ics.user]p3: 7411 // If the user-defined conversion is specified by a specialization of a 7412 // conversion function template, the second standard conversion sequence 7413 // shall have exact match rank. 7414 if (Conversion->getPrimaryTemplate() && 7415 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7416 Candidate.Viable = false; 7417 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7418 return; 7419 } 7420 7421 // C++0x [dcl.init.ref]p5: 7422 // In the second case, if the reference is an rvalue reference and 7423 // the second standard conversion sequence of the user-defined 7424 // conversion sequence includes an lvalue-to-rvalue conversion, the 7425 // program is ill-formed. 7426 if (ToType->isRValueReferenceType() && 7427 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7428 Candidate.Viable = false; 7429 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7430 return; 7431 } 7432 break; 7433 7434 case ImplicitConversionSequence::BadConversion: 7435 Candidate.Viable = false; 7436 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7437 return; 7438 7439 default: 7440 llvm_unreachable( 7441 "Can only end up with a standard conversion sequence or failure"); 7442 } 7443 7444 if (EnableIfAttr *FailedAttr = 7445 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7446 Candidate.Viable = false; 7447 Candidate.FailureKind = ovl_fail_enable_if; 7448 Candidate.DeductionFailure.Data = FailedAttr; 7449 return; 7450 } 7451 7452 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7453 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7454 Candidate.Viable = false; 7455 Candidate.FailureKind = ovl_non_default_multiversion_function; 7456 } 7457 } 7458 7459 /// Adds a conversion function template specialization 7460 /// candidate to the overload set, using template argument deduction 7461 /// to deduce the template arguments of the conversion function 7462 /// template from the type that we are converting to (C++ 7463 /// [temp.deduct.conv]). 7464 void Sema::AddTemplateConversionCandidate( 7465 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7466 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7467 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7468 bool AllowExplicit, bool AllowResultConversion) { 7469 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7470 "Only conversion function templates permitted here"); 7471 7472 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7473 return; 7474 7475 // If the function template has a non-dependent explicit specification, 7476 // exclude it now if appropriate; we are not permitted to perform deduction 7477 // and substitution in this case. 7478 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7479 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7480 Candidate.FoundDecl = FoundDecl; 7481 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7482 Candidate.Viable = false; 7483 Candidate.FailureKind = ovl_fail_explicit; 7484 return; 7485 } 7486 7487 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7488 CXXConversionDecl *Specialization = nullptr; 7489 if (TemplateDeductionResult Result 7490 = DeduceTemplateArguments(FunctionTemplate, ToType, 7491 Specialization, Info)) { 7492 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7493 Candidate.FoundDecl = FoundDecl; 7494 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7495 Candidate.Viable = false; 7496 Candidate.FailureKind = ovl_fail_bad_deduction; 7497 Candidate.IsSurrogate = false; 7498 Candidate.IgnoreObjectArgument = false; 7499 Candidate.ExplicitCallArguments = 1; 7500 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7501 Info); 7502 return; 7503 } 7504 7505 // Add the conversion function template specialization produced by 7506 // template argument deduction as a candidate. 7507 assert(Specialization && "Missing function template specialization?"); 7508 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7509 CandidateSet, AllowObjCConversionOnExplicit, 7510 AllowExplicit, AllowResultConversion); 7511 } 7512 7513 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7514 /// converts the given @c Object to a function pointer via the 7515 /// conversion function @c Conversion, and then attempts to call it 7516 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7517 /// the type of function that we'll eventually be calling. 7518 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7519 DeclAccessPair FoundDecl, 7520 CXXRecordDecl *ActingContext, 7521 const FunctionProtoType *Proto, 7522 Expr *Object, 7523 ArrayRef<Expr *> Args, 7524 OverloadCandidateSet& CandidateSet) { 7525 if (!CandidateSet.isNewCandidate(Conversion)) 7526 return; 7527 7528 // Overload resolution is always an unevaluated context. 7529 EnterExpressionEvaluationContext Unevaluated( 7530 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7531 7532 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7533 Candidate.FoundDecl = FoundDecl; 7534 Candidate.Function = nullptr; 7535 Candidate.Surrogate = Conversion; 7536 Candidate.Viable = true; 7537 Candidate.IsSurrogate = true; 7538 Candidate.IgnoreObjectArgument = false; 7539 Candidate.ExplicitCallArguments = Args.size(); 7540 7541 // Determine the implicit conversion sequence for the implicit 7542 // object parameter. 7543 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7544 *this, CandidateSet.getLocation(), Object->getType(), 7545 Object->Classify(Context), Conversion, ActingContext); 7546 if (ObjectInit.isBad()) { 7547 Candidate.Viable = false; 7548 Candidate.FailureKind = ovl_fail_bad_conversion; 7549 Candidate.Conversions[0] = ObjectInit; 7550 return; 7551 } 7552 7553 // The first conversion is actually a user-defined conversion whose 7554 // first conversion is ObjectInit's standard conversion (which is 7555 // effectively a reference binding). Record it as such. 7556 Candidate.Conversions[0].setUserDefined(); 7557 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7558 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7559 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7560 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7561 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7562 Candidate.Conversions[0].UserDefined.After 7563 = Candidate.Conversions[0].UserDefined.Before; 7564 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7565 7566 // Find the 7567 unsigned NumParams = Proto->getNumParams(); 7568 7569 // (C++ 13.3.2p2): A candidate function having fewer than m 7570 // parameters is viable only if it has an ellipsis in its parameter 7571 // list (8.3.5). 7572 if (Args.size() > NumParams && !Proto->isVariadic()) { 7573 Candidate.Viable = false; 7574 Candidate.FailureKind = ovl_fail_too_many_arguments; 7575 return; 7576 } 7577 7578 // Function types don't have any default arguments, so just check if 7579 // we have enough arguments. 7580 if (Args.size() < NumParams) { 7581 // Not enough arguments. 7582 Candidate.Viable = false; 7583 Candidate.FailureKind = ovl_fail_too_few_arguments; 7584 return; 7585 } 7586 7587 // Determine the implicit conversion sequences for each of the 7588 // arguments. 7589 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7590 if (ArgIdx < NumParams) { 7591 // (C++ 13.3.2p3): for F to be a viable function, there shall 7592 // exist for each argument an implicit conversion sequence 7593 // (13.3.3.1) that converts that argument to the corresponding 7594 // parameter of F. 7595 QualType ParamType = Proto->getParamType(ArgIdx); 7596 Candidate.Conversions[ArgIdx + 1] 7597 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7598 /*SuppressUserConversions=*/false, 7599 /*InOverloadResolution=*/false, 7600 /*AllowObjCWritebackConversion=*/ 7601 getLangOpts().ObjCAutoRefCount); 7602 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7603 Candidate.Viable = false; 7604 Candidate.FailureKind = ovl_fail_bad_conversion; 7605 return; 7606 } 7607 } else { 7608 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7609 // argument for which there is no corresponding parameter is 7610 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7611 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7612 } 7613 } 7614 7615 if (EnableIfAttr *FailedAttr = 7616 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7617 Candidate.Viable = false; 7618 Candidate.FailureKind = ovl_fail_enable_if; 7619 Candidate.DeductionFailure.Data = FailedAttr; 7620 return; 7621 } 7622 } 7623 7624 /// Add all of the non-member operator function declarations in the given 7625 /// function set to the overload candidate set. 7626 void Sema::AddNonMemberOperatorCandidates( 7627 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7628 OverloadCandidateSet &CandidateSet, 7629 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7630 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7631 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7632 ArrayRef<Expr *> FunctionArgs = Args; 7633 7634 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7635 FunctionDecl *FD = 7636 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7637 7638 // Don't consider rewritten functions if we're not rewriting. 7639 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7640 continue; 7641 7642 assert(!isa<CXXMethodDecl>(FD) && 7643 "unqualified operator lookup found a member function"); 7644 7645 if (FunTmpl) { 7646 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7647 FunctionArgs, CandidateSet); 7648 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7649 AddTemplateOverloadCandidate( 7650 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7651 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7652 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7653 } else { 7654 if (ExplicitTemplateArgs) 7655 continue; 7656 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7657 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7658 AddOverloadCandidate(FD, F.getPair(), 7659 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7660 false, false, true, false, ADLCallKind::NotADL, 7661 None, OverloadCandidateParamOrder::Reversed); 7662 } 7663 } 7664 } 7665 7666 /// Add overload candidates for overloaded operators that are 7667 /// member functions. 7668 /// 7669 /// Add the overloaded operator candidates that are member functions 7670 /// for the operator Op that was used in an operator expression such 7671 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7672 /// CandidateSet will store the added overload candidates. (C++ 7673 /// [over.match.oper]). 7674 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7675 SourceLocation OpLoc, 7676 ArrayRef<Expr *> Args, 7677 OverloadCandidateSet &CandidateSet, 7678 OverloadCandidateParamOrder PO) { 7679 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7680 7681 // C++ [over.match.oper]p3: 7682 // For a unary operator @ with an operand of a type whose 7683 // cv-unqualified version is T1, and for a binary operator @ with 7684 // a left operand of a type whose cv-unqualified version is T1 and 7685 // a right operand of a type whose cv-unqualified version is T2, 7686 // three sets of candidate functions, designated member 7687 // candidates, non-member candidates and built-in candidates, are 7688 // constructed as follows: 7689 QualType T1 = Args[0]->getType(); 7690 7691 // -- If T1 is a complete class type or a class currently being 7692 // defined, the set of member candidates is the result of the 7693 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7694 // the set of member candidates is empty. 7695 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7696 // Complete the type if it can be completed. 7697 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7698 return; 7699 // If the type is neither complete nor being defined, bail out now. 7700 if (!T1Rec->getDecl()->getDefinition()) 7701 return; 7702 7703 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7704 LookupQualifiedName(Operators, T1Rec->getDecl()); 7705 Operators.suppressDiagnostics(); 7706 7707 for (LookupResult::iterator Oper = Operators.begin(), 7708 OperEnd = Operators.end(); 7709 Oper != OperEnd; 7710 ++Oper) 7711 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7712 Args[0]->Classify(Context), Args.slice(1), 7713 CandidateSet, /*SuppressUserConversion=*/false, PO); 7714 } 7715 } 7716 7717 /// AddBuiltinCandidate - Add a candidate for a built-in 7718 /// operator. ResultTy and ParamTys are the result and parameter types 7719 /// of the built-in candidate, respectively. Args and NumArgs are the 7720 /// arguments being passed to the candidate. IsAssignmentOperator 7721 /// should be true when this built-in candidate is an assignment 7722 /// operator. NumContextualBoolArguments is the number of arguments 7723 /// (at the beginning of the argument list) that will be contextually 7724 /// converted to bool. 7725 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7726 OverloadCandidateSet& CandidateSet, 7727 bool IsAssignmentOperator, 7728 unsigned NumContextualBoolArguments) { 7729 // Overload resolution is always an unevaluated context. 7730 EnterExpressionEvaluationContext Unevaluated( 7731 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7732 7733 // Add this candidate 7734 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7735 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7736 Candidate.Function = nullptr; 7737 Candidate.IsSurrogate = false; 7738 Candidate.IgnoreObjectArgument = false; 7739 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7740 7741 // Determine the implicit conversion sequences for each of the 7742 // arguments. 7743 Candidate.Viable = true; 7744 Candidate.ExplicitCallArguments = Args.size(); 7745 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7746 // C++ [over.match.oper]p4: 7747 // For the built-in assignment operators, conversions of the 7748 // left operand are restricted as follows: 7749 // -- no temporaries are introduced to hold the left operand, and 7750 // -- no user-defined conversions are applied to the left 7751 // operand to achieve a type match with the left-most 7752 // parameter of a built-in candidate. 7753 // 7754 // We block these conversions by turning off user-defined 7755 // conversions, since that is the only way that initialization of 7756 // a reference to a non-class type can occur from something that 7757 // is not of the same type. 7758 if (ArgIdx < NumContextualBoolArguments) { 7759 assert(ParamTys[ArgIdx] == Context.BoolTy && 7760 "Contextual conversion to bool requires bool type"); 7761 Candidate.Conversions[ArgIdx] 7762 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7763 } else { 7764 Candidate.Conversions[ArgIdx] 7765 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7766 ArgIdx == 0 && IsAssignmentOperator, 7767 /*InOverloadResolution=*/false, 7768 /*AllowObjCWritebackConversion=*/ 7769 getLangOpts().ObjCAutoRefCount); 7770 } 7771 if (Candidate.Conversions[ArgIdx].isBad()) { 7772 Candidate.Viable = false; 7773 Candidate.FailureKind = ovl_fail_bad_conversion; 7774 break; 7775 } 7776 } 7777 } 7778 7779 namespace { 7780 7781 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7782 /// candidate operator functions for built-in operators (C++ 7783 /// [over.built]). The types are separated into pointer types and 7784 /// enumeration types. 7785 class BuiltinCandidateTypeSet { 7786 /// TypeSet - A set of types. 7787 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7788 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7789 7790 /// PointerTypes - The set of pointer types that will be used in the 7791 /// built-in candidates. 7792 TypeSet PointerTypes; 7793 7794 /// MemberPointerTypes - The set of member pointer types that will be 7795 /// used in the built-in candidates. 7796 TypeSet MemberPointerTypes; 7797 7798 /// EnumerationTypes - The set of enumeration types that will be 7799 /// used in the built-in candidates. 7800 TypeSet EnumerationTypes; 7801 7802 /// The set of vector types that will be used in the built-in 7803 /// candidates. 7804 TypeSet VectorTypes; 7805 7806 /// The set of matrix types that will be used in the built-in 7807 /// candidates. 7808 TypeSet MatrixTypes; 7809 7810 /// A flag indicating non-record types are viable candidates 7811 bool HasNonRecordTypes; 7812 7813 /// A flag indicating whether either arithmetic or enumeration types 7814 /// were present in the candidate set. 7815 bool HasArithmeticOrEnumeralTypes; 7816 7817 /// A flag indicating whether the nullptr type was present in the 7818 /// candidate set. 7819 bool HasNullPtrType; 7820 7821 /// Sema - The semantic analysis instance where we are building the 7822 /// candidate type set. 7823 Sema &SemaRef; 7824 7825 /// Context - The AST context in which we will build the type sets. 7826 ASTContext &Context; 7827 7828 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7829 const Qualifiers &VisibleQuals); 7830 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7831 7832 public: 7833 /// iterator - Iterates through the types that are part of the set. 7834 typedef TypeSet::iterator iterator; 7835 7836 BuiltinCandidateTypeSet(Sema &SemaRef) 7837 : HasNonRecordTypes(false), 7838 HasArithmeticOrEnumeralTypes(false), 7839 HasNullPtrType(false), 7840 SemaRef(SemaRef), 7841 Context(SemaRef.Context) { } 7842 7843 void AddTypesConvertedFrom(QualType Ty, 7844 SourceLocation Loc, 7845 bool AllowUserConversions, 7846 bool AllowExplicitConversions, 7847 const Qualifiers &VisibleTypeConversionsQuals); 7848 7849 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7850 llvm::iterator_range<iterator> member_pointer_types() { 7851 return MemberPointerTypes; 7852 } 7853 llvm::iterator_range<iterator> enumeration_types() { 7854 return EnumerationTypes; 7855 } 7856 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7857 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7858 7859 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7860 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7861 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7862 bool hasNullPtrType() const { return HasNullPtrType; } 7863 }; 7864 7865 } // end anonymous namespace 7866 7867 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7868 /// the set of pointer types along with any more-qualified variants of 7869 /// that type. For example, if @p Ty is "int const *", this routine 7870 /// will add "int const *", "int const volatile *", "int const 7871 /// restrict *", and "int const volatile restrict *" to the set of 7872 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7873 /// false otherwise. 7874 /// 7875 /// FIXME: what to do about extended qualifiers? 7876 bool 7877 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7878 const Qualifiers &VisibleQuals) { 7879 7880 // Insert this type. 7881 if (!PointerTypes.insert(Ty)) 7882 return false; 7883 7884 QualType PointeeTy; 7885 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7886 bool buildObjCPtr = false; 7887 if (!PointerTy) { 7888 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7889 PointeeTy = PTy->getPointeeType(); 7890 buildObjCPtr = true; 7891 } else { 7892 PointeeTy = PointerTy->getPointeeType(); 7893 } 7894 7895 // Don't add qualified variants of arrays. For one, they're not allowed 7896 // (the qualifier would sink to the element type), and for another, the 7897 // only overload situation where it matters is subscript or pointer +- int, 7898 // and those shouldn't have qualifier variants anyway. 7899 if (PointeeTy->isArrayType()) 7900 return true; 7901 7902 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7903 bool hasVolatile = VisibleQuals.hasVolatile(); 7904 bool hasRestrict = VisibleQuals.hasRestrict(); 7905 7906 // Iterate through all strict supersets of BaseCVR. 7907 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7908 if ((CVR | BaseCVR) != CVR) continue; 7909 // Skip over volatile if no volatile found anywhere in the types. 7910 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7911 7912 // Skip over restrict if no restrict found anywhere in the types, or if 7913 // the type cannot be restrict-qualified. 7914 if ((CVR & Qualifiers::Restrict) && 7915 (!hasRestrict || 7916 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7917 continue; 7918 7919 // Build qualified pointee type. 7920 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7921 7922 // Build qualified pointer type. 7923 QualType QPointerTy; 7924 if (!buildObjCPtr) 7925 QPointerTy = Context.getPointerType(QPointeeTy); 7926 else 7927 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7928 7929 // Insert qualified pointer type. 7930 PointerTypes.insert(QPointerTy); 7931 } 7932 7933 return true; 7934 } 7935 7936 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7937 /// to the set of pointer types along with any more-qualified variants of 7938 /// that type. For example, if @p Ty is "int const *", this routine 7939 /// will add "int const *", "int const volatile *", "int const 7940 /// restrict *", and "int const volatile restrict *" to the set of 7941 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7942 /// false otherwise. 7943 /// 7944 /// FIXME: what to do about extended qualifiers? 7945 bool 7946 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7947 QualType Ty) { 7948 // Insert this type. 7949 if (!MemberPointerTypes.insert(Ty)) 7950 return false; 7951 7952 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7953 assert(PointerTy && "type was not a member pointer type!"); 7954 7955 QualType PointeeTy = PointerTy->getPointeeType(); 7956 // Don't add qualified variants of arrays. For one, they're not allowed 7957 // (the qualifier would sink to the element type), and for another, the 7958 // only overload situation where it matters is subscript or pointer +- int, 7959 // and those shouldn't have qualifier variants anyway. 7960 if (PointeeTy->isArrayType()) 7961 return true; 7962 const Type *ClassTy = PointerTy->getClass(); 7963 7964 // Iterate through all strict supersets of the pointee type's CVR 7965 // qualifiers. 7966 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7967 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7968 if ((CVR | BaseCVR) != CVR) continue; 7969 7970 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7971 MemberPointerTypes.insert( 7972 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7973 } 7974 7975 return true; 7976 } 7977 7978 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7979 /// Ty can be implicit converted to the given set of @p Types. We're 7980 /// primarily interested in pointer types and enumeration types. We also 7981 /// take member pointer types, for the conditional operator. 7982 /// AllowUserConversions is true if we should look at the conversion 7983 /// functions of a class type, and AllowExplicitConversions if we 7984 /// should also include the explicit conversion functions of a class 7985 /// type. 7986 void 7987 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7988 SourceLocation Loc, 7989 bool AllowUserConversions, 7990 bool AllowExplicitConversions, 7991 const Qualifiers &VisibleQuals) { 7992 // Only deal with canonical types. 7993 Ty = Context.getCanonicalType(Ty); 7994 7995 // Look through reference types; they aren't part of the type of an 7996 // expression for the purposes of conversions. 7997 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7998 Ty = RefTy->getPointeeType(); 7999 8000 // If we're dealing with an array type, decay to the pointer. 8001 if (Ty->isArrayType()) 8002 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8003 8004 // Otherwise, we don't care about qualifiers on the type. 8005 Ty = Ty.getLocalUnqualifiedType(); 8006 8007 // Flag if we ever add a non-record type. 8008 const RecordType *TyRec = Ty->getAs<RecordType>(); 8009 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8010 8011 // Flag if we encounter an arithmetic type. 8012 HasArithmeticOrEnumeralTypes = 8013 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8014 8015 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8016 PointerTypes.insert(Ty); 8017 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8018 // Insert our type, and its more-qualified variants, into the set 8019 // of types. 8020 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8021 return; 8022 } else if (Ty->isMemberPointerType()) { 8023 // Member pointers are far easier, since the pointee can't be converted. 8024 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8025 return; 8026 } else if (Ty->isEnumeralType()) { 8027 HasArithmeticOrEnumeralTypes = true; 8028 EnumerationTypes.insert(Ty); 8029 } else if (Ty->isVectorType()) { 8030 // We treat vector types as arithmetic types in many contexts as an 8031 // extension. 8032 HasArithmeticOrEnumeralTypes = true; 8033 VectorTypes.insert(Ty); 8034 } else if (Ty->isMatrixType()) { 8035 // Similar to vector types, we treat vector types as arithmetic types in 8036 // many contexts as an extension. 8037 HasArithmeticOrEnumeralTypes = true; 8038 MatrixTypes.insert(Ty); 8039 } else if (Ty->isNullPtrType()) { 8040 HasNullPtrType = true; 8041 } else if (AllowUserConversions && TyRec) { 8042 // No conversion functions in incomplete types. 8043 if (!SemaRef.isCompleteType(Loc, Ty)) 8044 return; 8045 8046 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8047 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8048 if (isa<UsingShadowDecl>(D)) 8049 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8050 8051 // Skip conversion function templates; they don't tell us anything 8052 // about which builtin types we can convert to. 8053 if (isa<FunctionTemplateDecl>(D)) 8054 continue; 8055 8056 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8057 if (AllowExplicitConversions || !Conv->isExplicit()) { 8058 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8059 VisibleQuals); 8060 } 8061 } 8062 } 8063 } 8064 /// Helper function for adjusting address spaces for the pointer or reference 8065 /// operands of builtin operators depending on the argument. 8066 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8067 Expr *Arg) { 8068 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8069 } 8070 8071 /// Helper function for AddBuiltinOperatorCandidates() that adds 8072 /// the volatile- and non-volatile-qualified assignment operators for the 8073 /// given type to the candidate set. 8074 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8075 QualType T, 8076 ArrayRef<Expr *> Args, 8077 OverloadCandidateSet &CandidateSet) { 8078 QualType ParamTypes[2]; 8079 8080 // T& operator=(T&, T) 8081 ParamTypes[0] = S.Context.getLValueReferenceType( 8082 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8083 ParamTypes[1] = T; 8084 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8085 /*IsAssignmentOperator=*/true); 8086 8087 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8088 // volatile T& operator=(volatile T&, T) 8089 ParamTypes[0] = S.Context.getLValueReferenceType( 8090 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8091 Args[0])); 8092 ParamTypes[1] = T; 8093 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8094 /*IsAssignmentOperator=*/true); 8095 } 8096 } 8097 8098 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8099 /// if any, found in visible type conversion functions found in ArgExpr's type. 8100 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8101 Qualifiers VRQuals; 8102 const RecordType *TyRec; 8103 if (const MemberPointerType *RHSMPType = 8104 ArgExpr->getType()->getAs<MemberPointerType>()) 8105 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8106 else 8107 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8108 if (!TyRec) { 8109 // Just to be safe, assume the worst case. 8110 VRQuals.addVolatile(); 8111 VRQuals.addRestrict(); 8112 return VRQuals; 8113 } 8114 8115 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8116 if (!ClassDecl->hasDefinition()) 8117 return VRQuals; 8118 8119 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8120 if (isa<UsingShadowDecl>(D)) 8121 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8122 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8123 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8124 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8125 CanTy = ResTypeRef->getPointeeType(); 8126 // Need to go down the pointer/mempointer chain and add qualifiers 8127 // as see them. 8128 bool done = false; 8129 while (!done) { 8130 if (CanTy.isRestrictQualified()) 8131 VRQuals.addRestrict(); 8132 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8133 CanTy = ResTypePtr->getPointeeType(); 8134 else if (const MemberPointerType *ResTypeMPtr = 8135 CanTy->getAs<MemberPointerType>()) 8136 CanTy = ResTypeMPtr->getPointeeType(); 8137 else 8138 done = true; 8139 if (CanTy.isVolatileQualified()) 8140 VRQuals.addVolatile(); 8141 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8142 return VRQuals; 8143 } 8144 } 8145 } 8146 return VRQuals; 8147 } 8148 8149 namespace { 8150 8151 /// Helper class to manage the addition of builtin operator overload 8152 /// candidates. It provides shared state and utility methods used throughout 8153 /// the process, as well as a helper method to add each group of builtin 8154 /// operator overloads from the standard to a candidate set. 8155 class BuiltinOperatorOverloadBuilder { 8156 // Common instance state available to all overload candidate addition methods. 8157 Sema &S; 8158 ArrayRef<Expr *> Args; 8159 Qualifiers VisibleTypeConversionsQuals; 8160 bool HasArithmeticOrEnumeralCandidateType; 8161 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8162 OverloadCandidateSet &CandidateSet; 8163 8164 static constexpr int ArithmeticTypesCap = 24; 8165 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8166 8167 // Define some indices used to iterate over the arithmetic types in 8168 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8169 // types are that preserved by promotion (C++ [over.built]p2). 8170 unsigned FirstIntegralType, 8171 LastIntegralType; 8172 unsigned FirstPromotedIntegralType, 8173 LastPromotedIntegralType; 8174 unsigned FirstPromotedArithmeticType, 8175 LastPromotedArithmeticType; 8176 unsigned NumArithmeticTypes; 8177 8178 void InitArithmeticTypes() { 8179 // Start of promoted types. 8180 FirstPromotedArithmeticType = 0; 8181 ArithmeticTypes.push_back(S.Context.FloatTy); 8182 ArithmeticTypes.push_back(S.Context.DoubleTy); 8183 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8184 if (S.Context.getTargetInfo().hasFloat128Type()) 8185 ArithmeticTypes.push_back(S.Context.Float128Ty); 8186 8187 // Start of integral types. 8188 FirstIntegralType = ArithmeticTypes.size(); 8189 FirstPromotedIntegralType = ArithmeticTypes.size(); 8190 ArithmeticTypes.push_back(S.Context.IntTy); 8191 ArithmeticTypes.push_back(S.Context.LongTy); 8192 ArithmeticTypes.push_back(S.Context.LongLongTy); 8193 if (S.Context.getTargetInfo().hasInt128Type() || 8194 (S.Context.getAuxTargetInfo() && 8195 S.Context.getAuxTargetInfo()->hasInt128Type())) 8196 ArithmeticTypes.push_back(S.Context.Int128Ty); 8197 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8198 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8199 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8200 if (S.Context.getTargetInfo().hasInt128Type() || 8201 (S.Context.getAuxTargetInfo() && 8202 S.Context.getAuxTargetInfo()->hasInt128Type())) 8203 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8204 LastPromotedIntegralType = ArithmeticTypes.size(); 8205 LastPromotedArithmeticType = ArithmeticTypes.size(); 8206 // End of promoted types. 8207 8208 ArithmeticTypes.push_back(S.Context.BoolTy); 8209 ArithmeticTypes.push_back(S.Context.CharTy); 8210 ArithmeticTypes.push_back(S.Context.WCharTy); 8211 if (S.Context.getLangOpts().Char8) 8212 ArithmeticTypes.push_back(S.Context.Char8Ty); 8213 ArithmeticTypes.push_back(S.Context.Char16Ty); 8214 ArithmeticTypes.push_back(S.Context.Char32Ty); 8215 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8216 ArithmeticTypes.push_back(S.Context.ShortTy); 8217 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8218 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8219 LastIntegralType = ArithmeticTypes.size(); 8220 NumArithmeticTypes = ArithmeticTypes.size(); 8221 // End of integral types. 8222 // FIXME: What about complex? What about half? 8223 8224 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8225 "Enough inline storage for all arithmetic types."); 8226 } 8227 8228 /// Helper method to factor out the common pattern of adding overloads 8229 /// for '++' and '--' builtin operators. 8230 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8231 bool HasVolatile, 8232 bool HasRestrict) { 8233 QualType ParamTypes[2] = { 8234 S.Context.getLValueReferenceType(CandidateTy), 8235 S.Context.IntTy 8236 }; 8237 8238 // Non-volatile version. 8239 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8240 8241 // Use a heuristic to reduce number of builtin candidates in the set: 8242 // add volatile version only if there are conversions to a volatile type. 8243 if (HasVolatile) { 8244 ParamTypes[0] = 8245 S.Context.getLValueReferenceType( 8246 S.Context.getVolatileType(CandidateTy)); 8247 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8248 } 8249 8250 // Add restrict version only if there are conversions to a restrict type 8251 // and our candidate type is a non-restrict-qualified pointer. 8252 if (HasRestrict && CandidateTy->isAnyPointerType() && 8253 !CandidateTy.isRestrictQualified()) { 8254 ParamTypes[0] 8255 = S.Context.getLValueReferenceType( 8256 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8257 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8258 8259 if (HasVolatile) { 8260 ParamTypes[0] 8261 = S.Context.getLValueReferenceType( 8262 S.Context.getCVRQualifiedType(CandidateTy, 8263 (Qualifiers::Volatile | 8264 Qualifiers::Restrict))); 8265 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8266 } 8267 } 8268 8269 } 8270 8271 /// Helper to add an overload candidate for a binary builtin with types \p L 8272 /// and \p R. 8273 void AddCandidate(QualType L, QualType R) { 8274 QualType LandR[2] = {L, R}; 8275 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8276 } 8277 8278 public: 8279 BuiltinOperatorOverloadBuilder( 8280 Sema &S, ArrayRef<Expr *> Args, 8281 Qualifiers VisibleTypeConversionsQuals, 8282 bool HasArithmeticOrEnumeralCandidateType, 8283 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8284 OverloadCandidateSet &CandidateSet) 8285 : S(S), Args(Args), 8286 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8287 HasArithmeticOrEnumeralCandidateType( 8288 HasArithmeticOrEnumeralCandidateType), 8289 CandidateTypes(CandidateTypes), 8290 CandidateSet(CandidateSet) { 8291 8292 InitArithmeticTypes(); 8293 } 8294 8295 // Increment is deprecated for bool since C++17. 8296 // 8297 // C++ [over.built]p3: 8298 // 8299 // For every pair (T, VQ), where T is an arithmetic type other 8300 // than bool, and VQ is either volatile or empty, there exist 8301 // candidate operator functions of the form 8302 // 8303 // VQ T& operator++(VQ T&); 8304 // T operator++(VQ T&, int); 8305 // 8306 // C++ [over.built]p4: 8307 // 8308 // For every pair (T, VQ), where T is an arithmetic type other 8309 // than bool, and VQ is either volatile or empty, there exist 8310 // candidate operator functions of the form 8311 // 8312 // VQ T& operator--(VQ T&); 8313 // T operator--(VQ T&, int); 8314 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8315 if (!HasArithmeticOrEnumeralCandidateType) 8316 return; 8317 8318 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8319 const auto TypeOfT = ArithmeticTypes[Arith]; 8320 if (TypeOfT == S.Context.BoolTy) { 8321 if (Op == OO_MinusMinus) 8322 continue; 8323 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8324 continue; 8325 } 8326 addPlusPlusMinusMinusStyleOverloads( 8327 TypeOfT, 8328 VisibleTypeConversionsQuals.hasVolatile(), 8329 VisibleTypeConversionsQuals.hasRestrict()); 8330 } 8331 } 8332 8333 // C++ [over.built]p5: 8334 // 8335 // For every pair (T, VQ), where T is a cv-qualified or 8336 // cv-unqualified object type, and VQ is either volatile or 8337 // empty, there exist candidate operator functions of the form 8338 // 8339 // T*VQ& operator++(T*VQ&); 8340 // T*VQ& operator--(T*VQ&); 8341 // T* operator++(T*VQ&, int); 8342 // T* operator--(T*VQ&, int); 8343 void addPlusPlusMinusMinusPointerOverloads() { 8344 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8345 // Skip pointer types that aren't pointers to object types. 8346 if (!PtrTy->getPointeeType()->isObjectType()) 8347 continue; 8348 8349 addPlusPlusMinusMinusStyleOverloads( 8350 PtrTy, 8351 (!PtrTy.isVolatileQualified() && 8352 VisibleTypeConversionsQuals.hasVolatile()), 8353 (!PtrTy.isRestrictQualified() && 8354 VisibleTypeConversionsQuals.hasRestrict())); 8355 } 8356 } 8357 8358 // C++ [over.built]p6: 8359 // For every cv-qualified or cv-unqualified object type T, there 8360 // exist candidate operator functions of the form 8361 // 8362 // T& operator*(T*); 8363 // 8364 // C++ [over.built]p7: 8365 // For every function type T that does not have cv-qualifiers or a 8366 // ref-qualifier, there exist candidate operator functions of the form 8367 // T& operator*(T*); 8368 void addUnaryStarPointerOverloads() { 8369 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8370 QualType PointeeTy = ParamTy->getPointeeType(); 8371 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8372 continue; 8373 8374 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8375 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8376 continue; 8377 8378 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8379 } 8380 } 8381 8382 // C++ [over.built]p9: 8383 // For every promoted arithmetic type T, there exist candidate 8384 // operator functions of the form 8385 // 8386 // T operator+(T); 8387 // T operator-(T); 8388 void addUnaryPlusOrMinusArithmeticOverloads() { 8389 if (!HasArithmeticOrEnumeralCandidateType) 8390 return; 8391 8392 for (unsigned Arith = FirstPromotedArithmeticType; 8393 Arith < LastPromotedArithmeticType; ++Arith) { 8394 QualType ArithTy = ArithmeticTypes[Arith]; 8395 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8396 } 8397 8398 // Extension: We also add these operators for vector types. 8399 for (QualType VecTy : CandidateTypes[0].vector_types()) 8400 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8401 } 8402 8403 // C++ [over.built]p8: 8404 // For every type T, there exist candidate operator functions of 8405 // the form 8406 // 8407 // T* operator+(T*); 8408 void addUnaryPlusPointerOverloads() { 8409 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8410 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8411 } 8412 8413 // C++ [over.built]p10: 8414 // For every promoted integral type T, there exist candidate 8415 // operator functions of the form 8416 // 8417 // T operator~(T); 8418 void addUnaryTildePromotedIntegralOverloads() { 8419 if (!HasArithmeticOrEnumeralCandidateType) 8420 return; 8421 8422 for (unsigned Int = FirstPromotedIntegralType; 8423 Int < LastPromotedIntegralType; ++Int) { 8424 QualType IntTy = ArithmeticTypes[Int]; 8425 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8426 } 8427 8428 // Extension: We also add this operator for vector types. 8429 for (QualType VecTy : CandidateTypes[0].vector_types()) 8430 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8431 } 8432 8433 // C++ [over.match.oper]p16: 8434 // For every pointer to member type T or type std::nullptr_t, there 8435 // exist candidate operator functions of the form 8436 // 8437 // bool operator==(T,T); 8438 // bool operator!=(T,T); 8439 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8440 /// Set of (canonical) types that we've already handled. 8441 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8442 8443 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8444 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8445 // Don't add the same builtin candidate twice. 8446 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8447 continue; 8448 8449 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8450 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8451 } 8452 8453 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8454 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8455 if (AddedTypes.insert(NullPtrTy).second) { 8456 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8458 } 8459 } 8460 } 8461 } 8462 8463 // C++ [over.built]p15: 8464 // 8465 // For every T, where T is an enumeration type or a pointer type, 8466 // there exist candidate operator functions of the form 8467 // 8468 // bool operator<(T, T); 8469 // bool operator>(T, T); 8470 // bool operator<=(T, T); 8471 // bool operator>=(T, T); 8472 // bool operator==(T, T); 8473 // bool operator!=(T, T); 8474 // R operator<=>(T, T) 8475 void addGenericBinaryPointerOrEnumeralOverloads() { 8476 // C++ [over.match.oper]p3: 8477 // [...]the built-in candidates include all of the candidate operator 8478 // functions defined in 13.6 that, compared to the given operator, [...] 8479 // do not have the same parameter-type-list as any non-template non-member 8480 // candidate. 8481 // 8482 // Note that in practice, this only affects enumeration types because there 8483 // aren't any built-in candidates of record type, and a user-defined operator 8484 // must have an operand of record or enumeration type. Also, the only other 8485 // overloaded operator with enumeration arguments, operator=, 8486 // cannot be overloaded for enumeration types, so this is the only place 8487 // where we must suppress candidates like this. 8488 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8489 UserDefinedBinaryOperators; 8490 8491 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8492 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8493 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8494 CEnd = CandidateSet.end(); 8495 C != CEnd; ++C) { 8496 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8497 continue; 8498 8499 if (C->Function->isFunctionTemplateSpecialization()) 8500 continue; 8501 8502 // We interpret "same parameter-type-list" as applying to the 8503 // "synthesized candidate, with the order of the two parameters 8504 // reversed", not to the original function. 8505 bool Reversed = C->isReversed(); 8506 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8507 ->getType() 8508 .getUnqualifiedType(); 8509 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8510 ->getType() 8511 .getUnqualifiedType(); 8512 8513 // Skip if either parameter isn't of enumeral type. 8514 if (!FirstParamType->isEnumeralType() || 8515 !SecondParamType->isEnumeralType()) 8516 continue; 8517 8518 // Add this operator to the set of known user-defined operators. 8519 UserDefinedBinaryOperators.insert( 8520 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8521 S.Context.getCanonicalType(SecondParamType))); 8522 } 8523 } 8524 } 8525 8526 /// Set of (canonical) types that we've already handled. 8527 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8528 8529 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8530 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8531 // Don't add the same builtin candidate twice. 8532 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8533 continue; 8534 8535 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8536 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8537 } 8538 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8539 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8540 8541 // Don't add the same builtin candidate twice, or if a user defined 8542 // candidate exists. 8543 if (!AddedTypes.insert(CanonType).second || 8544 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8545 CanonType))) 8546 continue; 8547 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8548 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8549 } 8550 } 8551 } 8552 8553 // C++ [over.built]p13: 8554 // 8555 // For every cv-qualified or cv-unqualified object type T 8556 // there exist candidate operator functions of the form 8557 // 8558 // T* operator+(T*, ptrdiff_t); 8559 // T& operator[](T*, ptrdiff_t); [BELOW] 8560 // T* operator-(T*, ptrdiff_t); 8561 // T* operator+(ptrdiff_t, T*); 8562 // T& operator[](ptrdiff_t, T*); [BELOW] 8563 // 8564 // C++ [over.built]p14: 8565 // 8566 // For every T, where T is a pointer to object type, there 8567 // exist candidate operator functions of the form 8568 // 8569 // ptrdiff_t operator-(T, T); 8570 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8571 /// Set of (canonical) types that we've already handled. 8572 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8573 8574 for (int Arg = 0; Arg < 2; ++Arg) { 8575 QualType AsymmetricParamTypes[2] = { 8576 S.Context.getPointerDiffType(), 8577 S.Context.getPointerDiffType(), 8578 }; 8579 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8580 QualType PointeeTy = PtrTy->getPointeeType(); 8581 if (!PointeeTy->isObjectType()) 8582 continue; 8583 8584 AsymmetricParamTypes[Arg] = PtrTy; 8585 if (Arg == 0 || Op == OO_Plus) { 8586 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8587 // T* operator+(ptrdiff_t, T*); 8588 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8589 } 8590 if (Op == OO_Minus) { 8591 // ptrdiff_t operator-(T, T); 8592 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8593 continue; 8594 8595 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8596 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8597 } 8598 } 8599 } 8600 } 8601 8602 // C++ [over.built]p12: 8603 // 8604 // For every pair of promoted arithmetic types L and R, there 8605 // exist candidate operator functions of the form 8606 // 8607 // LR operator*(L, R); 8608 // LR operator/(L, R); 8609 // LR operator+(L, R); 8610 // LR operator-(L, R); 8611 // bool operator<(L, R); 8612 // bool operator>(L, R); 8613 // bool operator<=(L, R); 8614 // bool operator>=(L, R); 8615 // bool operator==(L, R); 8616 // bool operator!=(L, R); 8617 // 8618 // where LR is the result of the usual arithmetic conversions 8619 // between types L and R. 8620 // 8621 // C++ [over.built]p24: 8622 // 8623 // For every pair of promoted arithmetic types L and R, there exist 8624 // candidate operator functions of the form 8625 // 8626 // LR operator?(bool, L, R); 8627 // 8628 // where LR is the result of the usual arithmetic conversions 8629 // between types L and R. 8630 // Our candidates ignore the first parameter. 8631 void addGenericBinaryArithmeticOverloads() { 8632 if (!HasArithmeticOrEnumeralCandidateType) 8633 return; 8634 8635 for (unsigned Left = FirstPromotedArithmeticType; 8636 Left < LastPromotedArithmeticType; ++Left) { 8637 for (unsigned Right = FirstPromotedArithmeticType; 8638 Right < LastPromotedArithmeticType; ++Right) { 8639 QualType LandR[2] = { ArithmeticTypes[Left], 8640 ArithmeticTypes[Right] }; 8641 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8642 } 8643 } 8644 8645 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8646 // conditional operator for vector types. 8647 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8648 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8649 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8650 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8651 } 8652 } 8653 8654 /// Add binary operator overloads for each candidate matrix type M1, M2: 8655 /// * (M1, M1) -> M1 8656 /// * (M1, M1.getElementType()) -> M1 8657 /// * (M2.getElementType(), M2) -> M2 8658 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8659 void addMatrixBinaryArithmeticOverloads() { 8660 if (!HasArithmeticOrEnumeralCandidateType) 8661 return; 8662 8663 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8664 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8665 AddCandidate(M1, M1); 8666 } 8667 8668 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8669 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8670 if (!CandidateTypes[0].containsMatrixType(M2)) 8671 AddCandidate(M2, M2); 8672 } 8673 } 8674 8675 // C++2a [over.built]p14: 8676 // 8677 // For every integral type T there exists a candidate operator function 8678 // of the form 8679 // 8680 // std::strong_ordering operator<=>(T, T) 8681 // 8682 // C++2a [over.built]p15: 8683 // 8684 // For every pair of floating-point types L and R, there exists a candidate 8685 // operator function of the form 8686 // 8687 // std::partial_ordering operator<=>(L, R); 8688 // 8689 // FIXME: The current specification for integral types doesn't play nice with 8690 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8691 // comparisons. Under the current spec this can lead to ambiguity during 8692 // overload resolution. For example: 8693 // 8694 // enum A : int {a}; 8695 // auto x = (a <=> (long)42); 8696 // 8697 // error: call is ambiguous for arguments 'A' and 'long'. 8698 // note: candidate operator<=>(int, int) 8699 // note: candidate operator<=>(long, long) 8700 // 8701 // To avoid this error, this function deviates from the specification and adds 8702 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8703 // arithmetic types (the same as the generic relational overloads). 8704 // 8705 // For now this function acts as a placeholder. 8706 void addThreeWayArithmeticOverloads() { 8707 addGenericBinaryArithmeticOverloads(); 8708 } 8709 8710 // C++ [over.built]p17: 8711 // 8712 // For every pair of promoted integral types L and R, there 8713 // exist candidate operator functions of the form 8714 // 8715 // LR operator%(L, R); 8716 // LR operator&(L, R); 8717 // LR operator^(L, R); 8718 // LR operator|(L, R); 8719 // L operator<<(L, R); 8720 // L operator>>(L, R); 8721 // 8722 // where LR is the result of the usual arithmetic conversions 8723 // between types L and R. 8724 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8725 if (!HasArithmeticOrEnumeralCandidateType) 8726 return; 8727 8728 for (unsigned Left = FirstPromotedIntegralType; 8729 Left < LastPromotedIntegralType; ++Left) { 8730 for (unsigned Right = FirstPromotedIntegralType; 8731 Right < LastPromotedIntegralType; ++Right) { 8732 QualType LandR[2] = { ArithmeticTypes[Left], 8733 ArithmeticTypes[Right] }; 8734 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8735 } 8736 } 8737 } 8738 8739 // C++ [over.built]p20: 8740 // 8741 // For every pair (T, VQ), where T is an enumeration or 8742 // pointer to member type and VQ is either volatile or 8743 // empty, there exist candidate operator functions of the form 8744 // 8745 // VQ T& operator=(VQ T&, T); 8746 void addAssignmentMemberPointerOrEnumeralOverloads() { 8747 /// Set of (canonical) types that we've already handled. 8748 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8749 8750 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8751 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8752 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8753 continue; 8754 8755 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8756 } 8757 8758 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8759 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8760 continue; 8761 8762 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8763 } 8764 } 8765 } 8766 8767 // C++ [over.built]p19: 8768 // 8769 // For every pair (T, VQ), where T is any type and VQ is either 8770 // volatile or empty, there exist candidate operator functions 8771 // of the form 8772 // 8773 // T*VQ& operator=(T*VQ&, T*); 8774 // 8775 // C++ [over.built]p21: 8776 // 8777 // For every pair (T, VQ), where T is a cv-qualified or 8778 // cv-unqualified object type and VQ is either volatile or 8779 // empty, there exist candidate operator functions of the form 8780 // 8781 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8782 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8783 void addAssignmentPointerOverloads(bool isEqualOp) { 8784 /// Set of (canonical) types that we've already handled. 8785 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8786 8787 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8788 // If this is operator=, keep track of the builtin candidates we added. 8789 if (isEqualOp) 8790 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8791 else if (!PtrTy->getPointeeType()->isObjectType()) 8792 continue; 8793 8794 // non-volatile version 8795 QualType ParamTypes[2] = { 8796 S.Context.getLValueReferenceType(PtrTy), 8797 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8798 }; 8799 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8800 /*IsAssignmentOperator=*/ isEqualOp); 8801 8802 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8803 VisibleTypeConversionsQuals.hasVolatile(); 8804 if (NeedVolatile) { 8805 // volatile version 8806 ParamTypes[0] = 8807 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8808 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8809 /*IsAssignmentOperator=*/isEqualOp); 8810 } 8811 8812 if (!PtrTy.isRestrictQualified() && 8813 VisibleTypeConversionsQuals.hasRestrict()) { 8814 // restrict version 8815 ParamTypes[0] = 8816 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8817 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8818 /*IsAssignmentOperator=*/isEqualOp); 8819 8820 if (NeedVolatile) { 8821 // volatile restrict version 8822 ParamTypes[0] = 8823 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8824 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8825 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8826 /*IsAssignmentOperator=*/isEqualOp); 8827 } 8828 } 8829 } 8830 8831 if (isEqualOp) { 8832 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8833 // Make sure we don't add the same candidate twice. 8834 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8835 continue; 8836 8837 QualType ParamTypes[2] = { 8838 S.Context.getLValueReferenceType(PtrTy), 8839 PtrTy, 8840 }; 8841 8842 // non-volatile version 8843 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8844 /*IsAssignmentOperator=*/true); 8845 8846 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8847 VisibleTypeConversionsQuals.hasVolatile(); 8848 if (NeedVolatile) { 8849 // volatile version 8850 ParamTypes[0] = S.Context.getLValueReferenceType( 8851 S.Context.getVolatileType(PtrTy)); 8852 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8853 /*IsAssignmentOperator=*/true); 8854 } 8855 8856 if (!PtrTy.isRestrictQualified() && 8857 VisibleTypeConversionsQuals.hasRestrict()) { 8858 // restrict version 8859 ParamTypes[0] = S.Context.getLValueReferenceType( 8860 S.Context.getRestrictType(PtrTy)); 8861 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8862 /*IsAssignmentOperator=*/true); 8863 8864 if (NeedVolatile) { 8865 // volatile restrict version 8866 ParamTypes[0] = 8867 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8868 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8869 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8870 /*IsAssignmentOperator=*/true); 8871 } 8872 } 8873 } 8874 } 8875 } 8876 8877 // C++ [over.built]p18: 8878 // 8879 // For every triple (L, VQ, R), where L is an arithmetic type, 8880 // VQ is either volatile or empty, and R is a promoted 8881 // arithmetic type, there exist candidate operator functions of 8882 // the form 8883 // 8884 // VQ L& operator=(VQ L&, R); 8885 // VQ L& operator*=(VQ L&, R); 8886 // VQ L& operator/=(VQ L&, R); 8887 // VQ L& operator+=(VQ L&, R); 8888 // VQ L& operator-=(VQ L&, R); 8889 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8890 if (!HasArithmeticOrEnumeralCandidateType) 8891 return; 8892 8893 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8894 for (unsigned Right = FirstPromotedArithmeticType; 8895 Right < LastPromotedArithmeticType; ++Right) { 8896 QualType ParamTypes[2]; 8897 ParamTypes[1] = ArithmeticTypes[Right]; 8898 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8899 S, ArithmeticTypes[Left], Args[0]); 8900 // Add this built-in operator as a candidate (VQ is empty). 8901 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8902 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8903 /*IsAssignmentOperator=*/isEqualOp); 8904 8905 // Add this built-in operator as a candidate (VQ is 'volatile'). 8906 if (VisibleTypeConversionsQuals.hasVolatile()) { 8907 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8908 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8909 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8910 /*IsAssignmentOperator=*/isEqualOp); 8911 } 8912 } 8913 } 8914 8915 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8916 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8917 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8918 QualType ParamTypes[2]; 8919 ParamTypes[1] = Vec2Ty; 8920 // Add this built-in operator as a candidate (VQ is empty). 8921 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8922 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8923 /*IsAssignmentOperator=*/isEqualOp); 8924 8925 // Add this built-in operator as a candidate (VQ is 'volatile'). 8926 if (VisibleTypeConversionsQuals.hasVolatile()) { 8927 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8928 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8929 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8930 /*IsAssignmentOperator=*/isEqualOp); 8931 } 8932 } 8933 } 8934 8935 // C++ [over.built]p22: 8936 // 8937 // For every triple (L, VQ, R), where L is an integral type, VQ 8938 // is either volatile or empty, and R is a promoted integral 8939 // type, there exist candidate operator functions of the form 8940 // 8941 // VQ L& operator%=(VQ L&, R); 8942 // VQ L& operator<<=(VQ L&, R); 8943 // VQ L& operator>>=(VQ L&, R); 8944 // VQ L& operator&=(VQ L&, R); 8945 // VQ L& operator^=(VQ L&, R); 8946 // VQ L& operator|=(VQ L&, R); 8947 void addAssignmentIntegralOverloads() { 8948 if (!HasArithmeticOrEnumeralCandidateType) 8949 return; 8950 8951 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8952 for (unsigned Right = FirstPromotedIntegralType; 8953 Right < LastPromotedIntegralType; ++Right) { 8954 QualType ParamTypes[2]; 8955 ParamTypes[1] = ArithmeticTypes[Right]; 8956 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8957 S, ArithmeticTypes[Left], Args[0]); 8958 // Add this built-in operator as a candidate (VQ is empty). 8959 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8960 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8961 if (VisibleTypeConversionsQuals.hasVolatile()) { 8962 // Add this built-in operator as a candidate (VQ is 'volatile'). 8963 ParamTypes[0] = LeftBaseTy; 8964 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8965 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8966 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8967 } 8968 } 8969 } 8970 } 8971 8972 // C++ [over.operator]p23: 8973 // 8974 // There also exist candidate operator functions of the form 8975 // 8976 // bool operator!(bool); 8977 // bool operator&&(bool, bool); 8978 // bool operator||(bool, bool); 8979 void addExclaimOverload() { 8980 QualType ParamTy = S.Context.BoolTy; 8981 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8982 /*IsAssignmentOperator=*/false, 8983 /*NumContextualBoolArguments=*/1); 8984 } 8985 void addAmpAmpOrPipePipeOverload() { 8986 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8987 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8988 /*IsAssignmentOperator=*/false, 8989 /*NumContextualBoolArguments=*/2); 8990 } 8991 8992 // C++ [over.built]p13: 8993 // 8994 // For every cv-qualified or cv-unqualified object type T there 8995 // exist candidate operator functions of the form 8996 // 8997 // T* operator+(T*, ptrdiff_t); [ABOVE] 8998 // T& operator[](T*, ptrdiff_t); 8999 // T* operator-(T*, ptrdiff_t); [ABOVE] 9000 // T* operator+(ptrdiff_t, T*); [ABOVE] 9001 // T& operator[](ptrdiff_t, T*); 9002 void addSubscriptOverloads() { 9003 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9004 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9005 QualType PointeeType = PtrTy->getPointeeType(); 9006 if (!PointeeType->isObjectType()) 9007 continue; 9008 9009 // T& operator[](T*, ptrdiff_t) 9010 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9011 } 9012 9013 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9014 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9015 QualType PointeeType = PtrTy->getPointeeType(); 9016 if (!PointeeType->isObjectType()) 9017 continue; 9018 9019 // T& operator[](ptrdiff_t, T*) 9020 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9021 } 9022 } 9023 9024 // C++ [over.built]p11: 9025 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9026 // C1 is the same type as C2 or is a derived class of C2, T is an object 9027 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9028 // there exist candidate operator functions of the form 9029 // 9030 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9031 // 9032 // where CV12 is the union of CV1 and CV2. 9033 void addArrowStarOverloads() { 9034 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9035 QualType C1Ty = PtrTy; 9036 QualType C1; 9037 QualifierCollector Q1; 9038 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9039 if (!isa<RecordType>(C1)) 9040 continue; 9041 // heuristic to reduce number of builtin candidates in the set. 9042 // Add volatile/restrict version only if there are conversions to a 9043 // volatile/restrict type. 9044 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9045 continue; 9046 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9047 continue; 9048 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9049 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9050 QualType C2 = QualType(mptr->getClass(), 0); 9051 C2 = C2.getUnqualifiedType(); 9052 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9053 break; 9054 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9055 // build CV12 T& 9056 QualType T = mptr->getPointeeType(); 9057 if (!VisibleTypeConversionsQuals.hasVolatile() && 9058 T.isVolatileQualified()) 9059 continue; 9060 if (!VisibleTypeConversionsQuals.hasRestrict() && 9061 T.isRestrictQualified()) 9062 continue; 9063 T = Q1.apply(S.Context, T); 9064 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9065 } 9066 } 9067 } 9068 9069 // Note that we don't consider the first argument, since it has been 9070 // contextually converted to bool long ago. The candidates below are 9071 // therefore added as binary. 9072 // 9073 // C++ [over.built]p25: 9074 // For every type T, where T is a pointer, pointer-to-member, or scoped 9075 // enumeration type, there exist candidate operator functions of the form 9076 // 9077 // T operator?(bool, T, T); 9078 // 9079 void addConditionalOperatorOverloads() { 9080 /// Set of (canonical) types that we've already handled. 9081 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9082 9083 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9084 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9085 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9086 continue; 9087 9088 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9089 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9090 } 9091 9092 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9093 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9094 continue; 9095 9096 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9097 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9098 } 9099 9100 if (S.getLangOpts().CPlusPlus11) { 9101 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9102 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9103 continue; 9104 9105 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9106 continue; 9107 9108 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9109 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9110 } 9111 } 9112 } 9113 } 9114 }; 9115 9116 } // end anonymous namespace 9117 9118 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9119 /// operator overloads to the candidate set (C++ [over.built]), based 9120 /// on the operator @p Op and the arguments given. For example, if the 9121 /// operator is a binary '+', this routine might add "int 9122 /// operator+(int, int)" to cover integer addition. 9123 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9124 SourceLocation OpLoc, 9125 ArrayRef<Expr *> Args, 9126 OverloadCandidateSet &CandidateSet) { 9127 // Find all of the types that the arguments can convert to, but only 9128 // if the operator we're looking at has built-in operator candidates 9129 // that make use of these types. Also record whether we encounter non-record 9130 // candidate types or either arithmetic or enumeral candidate types. 9131 Qualifiers VisibleTypeConversionsQuals; 9132 VisibleTypeConversionsQuals.addConst(); 9133 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9134 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9135 9136 bool HasNonRecordCandidateType = false; 9137 bool HasArithmeticOrEnumeralCandidateType = false; 9138 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9139 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9140 CandidateTypes.emplace_back(*this); 9141 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9142 OpLoc, 9143 true, 9144 (Op == OO_Exclaim || 9145 Op == OO_AmpAmp || 9146 Op == OO_PipePipe), 9147 VisibleTypeConversionsQuals); 9148 HasNonRecordCandidateType = HasNonRecordCandidateType || 9149 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9150 HasArithmeticOrEnumeralCandidateType = 9151 HasArithmeticOrEnumeralCandidateType || 9152 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9153 } 9154 9155 // Exit early when no non-record types have been added to the candidate set 9156 // for any of the arguments to the operator. 9157 // 9158 // We can't exit early for !, ||, or &&, since there we have always have 9159 // 'bool' overloads. 9160 if (!HasNonRecordCandidateType && 9161 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9162 return; 9163 9164 // Setup an object to manage the common state for building overloads. 9165 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9166 VisibleTypeConversionsQuals, 9167 HasArithmeticOrEnumeralCandidateType, 9168 CandidateTypes, CandidateSet); 9169 9170 // Dispatch over the operation to add in only those overloads which apply. 9171 switch (Op) { 9172 case OO_None: 9173 case NUM_OVERLOADED_OPERATORS: 9174 llvm_unreachable("Expected an overloaded operator"); 9175 9176 case OO_New: 9177 case OO_Delete: 9178 case OO_Array_New: 9179 case OO_Array_Delete: 9180 case OO_Call: 9181 llvm_unreachable( 9182 "Special operators don't use AddBuiltinOperatorCandidates"); 9183 9184 case OO_Comma: 9185 case OO_Arrow: 9186 case OO_Coawait: 9187 // C++ [over.match.oper]p3: 9188 // -- For the operator ',', the unary operator '&', the 9189 // operator '->', or the operator 'co_await', the 9190 // built-in candidates set is empty. 9191 break; 9192 9193 case OO_Plus: // '+' is either unary or binary 9194 if (Args.size() == 1) 9195 OpBuilder.addUnaryPlusPointerOverloads(); 9196 LLVM_FALLTHROUGH; 9197 9198 case OO_Minus: // '-' is either unary or binary 9199 if (Args.size() == 1) { 9200 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9201 } else { 9202 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9203 OpBuilder.addGenericBinaryArithmeticOverloads(); 9204 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9205 } 9206 break; 9207 9208 case OO_Star: // '*' is either unary or binary 9209 if (Args.size() == 1) 9210 OpBuilder.addUnaryStarPointerOverloads(); 9211 else { 9212 OpBuilder.addGenericBinaryArithmeticOverloads(); 9213 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9214 } 9215 break; 9216 9217 case OO_Slash: 9218 OpBuilder.addGenericBinaryArithmeticOverloads(); 9219 break; 9220 9221 case OO_PlusPlus: 9222 case OO_MinusMinus: 9223 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9224 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9225 break; 9226 9227 case OO_EqualEqual: 9228 case OO_ExclaimEqual: 9229 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9230 LLVM_FALLTHROUGH; 9231 9232 case OO_Less: 9233 case OO_Greater: 9234 case OO_LessEqual: 9235 case OO_GreaterEqual: 9236 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9237 OpBuilder.addGenericBinaryArithmeticOverloads(); 9238 break; 9239 9240 case OO_Spaceship: 9241 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9242 OpBuilder.addThreeWayArithmeticOverloads(); 9243 break; 9244 9245 case OO_Percent: 9246 case OO_Caret: 9247 case OO_Pipe: 9248 case OO_LessLess: 9249 case OO_GreaterGreater: 9250 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9251 break; 9252 9253 case OO_Amp: // '&' is either unary or binary 9254 if (Args.size() == 1) 9255 // C++ [over.match.oper]p3: 9256 // -- For the operator ',', the unary operator '&', or the 9257 // operator '->', the built-in candidates set is empty. 9258 break; 9259 9260 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9261 break; 9262 9263 case OO_Tilde: 9264 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9265 break; 9266 9267 case OO_Equal: 9268 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9269 LLVM_FALLTHROUGH; 9270 9271 case OO_PlusEqual: 9272 case OO_MinusEqual: 9273 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9274 LLVM_FALLTHROUGH; 9275 9276 case OO_StarEqual: 9277 case OO_SlashEqual: 9278 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9279 break; 9280 9281 case OO_PercentEqual: 9282 case OO_LessLessEqual: 9283 case OO_GreaterGreaterEqual: 9284 case OO_AmpEqual: 9285 case OO_CaretEqual: 9286 case OO_PipeEqual: 9287 OpBuilder.addAssignmentIntegralOverloads(); 9288 break; 9289 9290 case OO_Exclaim: 9291 OpBuilder.addExclaimOverload(); 9292 break; 9293 9294 case OO_AmpAmp: 9295 case OO_PipePipe: 9296 OpBuilder.addAmpAmpOrPipePipeOverload(); 9297 break; 9298 9299 case OO_Subscript: 9300 OpBuilder.addSubscriptOverloads(); 9301 break; 9302 9303 case OO_ArrowStar: 9304 OpBuilder.addArrowStarOverloads(); 9305 break; 9306 9307 case OO_Conditional: 9308 OpBuilder.addConditionalOperatorOverloads(); 9309 OpBuilder.addGenericBinaryArithmeticOverloads(); 9310 break; 9311 } 9312 } 9313 9314 /// Add function candidates found via argument-dependent lookup 9315 /// to the set of overloading candidates. 9316 /// 9317 /// This routine performs argument-dependent name lookup based on the 9318 /// given function name (which may also be an operator name) and adds 9319 /// all of the overload candidates found by ADL to the overload 9320 /// candidate set (C++ [basic.lookup.argdep]). 9321 void 9322 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9323 SourceLocation Loc, 9324 ArrayRef<Expr *> Args, 9325 TemplateArgumentListInfo *ExplicitTemplateArgs, 9326 OverloadCandidateSet& CandidateSet, 9327 bool PartialOverloading) { 9328 ADLResult Fns; 9329 9330 // FIXME: This approach for uniquing ADL results (and removing 9331 // redundant candidates from the set) relies on pointer-equality, 9332 // which means we need to key off the canonical decl. However, 9333 // always going back to the canonical decl might not get us the 9334 // right set of default arguments. What default arguments are 9335 // we supposed to consider on ADL candidates, anyway? 9336 9337 // FIXME: Pass in the explicit template arguments? 9338 ArgumentDependentLookup(Name, Loc, Args, Fns); 9339 9340 // Erase all of the candidates we already knew about. 9341 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9342 CandEnd = CandidateSet.end(); 9343 Cand != CandEnd; ++Cand) 9344 if (Cand->Function) { 9345 Fns.erase(Cand->Function); 9346 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9347 Fns.erase(FunTmpl); 9348 } 9349 9350 // For each of the ADL candidates we found, add it to the overload 9351 // set. 9352 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9353 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9354 9355 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9356 if (ExplicitTemplateArgs) 9357 continue; 9358 9359 AddOverloadCandidate( 9360 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9361 PartialOverloading, /*AllowExplicit=*/true, 9362 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9363 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9364 AddOverloadCandidate( 9365 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9366 /*SuppressUserConversions=*/false, PartialOverloading, 9367 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9368 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9369 } 9370 } else { 9371 auto *FTD = cast<FunctionTemplateDecl>(*I); 9372 AddTemplateOverloadCandidate( 9373 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9374 /*SuppressUserConversions=*/false, PartialOverloading, 9375 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9376 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9377 Context, FTD->getTemplatedDecl())) { 9378 AddTemplateOverloadCandidate( 9379 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9380 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9381 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9382 OverloadCandidateParamOrder::Reversed); 9383 } 9384 } 9385 } 9386 } 9387 9388 namespace { 9389 enum class Comparison { Equal, Better, Worse }; 9390 } 9391 9392 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9393 /// overload resolution. 9394 /// 9395 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9396 /// Cand1's first N enable_if attributes have precisely the same conditions as 9397 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9398 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9399 /// 9400 /// Note that you can have a pair of candidates such that Cand1's enable_if 9401 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9402 /// worse than Cand1's. 9403 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9404 const FunctionDecl *Cand2) { 9405 // Common case: One (or both) decls don't have enable_if attrs. 9406 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9407 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9408 if (!Cand1Attr || !Cand2Attr) { 9409 if (Cand1Attr == Cand2Attr) 9410 return Comparison::Equal; 9411 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9412 } 9413 9414 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9415 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9416 9417 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9418 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9419 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9420 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9421 9422 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9423 // has fewer enable_if attributes than Cand2, and vice versa. 9424 if (!Cand1A) 9425 return Comparison::Worse; 9426 if (!Cand2A) 9427 return Comparison::Better; 9428 9429 Cand1ID.clear(); 9430 Cand2ID.clear(); 9431 9432 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9433 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9434 if (Cand1ID != Cand2ID) 9435 return Comparison::Worse; 9436 } 9437 9438 return Comparison::Equal; 9439 } 9440 9441 static Comparison 9442 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9443 const OverloadCandidate &Cand2) { 9444 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9445 !Cand2.Function->isMultiVersion()) 9446 return Comparison::Equal; 9447 9448 // If both are invalid, they are equal. If one of them is invalid, the other 9449 // is better. 9450 if (Cand1.Function->isInvalidDecl()) { 9451 if (Cand2.Function->isInvalidDecl()) 9452 return Comparison::Equal; 9453 return Comparison::Worse; 9454 } 9455 if (Cand2.Function->isInvalidDecl()) 9456 return Comparison::Better; 9457 9458 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9459 // cpu_dispatch, else arbitrarily based on the identifiers. 9460 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9461 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9462 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9463 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9464 9465 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9466 return Comparison::Equal; 9467 9468 if (Cand1CPUDisp && !Cand2CPUDisp) 9469 return Comparison::Better; 9470 if (Cand2CPUDisp && !Cand1CPUDisp) 9471 return Comparison::Worse; 9472 9473 if (Cand1CPUSpec && Cand2CPUSpec) { 9474 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9475 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9476 ? Comparison::Better 9477 : Comparison::Worse; 9478 9479 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9480 FirstDiff = std::mismatch( 9481 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9482 Cand2CPUSpec->cpus_begin(), 9483 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9484 return LHS->getName() == RHS->getName(); 9485 }); 9486 9487 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9488 "Two different cpu-specific versions should not have the same " 9489 "identifier list, otherwise they'd be the same decl!"); 9490 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9491 ? Comparison::Better 9492 : Comparison::Worse; 9493 } 9494 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9495 } 9496 9497 /// Compute the type of the implicit object parameter for the given function, 9498 /// if any. Returns None if there is no implicit object parameter, and a null 9499 /// QualType if there is a 'matches anything' implicit object parameter. 9500 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9501 const FunctionDecl *F) { 9502 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9503 return llvm::None; 9504 9505 auto *M = cast<CXXMethodDecl>(F); 9506 // Static member functions' object parameters match all types. 9507 if (M->isStatic()) 9508 return QualType(); 9509 9510 QualType T = M->getThisObjectType(); 9511 if (M->getRefQualifier() == RQ_RValue) 9512 return Context.getRValueReferenceType(T); 9513 return Context.getLValueReferenceType(T); 9514 } 9515 9516 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9517 const FunctionDecl *F2, unsigned NumParams) { 9518 if (declaresSameEntity(F1, F2)) 9519 return true; 9520 9521 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9522 if (First) { 9523 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9524 return *T; 9525 } 9526 assert(I < F->getNumParams()); 9527 return F->getParamDecl(I++)->getType(); 9528 }; 9529 9530 unsigned I1 = 0, I2 = 0; 9531 for (unsigned I = 0; I != NumParams; ++I) { 9532 QualType T1 = NextParam(F1, I1, I == 0); 9533 QualType T2 = NextParam(F2, I2, I == 0); 9534 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9535 return false; 9536 } 9537 return true; 9538 } 9539 9540 /// isBetterOverloadCandidate - Determines whether the first overload 9541 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9542 bool clang::isBetterOverloadCandidate( 9543 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9544 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9545 // Define viable functions to be better candidates than non-viable 9546 // functions. 9547 if (!Cand2.Viable) 9548 return Cand1.Viable; 9549 else if (!Cand1.Viable) 9550 return false; 9551 9552 // [CUDA] A function with 'never' preference is marked not viable, therefore 9553 // is never shown up here. The worst preference shown up here is 'wrong side', 9554 // e.g. an H function called by a HD function in device compilation. This is 9555 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9556 // function which is called only by an H function. A deferred diagnostic will 9557 // be triggered if it is emitted. However a wrong-sided function is still 9558 // a viable candidate here. 9559 // 9560 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9561 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9562 // can be emitted, Cand1 is not better than Cand2. This rule should have 9563 // precedence over other rules. 9564 // 9565 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9566 // other rules should be used to determine which is better. This is because 9567 // host/device based overloading resolution is mostly for determining 9568 // viability of a function. If two functions are both viable, other factors 9569 // should take precedence in preference, e.g. the standard-defined preferences 9570 // like argument conversion ranks or enable_if partial-ordering. The 9571 // preference for pass-object-size parameters is probably most similar to a 9572 // type-based-overloading decision and so should take priority. 9573 // 9574 // If other rules cannot determine which is better, CUDA preference will be 9575 // used again to determine which is better. 9576 // 9577 // TODO: Currently IdentifyCUDAPreference does not return correct values 9578 // for functions called in global variable initializers due to missing 9579 // correct context about device/host. Therefore we can only enforce this 9580 // rule when there is a caller. We should enforce this rule for functions 9581 // in global variable initializers once proper context is added. 9582 // 9583 // TODO: We can only enable the hostness based overloading resolution when 9584 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9585 // overloading resolution diagnostics. 9586 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9587 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9588 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9589 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9590 bool IsCand1ImplicitHD = 9591 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9592 bool IsCand2ImplicitHD = 9593 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9594 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9595 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9596 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9597 // The implicit HD function may be a function in a system header which 9598 // is forced by pragma. In device compilation, if we prefer HD candidates 9599 // over wrong-sided candidates, overloading resolution may change, which 9600 // may result in non-deferrable diagnostics. As a workaround, we let 9601 // implicit HD candidates take equal preference as wrong-sided candidates. 9602 // This will preserve the overloading resolution. 9603 // TODO: We still need special handling of implicit HD functions since 9604 // they may incur other diagnostics to be deferred. We should make all 9605 // host/device related diagnostics deferrable and remove special handling 9606 // of implicit HD functions. 9607 auto EmitThreshold = 9608 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9609 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9610 ? Sema::CFP_Never 9611 : Sema::CFP_WrongSide; 9612 auto Cand1Emittable = P1 > EmitThreshold; 9613 auto Cand2Emittable = P2 > EmitThreshold; 9614 if (Cand1Emittable && !Cand2Emittable) 9615 return true; 9616 if (!Cand1Emittable && Cand2Emittable) 9617 return false; 9618 } 9619 } 9620 9621 // C++ [over.match.best]p1: 9622 // 9623 // -- if F is a static member function, ICS1(F) is defined such 9624 // that ICS1(F) is neither better nor worse than ICS1(G) for 9625 // any function G, and, symmetrically, ICS1(G) is neither 9626 // better nor worse than ICS1(F). 9627 unsigned StartArg = 0; 9628 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9629 StartArg = 1; 9630 9631 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9632 // We don't allow incompatible pointer conversions in C++. 9633 if (!S.getLangOpts().CPlusPlus) 9634 return ICS.isStandard() && 9635 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9636 9637 // The only ill-formed conversion we allow in C++ is the string literal to 9638 // char* conversion, which is only considered ill-formed after C++11. 9639 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9640 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9641 }; 9642 9643 // Define functions that don't require ill-formed conversions for a given 9644 // argument to be better candidates than functions that do. 9645 unsigned NumArgs = Cand1.Conversions.size(); 9646 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9647 bool HasBetterConversion = false; 9648 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9649 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9650 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9651 if (Cand1Bad != Cand2Bad) { 9652 if (Cand1Bad) 9653 return false; 9654 HasBetterConversion = true; 9655 } 9656 } 9657 9658 if (HasBetterConversion) 9659 return true; 9660 9661 // C++ [over.match.best]p1: 9662 // A viable function F1 is defined to be a better function than another 9663 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9664 // conversion sequence than ICSi(F2), and then... 9665 bool HasWorseConversion = false; 9666 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9667 switch (CompareImplicitConversionSequences(S, Loc, 9668 Cand1.Conversions[ArgIdx], 9669 Cand2.Conversions[ArgIdx])) { 9670 case ImplicitConversionSequence::Better: 9671 // Cand1 has a better conversion sequence. 9672 HasBetterConversion = true; 9673 break; 9674 9675 case ImplicitConversionSequence::Worse: 9676 if (Cand1.Function && Cand2.Function && 9677 Cand1.isReversed() != Cand2.isReversed() && 9678 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9679 NumArgs)) { 9680 // Work around large-scale breakage caused by considering reversed 9681 // forms of operator== in C++20: 9682 // 9683 // When comparing a function against a reversed function with the same 9684 // parameter types, if we have a better conversion for one argument and 9685 // a worse conversion for the other, the implicit conversion sequences 9686 // are treated as being equally good. 9687 // 9688 // This prevents a comparison function from being considered ambiguous 9689 // with a reversed form that is written in the same way. 9690 // 9691 // We diagnose this as an extension from CreateOverloadedBinOp. 9692 HasWorseConversion = true; 9693 break; 9694 } 9695 9696 // Cand1 can't be better than Cand2. 9697 return false; 9698 9699 case ImplicitConversionSequence::Indistinguishable: 9700 // Do nothing. 9701 break; 9702 } 9703 } 9704 9705 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9706 // ICSj(F2), or, if not that, 9707 if (HasBetterConversion && !HasWorseConversion) 9708 return true; 9709 9710 // -- the context is an initialization by user-defined conversion 9711 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9712 // from the return type of F1 to the destination type (i.e., 9713 // the type of the entity being initialized) is a better 9714 // conversion sequence than the standard conversion sequence 9715 // from the return type of F2 to the destination type. 9716 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9717 Cand1.Function && Cand2.Function && 9718 isa<CXXConversionDecl>(Cand1.Function) && 9719 isa<CXXConversionDecl>(Cand2.Function)) { 9720 // First check whether we prefer one of the conversion functions over the 9721 // other. This only distinguishes the results in non-standard, extension 9722 // cases such as the conversion from a lambda closure type to a function 9723 // pointer or block. 9724 ImplicitConversionSequence::CompareKind Result = 9725 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9726 if (Result == ImplicitConversionSequence::Indistinguishable) 9727 Result = CompareStandardConversionSequences(S, Loc, 9728 Cand1.FinalConversion, 9729 Cand2.FinalConversion); 9730 9731 if (Result != ImplicitConversionSequence::Indistinguishable) 9732 return Result == ImplicitConversionSequence::Better; 9733 9734 // FIXME: Compare kind of reference binding if conversion functions 9735 // convert to a reference type used in direct reference binding, per 9736 // C++14 [over.match.best]p1 section 2 bullet 3. 9737 } 9738 9739 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9740 // as combined with the resolution to CWG issue 243. 9741 // 9742 // When the context is initialization by constructor ([over.match.ctor] or 9743 // either phase of [over.match.list]), a constructor is preferred over 9744 // a conversion function. 9745 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9746 Cand1.Function && Cand2.Function && 9747 isa<CXXConstructorDecl>(Cand1.Function) != 9748 isa<CXXConstructorDecl>(Cand2.Function)) 9749 return isa<CXXConstructorDecl>(Cand1.Function); 9750 9751 // -- F1 is a non-template function and F2 is a function template 9752 // specialization, or, if not that, 9753 bool Cand1IsSpecialization = Cand1.Function && 9754 Cand1.Function->getPrimaryTemplate(); 9755 bool Cand2IsSpecialization = Cand2.Function && 9756 Cand2.Function->getPrimaryTemplate(); 9757 if (Cand1IsSpecialization != Cand2IsSpecialization) 9758 return Cand2IsSpecialization; 9759 9760 // -- F1 and F2 are function template specializations, and the function 9761 // template for F1 is more specialized than the template for F2 9762 // according to the partial ordering rules described in 14.5.5.2, or, 9763 // if not that, 9764 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9765 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9766 Cand1.Function->getPrimaryTemplate(), 9767 Cand2.Function->getPrimaryTemplate(), Loc, 9768 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9769 : TPOC_Call, 9770 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9771 Cand1.isReversed() ^ Cand2.isReversed())) 9772 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9773 } 9774 9775 // -— F1 and F2 are non-template functions with the same 9776 // parameter-type-lists, and F1 is more constrained than F2 [...], 9777 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9778 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9779 Cand2.Function->hasPrototype()) { 9780 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9781 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9782 if (PT1->getNumParams() == PT2->getNumParams() && 9783 PT1->isVariadic() == PT2->isVariadic() && 9784 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9785 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9786 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9787 if (RC1 && RC2) { 9788 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9789 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9790 {RC2}, AtLeastAsConstrained1) || 9791 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9792 {RC1}, AtLeastAsConstrained2)) 9793 return false; 9794 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9795 return AtLeastAsConstrained1; 9796 } else if (RC1 || RC2) { 9797 return RC1 != nullptr; 9798 } 9799 } 9800 } 9801 9802 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9803 // class B of D, and for all arguments the corresponding parameters of 9804 // F1 and F2 have the same type. 9805 // FIXME: Implement the "all parameters have the same type" check. 9806 bool Cand1IsInherited = 9807 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9808 bool Cand2IsInherited = 9809 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9810 if (Cand1IsInherited != Cand2IsInherited) 9811 return Cand2IsInherited; 9812 else if (Cand1IsInherited) { 9813 assert(Cand2IsInherited); 9814 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9815 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9816 if (Cand1Class->isDerivedFrom(Cand2Class)) 9817 return true; 9818 if (Cand2Class->isDerivedFrom(Cand1Class)) 9819 return false; 9820 // Inherited from sibling base classes: still ambiguous. 9821 } 9822 9823 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9824 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9825 // with reversed order of parameters and F1 is not 9826 // 9827 // We rank reversed + different operator as worse than just reversed, but 9828 // that comparison can never happen, because we only consider reversing for 9829 // the maximally-rewritten operator (== or <=>). 9830 if (Cand1.RewriteKind != Cand2.RewriteKind) 9831 return Cand1.RewriteKind < Cand2.RewriteKind; 9832 9833 // Check C++17 tie-breakers for deduction guides. 9834 { 9835 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9836 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9837 if (Guide1 && Guide2) { 9838 // -- F1 is generated from a deduction-guide and F2 is not 9839 if (Guide1->isImplicit() != Guide2->isImplicit()) 9840 return Guide2->isImplicit(); 9841 9842 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9843 if (Guide1->isCopyDeductionCandidate()) 9844 return true; 9845 } 9846 } 9847 9848 // Check for enable_if value-based overload resolution. 9849 if (Cand1.Function && Cand2.Function) { 9850 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9851 if (Cmp != Comparison::Equal) 9852 return Cmp == Comparison::Better; 9853 } 9854 9855 bool HasPS1 = Cand1.Function != nullptr && 9856 functionHasPassObjectSizeParams(Cand1.Function); 9857 bool HasPS2 = Cand2.Function != nullptr && 9858 functionHasPassObjectSizeParams(Cand2.Function); 9859 if (HasPS1 != HasPS2 && HasPS1) 9860 return true; 9861 9862 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9863 if (MV == Comparison::Better) 9864 return true; 9865 if (MV == Comparison::Worse) 9866 return false; 9867 9868 // If other rules cannot determine which is better, CUDA preference is used 9869 // to determine which is better. 9870 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9871 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9872 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9873 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9874 } 9875 9876 return false; 9877 } 9878 9879 /// Determine whether two declarations are "equivalent" for the purposes of 9880 /// name lookup and overload resolution. This applies when the same internal/no 9881 /// linkage entity is defined by two modules (probably by textually including 9882 /// the same header). In such a case, we don't consider the declarations to 9883 /// declare the same entity, but we also don't want lookups with both 9884 /// declarations visible to be ambiguous in some cases (this happens when using 9885 /// a modularized libstdc++). 9886 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9887 const NamedDecl *B) { 9888 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9889 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9890 if (!VA || !VB) 9891 return false; 9892 9893 // The declarations must be declaring the same name as an internal linkage 9894 // entity in different modules. 9895 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9896 VB->getDeclContext()->getRedeclContext()) || 9897 getOwningModule(VA) == getOwningModule(VB) || 9898 VA->isExternallyVisible() || VB->isExternallyVisible()) 9899 return false; 9900 9901 // Check that the declarations appear to be equivalent. 9902 // 9903 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9904 // For constants and functions, we should check the initializer or body is 9905 // the same. For non-constant variables, we shouldn't allow it at all. 9906 if (Context.hasSameType(VA->getType(), VB->getType())) 9907 return true; 9908 9909 // Enum constants within unnamed enumerations will have different types, but 9910 // may still be similar enough to be interchangeable for our purposes. 9911 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9912 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9913 // Only handle anonymous enums. If the enumerations were named and 9914 // equivalent, they would have been merged to the same type. 9915 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9916 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9917 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9918 !Context.hasSameType(EnumA->getIntegerType(), 9919 EnumB->getIntegerType())) 9920 return false; 9921 // Allow this only if the value is the same for both enumerators. 9922 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9923 } 9924 } 9925 9926 // Nothing else is sufficiently similar. 9927 return false; 9928 } 9929 9930 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9931 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9932 assert(D && "Unknown declaration"); 9933 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9934 9935 Module *M = getOwningModule(D); 9936 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9937 << !M << (M ? M->getFullModuleName() : ""); 9938 9939 for (auto *E : Equiv) { 9940 Module *M = getOwningModule(E); 9941 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9942 << !M << (M ? M->getFullModuleName() : ""); 9943 } 9944 } 9945 9946 /// Computes the best viable function (C++ 13.3.3) 9947 /// within an overload candidate set. 9948 /// 9949 /// \param Loc The location of the function name (or operator symbol) for 9950 /// which overload resolution occurs. 9951 /// 9952 /// \param Best If overload resolution was successful or found a deleted 9953 /// function, \p Best points to the candidate function found. 9954 /// 9955 /// \returns The result of overload resolution. 9956 OverloadingResult 9957 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9958 iterator &Best) { 9959 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9960 std::transform(begin(), end(), std::back_inserter(Candidates), 9961 [](OverloadCandidate &Cand) { return &Cand; }); 9962 9963 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9964 // are accepted by both clang and NVCC. However, during a particular 9965 // compilation mode only one call variant is viable. We need to 9966 // exclude non-viable overload candidates from consideration based 9967 // only on their host/device attributes. Specifically, if one 9968 // candidate call is WrongSide and the other is SameSide, we ignore 9969 // the WrongSide candidate. 9970 // We only need to remove wrong-sided candidates here if 9971 // -fgpu-exclude-wrong-side-overloads is off. When 9972 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 9973 // uniformly in isBetterOverloadCandidate. 9974 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 9975 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9976 bool ContainsSameSideCandidate = 9977 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9978 // Check viable function only. 9979 return Cand->Viable && Cand->Function && 9980 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9981 Sema::CFP_SameSide; 9982 }); 9983 if (ContainsSameSideCandidate) { 9984 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9985 // Check viable function only to avoid unnecessary data copying/moving. 9986 return Cand->Viable && Cand->Function && 9987 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9988 Sema::CFP_WrongSide; 9989 }; 9990 llvm::erase_if(Candidates, IsWrongSideCandidate); 9991 } 9992 } 9993 9994 // Find the best viable function. 9995 Best = end(); 9996 for (auto *Cand : Candidates) { 9997 Cand->Best = false; 9998 if (Cand->Viable) 9999 if (Best == end() || 10000 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10001 Best = Cand; 10002 } 10003 10004 // If we didn't find any viable functions, abort. 10005 if (Best == end()) 10006 return OR_No_Viable_Function; 10007 10008 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10009 10010 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10011 PendingBest.push_back(&*Best); 10012 Best->Best = true; 10013 10014 // Make sure that this function is better than every other viable 10015 // function. If not, we have an ambiguity. 10016 while (!PendingBest.empty()) { 10017 auto *Curr = PendingBest.pop_back_val(); 10018 for (auto *Cand : Candidates) { 10019 if (Cand->Viable && !Cand->Best && 10020 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10021 PendingBest.push_back(Cand); 10022 Cand->Best = true; 10023 10024 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10025 Curr->Function)) 10026 EquivalentCands.push_back(Cand->Function); 10027 else 10028 Best = end(); 10029 } 10030 } 10031 } 10032 10033 // If we found more than one best candidate, this is ambiguous. 10034 if (Best == end()) 10035 return OR_Ambiguous; 10036 10037 // Best is the best viable function. 10038 if (Best->Function && Best->Function->isDeleted()) 10039 return OR_Deleted; 10040 10041 if (!EquivalentCands.empty()) 10042 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10043 EquivalentCands); 10044 10045 return OR_Success; 10046 } 10047 10048 namespace { 10049 10050 enum OverloadCandidateKind { 10051 oc_function, 10052 oc_method, 10053 oc_reversed_binary_operator, 10054 oc_constructor, 10055 oc_implicit_default_constructor, 10056 oc_implicit_copy_constructor, 10057 oc_implicit_move_constructor, 10058 oc_implicit_copy_assignment, 10059 oc_implicit_move_assignment, 10060 oc_implicit_equality_comparison, 10061 oc_inherited_constructor 10062 }; 10063 10064 enum OverloadCandidateSelect { 10065 ocs_non_template, 10066 ocs_template, 10067 ocs_described_template, 10068 }; 10069 10070 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10071 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10072 OverloadCandidateRewriteKind CRK, 10073 std::string &Description) { 10074 10075 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10076 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10077 isTemplate = true; 10078 Description = S.getTemplateArgumentBindingsText( 10079 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10080 } 10081 10082 OverloadCandidateSelect Select = [&]() { 10083 if (!Description.empty()) 10084 return ocs_described_template; 10085 return isTemplate ? ocs_template : ocs_non_template; 10086 }(); 10087 10088 OverloadCandidateKind Kind = [&]() { 10089 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10090 return oc_implicit_equality_comparison; 10091 10092 if (CRK & CRK_Reversed) 10093 return oc_reversed_binary_operator; 10094 10095 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10096 if (!Ctor->isImplicit()) { 10097 if (isa<ConstructorUsingShadowDecl>(Found)) 10098 return oc_inherited_constructor; 10099 else 10100 return oc_constructor; 10101 } 10102 10103 if (Ctor->isDefaultConstructor()) 10104 return oc_implicit_default_constructor; 10105 10106 if (Ctor->isMoveConstructor()) 10107 return oc_implicit_move_constructor; 10108 10109 assert(Ctor->isCopyConstructor() && 10110 "unexpected sort of implicit constructor"); 10111 return oc_implicit_copy_constructor; 10112 } 10113 10114 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10115 // This actually gets spelled 'candidate function' for now, but 10116 // it doesn't hurt to split it out. 10117 if (!Meth->isImplicit()) 10118 return oc_method; 10119 10120 if (Meth->isMoveAssignmentOperator()) 10121 return oc_implicit_move_assignment; 10122 10123 if (Meth->isCopyAssignmentOperator()) 10124 return oc_implicit_copy_assignment; 10125 10126 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10127 return oc_method; 10128 } 10129 10130 return oc_function; 10131 }(); 10132 10133 return std::make_pair(Kind, Select); 10134 } 10135 10136 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10137 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10138 // set. 10139 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10140 S.Diag(FoundDecl->getLocation(), 10141 diag::note_ovl_candidate_inherited_constructor) 10142 << Shadow->getNominatedBaseClass(); 10143 } 10144 10145 } // end anonymous namespace 10146 10147 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10148 const FunctionDecl *FD) { 10149 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10150 bool AlwaysTrue; 10151 if (EnableIf->getCond()->isValueDependent() || 10152 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10153 return false; 10154 if (!AlwaysTrue) 10155 return false; 10156 } 10157 return true; 10158 } 10159 10160 /// Returns true if we can take the address of the function. 10161 /// 10162 /// \param Complain - If true, we'll emit a diagnostic 10163 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10164 /// we in overload resolution? 10165 /// \param Loc - The location of the statement we're complaining about. Ignored 10166 /// if we're not complaining, or if we're in overload resolution. 10167 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10168 bool Complain, 10169 bool InOverloadResolution, 10170 SourceLocation Loc) { 10171 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10172 if (Complain) { 10173 if (InOverloadResolution) 10174 S.Diag(FD->getBeginLoc(), 10175 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10176 else 10177 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10178 } 10179 return false; 10180 } 10181 10182 if (FD->getTrailingRequiresClause()) { 10183 ConstraintSatisfaction Satisfaction; 10184 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10185 return false; 10186 if (!Satisfaction.IsSatisfied) { 10187 if (Complain) { 10188 if (InOverloadResolution) 10189 S.Diag(FD->getBeginLoc(), 10190 diag::note_ovl_candidate_unsatisfied_constraints); 10191 else 10192 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10193 << FD; 10194 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10195 } 10196 return false; 10197 } 10198 } 10199 10200 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10201 return P->hasAttr<PassObjectSizeAttr>(); 10202 }); 10203 if (I == FD->param_end()) 10204 return true; 10205 10206 if (Complain) { 10207 // Add one to ParamNo because it's user-facing 10208 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10209 if (InOverloadResolution) 10210 S.Diag(FD->getLocation(), 10211 diag::note_ovl_candidate_has_pass_object_size_params) 10212 << ParamNo; 10213 else 10214 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10215 << FD << ParamNo; 10216 } 10217 return false; 10218 } 10219 10220 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10221 const FunctionDecl *FD) { 10222 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10223 /*InOverloadResolution=*/true, 10224 /*Loc=*/SourceLocation()); 10225 } 10226 10227 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10228 bool Complain, 10229 SourceLocation Loc) { 10230 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10231 /*InOverloadResolution=*/false, 10232 Loc); 10233 } 10234 10235 // Don't print candidates other than the one that matches the calling 10236 // convention of the call operator, since that is guaranteed to exist. 10237 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10238 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10239 10240 if (!ConvD) 10241 return false; 10242 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10243 if (!RD->isLambda()) 10244 return false; 10245 10246 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10247 CallingConv CallOpCC = 10248 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10249 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10250 CallingConv ConvToCC = 10251 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10252 10253 return ConvToCC != CallOpCC; 10254 } 10255 10256 // Notes the location of an overload candidate. 10257 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10258 OverloadCandidateRewriteKind RewriteKind, 10259 QualType DestType, bool TakingAddress) { 10260 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10261 return; 10262 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10263 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10264 return; 10265 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10266 return; 10267 10268 std::string FnDesc; 10269 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10270 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10271 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10272 << (unsigned)KSPair.first << (unsigned)KSPair.second 10273 << Fn << FnDesc; 10274 10275 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10276 Diag(Fn->getLocation(), PD); 10277 MaybeEmitInheritedConstructorNote(*this, Found); 10278 } 10279 10280 static void 10281 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10282 // Perhaps the ambiguity was caused by two atomic constraints that are 10283 // 'identical' but not equivalent: 10284 // 10285 // void foo() requires (sizeof(T) > 4) { } // #1 10286 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10287 // 10288 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10289 // #2 to subsume #1, but these constraint are not considered equivalent 10290 // according to the subsumption rules because they are not the same 10291 // source-level construct. This behavior is quite confusing and we should try 10292 // to help the user figure out what happened. 10293 10294 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10295 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10296 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10297 if (!I->Function) 10298 continue; 10299 SmallVector<const Expr *, 3> AC; 10300 if (auto *Template = I->Function->getPrimaryTemplate()) 10301 Template->getAssociatedConstraints(AC); 10302 else 10303 I->Function->getAssociatedConstraints(AC); 10304 if (AC.empty()) 10305 continue; 10306 if (FirstCand == nullptr) { 10307 FirstCand = I->Function; 10308 FirstAC = AC; 10309 } else if (SecondCand == nullptr) { 10310 SecondCand = I->Function; 10311 SecondAC = AC; 10312 } else { 10313 // We have more than one pair of constrained functions - this check is 10314 // expensive and we'd rather not try to diagnose it. 10315 return; 10316 } 10317 } 10318 if (!SecondCand) 10319 return; 10320 // The diagnostic can only happen if there are associated constraints on 10321 // both sides (there needs to be some identical atomic constraint). 10322 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10323 SecondCand, SecondAC)) 10324 // Just show the user one diagnostic, they'll probably figure it out 10325 // from here. 10326 return; 10327 } 10328 10329 // Notes the location of all overload candidates designated through 10330 // OverloadedExpr 10331 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10332 bool TakingAddress) { 10333 assert(OverloadedExpr->getType() == Context.OverloadTy); 10334 10335 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10336 OverloadExpr *OvlExpr = Ovl.Expression; 10337 10338 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10339 IEnd = OvlExpr->decls_end(); 10340 I != IEnd; ++I) { 10341 if (FunctionTemplateDecl *FunTmpl = 10342 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10343 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10344 TakingAddress); 10345 } else if (FunctionDecl *Fun 10346 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10347 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10348 } 10349 } 10350 } 10351 10352 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10353 /// "lead" diagnostic; it will be given two arguments, the source and 10354 /// target types of the conversion. 10355 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10356 Sema &S, 10357 SourceLocation CaretLoc, 10358 const PartialDiagnostic &PDiag) const { 10359 S.Diag(CaretLoc, PDiag) 10360 << Ambiguous.getFromType() << Ambiguous.getToType(); 10361 unsigned CandsShown = 0; 10362 AmbiguousConversionSequence::const_iterator I, E; 10363 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10364 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10365 break; 10366 ++CandsShown; 10367 S.NoteOverloadCandidate(I->first, I->second); 10368 } 10369 S.Diags.overloadCandidatesShown(CandsShown); 10370 if (I != E) 10371 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10372 } 10373 10374 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10375 unsigned I, bool TakingCandidateAddress) { 10376 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10377 assert(Conv.isBad()); 10378 assert(Cand->Function && "for now, candidate must be a function"); 10379 FunctionDecl *Fn = Cand->Function; 10380 10381 // There's a conversion slot for the object argument if this is a 10382 // non-constructor method. Note that 'I' corresponds the 10383 // conversion-slot index. 10384 bool isObjectArgument = false; 10385 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10386 if (I == 0) 10387 isObjectArgument = true; 10388 else 10389 I--; 10390 } 10391 10392 std::string FnDesc; 10393 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10394 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10395 FnDesc); 10396 10397 Expr *FromExpr = Conv.Bad.FromExpr; 10398 QualType FromTy = Conv.Bad.getFromType(); 10399 QualType ToTy = Conv.Bad.getToType(); 10400 10401 if (FromTy == S.Context.OverloadTy) { 10402 assert(FromExpr && "overload set argument came from implicit argument?"); 10403 Expr *E = FromExpr->IgnoreParens(); 10404 if (isa<UnaryOperator>(E)) 10405 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10406 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10407 10408 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10409 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10410 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10411 << Name << I + 1; 10412 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10413 return; 10414 } 10415 10416 // Do some hand-waving analysis to see if the non-viability is due 10417 // to a qualifier mismatch. 10418 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10419 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10420 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10421 CToTy = RT->getPointeeType(); 10422 else { 10423 // TODO: detect and diagnose the full richness of const mismatches. 10424 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10425 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10426 CFromTy = FromPT->getPointeeType(); 10427 CToTy = ToPT->getPointeeType(); 10428 } 10429 } 10430 10431 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10432 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10433 Qualifiers FromQs = CFromTy.getQualifiers(); 10434 Qualifiers ToQs = CToTy.getQualifiers(); 10435 10436 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10437 if (isObjectArgument) 10438 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10439 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10440 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10441 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10442 else 10443 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10444 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10445 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10446 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10447 << ToTy->isReferenceType() << I + 1; 10448 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10449 return; 10450 } 10451 10452 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10454 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10455 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10456 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10457 << (unsigned)isObjectArgument << I + 1; 10458 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10459 return; 10460 } 10461 10462 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10464 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10465 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10466 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10467 << (unsigned)isObjectArgument << I + 1; 10468 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10469 return; 10470 } 10471 10472 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10473 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10474 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10475 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10476 << FromQs.hasUnaligned() << I + 1; 10477 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10478 return; 10479 } 10480 10481 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10482 assert(CVR && "expected qualifiers mismatch"); 10483 10484 if (isObjectArgument) { 10485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10486 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10487 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10488 << (CVR - 1); 10489 } else { 10490 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10491 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10492 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10493 << (CVR - 1) << I + 1; 10494 } 10495 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10496 return; 10497 } 10498 10499 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10500 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10501 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10502 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10503 << (unsigned)isObjectArgument << I + 1 10504 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10506 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10507 return; 10508 } 10509 10510 // Special diagnostic for failure to convert an initializer list, since 10511 // telling the user that it has type void is not useful. 10512 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10513 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10514 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10515 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10516 << ToTy << (unsigned)isObjectArgument << I + 1; 10517 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10518 return; 10519 } 10520 10521 // Diagnose references or pointers to incomplete types differently, 10522 // since it's far from impossible that the incompleteness triggered 10523 // the failure. 10524 QualType TempFromTy = FromTy.getNonReferenceType(); 10525 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10526 TempFromTy = PTy->getPointeeType(); 10527 if (TempFromTy->isIncompleteType()) { 10528 // Emit the generic diagnostic and, optionally, add the hints to it. 10529 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10530 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10531 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10532 << ToTy << (unsigned)isObjectArgument << I + 1 10533 << (unsigned)(Cand->Fix.Kind); 10534 10535 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10536 return; 10537 } 10538 10539 // Diagnose base -> derived pointer conversions. 10540 unsigned BaseToDerivedConversion = 0; 10541 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10542 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10543 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10544 FromPtrTy->getPointeeType()) && 10545 !FromPtrTy->getPointeeType()->isIncompleteType() && 10546 !ToPtrTy->getPointeeType()->isIncompleteType() && 10547 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10548 FromPtrTy->getPointeeType())) 10549 BaseToDerivedConversion = 1; 10550 } 10551 } else if (const ObjCObjectPointerType *FromPtrTy 10552 = FromTy->getAs<ObjCObjectPointerType>()) { 10553 if (const ObjCObjectPointerType *ToPtrTy 10554 = ToTy->getAs<ObjCObjectPointerType>()) 10555 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10556 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10557 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10558 FromPtrTy->getPointeeType()) && 10559 FromIface->isSuperClassOf(ToIface)) 10560 BaseToDerivedConversion = 2; 10561 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10562 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10563 !FromTy->isIncompleteType() && 10564 !ToRefTy->getPointeeType()->isIncompleteType() && 10565 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10566 BaseToDerivedConversion = 3; 10567 } 10568 } 10569 10570 if (BaseToDerivedConversion) { 10571 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10572 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10573 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10574 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10575 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10576 return; 10577 } 10578 10579 if (isa<ObjCObjectPointerType>(CFromTy) && 10580 isa<PointerType>(CToTy)) { 10581 Qualifiers FromQs = CFromTy.getQualifiers(); 10582 Qualifiers ToQs = CToTy.getQualifiers(); 10583 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10585 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10586 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10587 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10588 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10589 return; 10590 } 10591 } 10592 10593 if (TakingCandidateAddress && 10594 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10595 return; 10596 10597 // Emit the generic diagnostic and, optionally, add the hints to it. 10598 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10599 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10600 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10601 << ToTy << (unsigned)isObjectArgument << I + 1 10602 << (unsigned)(Cand->Fix.Kind); 10603 10604 // If we can fix the conversion, suggest the FixIts. 10605 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10606 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10607 FDiag << *HI; 10608 S.Diag(Fn->getLocation(), FDiag); 10609 10610 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10611 } 10612 10613 /// Additional arity mismatch diagnosis specific to a function overload 10614 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10615 /// over a candidate in any candidate set. 10616 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10617 unsigned NumArgs) { 10618 FunctionDecl *Fn = Cand->Function; 10619 unsigned MinParams = Fn->getMinRequiredArguments(); 10620 10621 // With invalid overloaded operators, it's possible that we think we 10622 // have an arity mismatch when in fact it looks like we have the 10623 // right number of arguments, because only overloaded operators have 10624 // the weird behavior of overloading member and non-member functions. 10625 // Just don't report anything. 10626 if (Fn->isInvalidDecl() && 10627 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10628 return true; 10629 10630 if (NumArgs < MinParams) { 10631 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10632 (Cand->FailureKind == ovl_fail_bad_deduction && 10633 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10634 } else { 10635 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10636 (Cand->FailureKind == ovl_fail_bad_deduction && 10637 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10638 } 10639 10640 return false; 10641 } 10642 10643 /// General arity mismatch diagnosis over a candidate in a candidate set. 10644 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10645 unsigned NumFormalArgs) { 10646 assert(isa<FunctionDecl>(D) && 10647 "The templated declaration should at least be a function" 10648 " when diagnosing bad template argument deduction due to too many" 10649 " or too few arguments"); 10650 10651 FunctionDecl *Fn = cast<FunctionDecl>(D); 10652 10653 // TODO: treat calls to a missing default constructor as a special case 10654 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10655 unsigned MinParams = Fn->getMinRequiredArguments(); 10656 10657 // at least / at most / exactly 10658 unsigned mode, modeCount; 10659 if (NumFormalArgs < MinParams) { 10660 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10661 FnTy->isTemplateVariadic()) 10662 mode = 0; // "at least" 10663 else 10664 mode = 2; // "exactly" 10665 modeCount = MinParams; 10666 } else { 10667 if (MinParams != FnTy->getNumParams()) 10668 mode = 1; // "at most" 10669 else 10670 mode = 2; // "exactly" 10671 modeCount = FnTy->getNumParams(); 10672 } 10673 10674 std::string Description; 10675 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10676 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10677 10678 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10679 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10680 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10681 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10682 else 10683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10684 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10685 << Description << mode << modeCount << NumFormalArgs; 10686 10687 MaybeEmitInheritedConstructorNote(S, Found); 10688 } 10689 10690 /// Arity mismatch diagnosis specific to a function overload candidate. 10691 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10692 unsigned NumFormalArgs) { 10693 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10694 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10695 } 10696 10697 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10698 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10699 return TD; 10700 llvm_unreachable("Unsupported: Getting the described template declaration" 10701 " for bad deduction diagnosis"); 10702 } 10703 10704 /// Diagnose a failed template-argument deduction. 10705 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10706 DeductionFailureInfo &DeductionFailure, 10707 unsigned NumArgs, 10708 bool TakingCandidateAddress) { 10709 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10710 NamedDecl *ParamD; 10711 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10712 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10713 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10714 switch (DeductionFailure.Result) { 10715 case Sema::TDK_Success: 10716 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10717 10718 case Sema::TDK_Incomplete: { 10719 assert(ParamD && "no parameter found for incomplete deduction result"); 10720 S.Diag(Templated->getLocation(), 10721 diag::note_ovl_candidate_incomplete_deduction) 10722 << ParamD->getDeclName(); 10723 MaybeEmitInheritedConstructorNote(S, Found); 10724 return; 10725 } 10726 10727 case Sema::TDK_IncompletePack: { 10728 assert(ParamD && "no parameter found for incomplete deduction result"); 10729 S.Diag(Templated->getLocation(), 10730 diag::note_ovl_candidate_incomplete_deduction_pack) 10731 << ParamD->getDeclName() 10732 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10733 << *DeductionFailure.getFirstArg(); 10734 MaybeEmitInheritedConstructorNote(S, Found); 10735 return; 10736 } 10737 10738 case Sema::TDK_Underqualified: { 10739 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10740 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10741 10742 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10743 10744 // Param will have been canonicalized, but it should just be a 10745 // qualified version of ParamD, so move the qualifiers to that. 10746 QualifierCollector Qs; 10747 Qs.strip(Param); 10748 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10749 assert(S.Context.hasSameType(Param, NonCanonParam)); 10750 10751 // Arg has also been canonicalized, but there's nothing we can do 10752 // about that. It also doesn't matter as much, because it won't 10753 // have any template parameters in it (because deduction isn't 10754 // done on dependent types). 10755 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10756 10757 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10758 << ParamD->getDeclName() << Arg << NonCanonParam; 10759 MaybeEmitInheritedConstructorNote(S, Found); 10760 return; 10761 } 10762 10763 case Sema::TDK_Inconsistent: { 10764 assert(ParamD && "no parameter found for inconsistent deduction result"); 10765 int which = 0; 10766 if (isa<TemplateTypeParmDecl>(ParamD)) 10767 which = 0; 10768 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10769 // Deduction might have failed because we deduced arguments of two 10770 // different types for a non-type template parameter. 10771 // FIXME: Use a different TDK value for this. 10772 QualType T1 = 10773 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10774 QualType T2 = 10775 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10776 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10777 S.Diag(Templated->getLocation(), 10778 diag::note_ovl_candidate_inconsistent_deduction_types) 10779 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10780 << *DeductionFailure.getSecondArg() << T2; 10781 MaybeEmitInheritedConstructorNote(S, Found); 10782 return; 10783 } 10784 10785 which = 1; 10786 } else { 10787 which = 2; 10788 } 10789 10790 // Tweak the diagnostic if the problem is that we deduced packs of 10791 // different arities. We'll print the actual packs anyway in case that 10792 // includes additional useful information. 10793 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10794 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10795 DeductionFailure.getFirstArg()->pack_size() != 10796 DeductionFailure.getSecondArg()->pack_size()) { 10797 which = 3; 10798 } 10799 10800 S.Diag(Templated->getLocation(), 10801 diag::note_ovl_candidate_inconsistent_deduction) 10802 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10803 << *DeductionFailure.getSecondArg(); 10804 MaybeEmitInheritedConstructorNote(S, Found); 10805 return; 10806 } 10807 10808 case Sema::TDK_InvalidExplicitArguments: 10809 assert(ParamD && "no parameter found for invalid explicit arguments"); 10810 if (ParamD->getDeclName()) 10811 S.Diag(Templated->getLocation(), 10812 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10813 << ParamD->getDeclName(); 10814 else { 10815 int index = 0; 10816 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10817 index = TTP->getIndex(); 10818 else if (NonTypeTemplateParmDecl *NTTP 10819 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10820 index = NTTP->getIndex(); 10821 else 10822 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10823 S.Diag(Templated->getLocation(), 10824 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10825 << (index + 1); 10826 } 10827 MaybeEmitInheritedConstructorNote(S, Found); 10828 return; 10829 10830 case Sema::TDK_ConstraintsNotSatisfied: { 10831 // Format the template argument list into the argument string. 10832 SmallString<128> TemplateArgString; 10833 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10834 TemplateArgString = " "; 10835 TemplateArgString += S.getTemplateArgumentBindingsText( 10836 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10837 if (TemplateArgString.size() == 1) 10838 TemplateArgString.clear(); 10839 S.Diag(Templated->getLocation(), 10840 diag::note_ovl_candidate_unsatisfied_constraints) 10841 << TemplateArgString; 10842 10843 S.DiagnoseUnsatisfiedConstraint( 10844 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10845 return; 10846 } 10847 case Sema::TDK_TooManyArguments: 10848 case Sema::TDK_TooFewArguments: 10849 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10850 return; 10851 10852 case Sema::TDK_InstantiationDepth: 10853 S.Diag(Templated->getLocation(), 10854 diag::note_ovl_candidate_instantiation_depth); 10855 MaybeEmitInheritedConstructorNote(S, Found); 10856 return; 10857 10858 case Sema::TDK_SubstitutionFailure: { 10859 // Format the template argument list into the argument string. 10860 SmallString<128> TemplateArgString; 10861 if (TemplateArgumentList *Args = 10862 DeductionFailure.getTemplateArgumentList()) { 10863 TemplateArgString = " "; 10864 TemplateArgString += S.getTemplateArgumentBindingsText( 10865 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10866 if (TemplateArgString.size() == 1) 10867 TemplateArgString.clear(); 10868 } 10869 10870 // If this candidate was disabled by enable_if, say so. 10871 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10872 if (PDiag && PDiag->second.getDiagID() == 10873 diag::err_typename_nested_not_found_enable_if) { 10874 // FIXME: Use the source range of the condition, and the fully-qualified 10875 // name of the enable_if template. These are both present in PDiag. 10876 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10877 << "'enable_if'" << TemplateArgString; 10878 return; 10879 } 10880 10881 // We found a specific requirement that disabled the enable_if. 10882 if (PDiag && PDiag->second.getDiagID() == 10883 diag::err_typename_nested_not_found_requirement) { 10884 S.Diag(Templated->getLocation(), 10885 diag::note_ovl_candidate_disabled_by_requirement) 10886 << PDiag->second.getStringArg(0) << TemplateArgString; 10887 return; 10888 } 10889 10890 // Format the SFINAE diagnostic into the argument string. 10891 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10892 // formatted message in another diagnostic. 10893 SmallString<128> SFINAEArgString; 10894 SourceRange R; 10895 if (PDiag) { 10896 SFINAEArgString = ": "; 10897 R = SourceRange(PDiag->first, PDiag->first); 10898 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10899 } 10900 10901 S.Diag(Templated->getLocation(), 10902 diag::note_ovl_candidate_substitution_failure) 10903 << TemplateArgString << SFINAEArgString << R; 10904 MaybeEmitInheritedConstructorNote(S, Found); 10905 return; 10906 } 10907 10908 case Sema::TDK_DeducedMismatch: 10909 case Sema::TDK_DeducedMismatchNested: { 10910 // Format the template argument list into the argument string. 10911 SmallString<128> TemplateArgString; 10912 if (TemplateArgumentList *Args = 10913 DeductionFailure.getTemplateArgumentList()) { 10914 TemplateArgString = " "; 10915 TemplateArgString += S.getTemplateArgumentBindingsText( 10916 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10917 if (TemplateArgString.size() == 1) 10918 TemplateArgString.clear(); 10919 } 10920 10921 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10922 << (*DeductionFailure.getCallArgIndex() + 1) 10923 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10924 << TemplateArgString 10925 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10926 break; 10927 } 10928 10929 case Sema::TDK_NonDeducedMismatch: { 10930 // FIXME: Provide a source location to indicate what we couldn't match. 10931 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10932 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10933 if (FirstTA.getKind() == TemplateArgument::Template && 10934 SecondTA.getKind() == TemplateArgument::Template) { 10935 TemplateName FirstTN = FirstTA.getAsTemplate(); 10936 TemplateName SecondTN = SecondTA.getAsTemplate(); 10937 if (FirstTN.getKind() == TemplateName::Template && 10938 SecondTN.getKind() == TemplateName::Template) { 10939 if (FirstTN.getAsTemplateDecl()->getName() == 10940 SecondTN.getAsTemplateDecl()->getName()) { 10941 // FIXME: This fixes a bad diagnostic where both templates are named 10942 // the same. This particular case is a bit difficult since: 10943 // 1) It is passed as a string to the diagnostic printer. 10944 // 2) The diagnostic printer only attempts to find a better 10945 // name for types, not decls. 10946 // Ideally, this should folded into the diagnostic printer. 10947 S.Diag(Templated->getLocation(), 10948 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10949 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10950 return; 10951 } 10952 } 10953 } 10954 10955 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10956 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10957 return; 10958 10959 // FIXME: For generic lambda parameters, check if the function is a lambda 10960 // call operator, and if so, emit a prettier and more informative 10961 // diagnostic that mentions 'auto' and lambda in addition to 10962 // (or instead of?) the canonical template type parameters. 10963 S.Diag(Templated->getLocation(), 10964 diag::note_ovl_candidate_non_deduced_mismatch) 10965 << FirstTA << SecondTA; 10966 return; 10967 } 10968 // TODO: diagnose these individually, then kill off 10969 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10970 case Sema::TDK_MiscellaneousDeductionFailure: 10971 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10972 MaybeEmitInheritedConstructorNote(S, Found); 10973 return; 10974 case Sema::TDK_CUDATargetMismatch: 10975 S.Diag(Templated->getLocation(), 10976 diag::note_cuda_ovl_candidate_target_mismatch); 10977 return; 10978 } 10979 } 10980 10981 /// Diagnose a failed template-argument deduction, for function calls. 10982 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10983 unsigned NumArgs, 10984 bool TakingCandidateAddress) { 10985 unsigned TDK = Cand->DeductionFailure.Result; 10986 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10987 if (CheckArityMismatch(S, Cand, NumArgs)) 10988 return; 10989 } 10990 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10991 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10992 } 10993 10994 /// CUDA: diagnose an invalid call across targets. 10995 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10996 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10997 FunctionDecl *Callee = Cand->Function; 10998 10999 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11000 CalleeTarget = S.IdentifyCUDATarget(Callee); 11001 11002 std::string FnDesc; 11003 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11004 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11005 Cand->getRewriteKind(), FnDesc); 11006 11007 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11008 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11009 << FnDesc /* Ignored */ 11010 << CalleeTarget << CallerTarget; 11011 11012 // This could be an implicit constructor for which we could not infer the 11013 // target due to a collsion. Diagnose that case. 11014 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11015 if (Meth != nullptr && Meth->isImplicit()) { 11016 CXXRecordDecl *ParentClass = Meth->getParent(); 11017 Sema::CXXSpecialMember CSM; 11018 11019 switch (FnKindPair.first) { 11020 default: 11021 return; 11022 case oc_implicit_default_constructor: 11023 CSM = Sema::CXXDefaultConstructor; 11024 break; 11025 case oc_implicit_copy_constructor: 11026 CSM = Sema::CXXCopyConstructor; 11027 break; 11028 case oc_implicit_move_constructor: 11029 CSM = Sema::CXXMoveConstructor; 11030 break; 11031 case oc_implicit_copy_assignment: 11032 CSM = Sema::CXXCopyAssignment; 11033 break; 11034 case oc_implicit_move_assignment: 11035 CSM = Sema::CXXMoveAssignment; 11036 break; 11037 }; 11038 11039 bool ConstRHS = false; 11040 if (Meth->getNumParams()) { 11041 if (const ReferenceType *RT = 11042 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11043 ConstRHS = RT->getPointeeType().isConstQualified(); 11044 } 11045 } 11046 11047 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11048 /* ConstRHS */ ConstRHS, 11049 /* Diagnose */ true); 11050 } 11051 } 11052 11053 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11054 FunctionDecl *Callee = Cand->Function; 11055 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11056 11057 S.Diag(Callee->getLocation(), 11058 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11059 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11060 } 11061 11062 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11063 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11064 assert(ES.isExplicit() && "not an explicit candidate"); 11065 11066 unsigned Kind; 11067 switch (Cand->Function->getDeclKind()) { 11068 case Decl::Kind::CXXConstructor: 11069 Kind = 0; 11070 break; 11071 case Decl::Kind::CXXConversion: 11072 Kind = 1; 11073 break; 11074 case Decl::Kind::CXXDeductionGuide: 11075 Kind = Cand->Function->isImplicit() ? 0 : 2; 11076 break; 11077 default: 11078 llvm_unreachable("invalid Decl"); 11079 } 11080 11081 // Note the location of the first (in-class) declaration; a redeclaration 11082 // (particularly an out-of-class definition) will typically lack the 11083 // 'explicit' specifier. 11084 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11085 FunctionDecl *First = Cand->Function->getFirstDecl(); 11086 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11087 First = Pattern->getFirstDecl(); 11088 11089 S.Diag(First->getLocation(), 11090 diag::note_ovl_candidate_explicit) 11091 << Kind << (ES.getExpr() ? 1 : 0) 11092 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11093 } 11094 11095 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 11096 FunctionDecl *Callee = Cand->Function; 11097 11098 S.Diag(Callee->getLocation(), 11099 diag::note_ovl_candidate_disabled_by_extension) 11100 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 11101 } 11102 11103 /// Generates a 'note' diagnostic for an overload candidate. We've 11104 /// already generated a primary error at the call site. 11105 /// 11106 /// It really does need to be a single diagnostic with its caret 11107 /// pointed at the candidate declaration. Yes, this creates some 11108 /// major challenges of technical writing. Yes, this makes pointing 11109 /// out problems with specific arguments quite awkward. It's still 11110 /// better than generating twenty screens of text for every failed 11111 /// overload. 11112 /// 11113 /// It would be great to be able to express per-candidate problems 11114 /// more richly for those diagnostic clients that cared, but we'd 11115 /// still have to be just as careful with the default diagnostics. 11116 /// \param CtorDestAS Addr space of object being constructed (for ctor 11117 /// candidates only). 11118 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11119 unsigned NumArgs, 11120 bool TakingCandidateAddress, 11121 LangAS CtorDestAS = LangAS::Default) { 11122 FunctionDecl *Fn = Cand->Function; 11123 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11124 return; 11125 11126 // Note deleted candidates, but only if they're viable. 11127 if (Cand->Viable) { 11128 if (Fn->isDeleted()) { 11129 std::string FnDesc; 11130 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11131 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11132 Cand->getRewriteKind(), FnDesc); 11133 11134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11135 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11136 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11137 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11138 return; 11139 } 11140 11141 // We don't really have anything else to say about viable candidates. 11142 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11143 return; 11144 } 11145 11146 switch (Cand->FailureKind) { 11147 case ovl_fail_too_many_arguments: 11148 case ovl_fail_too_few_arguments: 11149 return DiagnoseArityMismatch(S, Cand, NumArgs); 11150 11151 case ovl_fail_bad_deduction: 11152 return DiagnoseBadDeduction(S, Cand, NumArgs, 11153 TakingCandidateAddress); 11154 11155 case ovl_fail_illegal_constructor: { 11156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11157 << (Fn->getPrimaryTemplate() ? 1 : 0); 11158 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11159 return; 11160 } 11161 11162 case ovl_fail_object_addrspace_mismatch: { 11163 Qualifiers QualsForPrinting; 11164 QualsForPrinting.setAddressSpace(CtorDestAS); 11165 S.Diag(Fn->getLocation(), 11166 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11167 << QualsForPrinting; 11168 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11169 return; 11170 } 11171 11172 case ovl_fail_trivial_conversion: 11173 case ovl_fail_bad_final_conversion: 11174 case ovl_fail_final_conversion_not_exact: 11175 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11176 11177 case ovl_fail_bad_conversion: { 11178 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11179 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11180 if (Cand->Conversions[I].isBad()) 11181 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11182 11183 // FIXME: this currently happens when we're called from SemaInit 11184 // when user-conversion overload fails. Figure out how to handle 11185 // those conditions and diagnose them well. 11186 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11187 } 11188 11189 case ovl_fail_bad_target: 11190 return DiagnoseBadTarget(S, Cand); 11191 11192 case ovl_fail_enable_if: 11193 return DiagnoseFailedEnableIfAttr(S, Cand); 11194 11195 case ovl_fail_explicit: 11196 return DiagnoseFailedExplicitSpec(S, Cand); 11197 11198 case ovl_fail_ext_disabled: 11199 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11200 11201 case ovl_fail_inhctor_slice: 11202 // It's generally not interesting to note copy/move constructors here. 11203 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11204 return; 11205 S.Diag(Fn->getLocation(), 11206 diag::note_ovl_candidate_inherited_constructor_slice) 11207 << (Fn->getPrimaryTemplate() ? 1 : 0) 11208 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11209 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11210 return; 11211 11212 case ovl_fail_addr_not_available: { 11213 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11214 (void)Available; 11215 assert(!Available); 11216 break; 11217 } 11218 case ovl_non_default_multiversion_function: 11219 // Do nothing, these should simply be ignored. 11220 break; 11221 11222 case ovl_fail_constraints_not_satisfied: { 11223 std::string FnDesc; 11224 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11225 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11226 Cand->getRewriteKind(), FnDesc); 11227 11228 S.Diag(Fn->getLocation(), 11229 diag::note_ovl_candidate_constraints_not_satisfied) 11230 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11231 << FnDesc /* Ignored */; 11232 ConstraintSatisfaction Satisfaction; 11233 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11234 break; 11235 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11236 } 11237 } 11238 } 11239 11240 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11241 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11242 return; 11243 11244 // Desugar the type of the surrogate down to a function type, 11245 // retaining as many typedefs as possible while still showing 11246 // the function type (and, therefore, its parameter types). 11247 QualType FnType = Cand->Surrogate->getConversionType(); 11248 bool isLValueReference = false; 11249 bool isRValueReference = false; 11250 bool isPointer = false; 11251 if (const LValueReferenceType *FnTypeRef = 11252 FnType->getAs<LValueReferenceType>()) { 11253 FnType = FnTypeRef->getPointeeType(); 11254 isLValueReference = true; 11255 } else if (const RValueReferenceType *FnTypeRef = 11256 FnType->getAs<RValueReferenceType>()) { 11257 FnType = FnTypeRef->getPointeeType(); 11258 isRValueReference = true; 11259 } 11260 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11261 FnType = FnTypePtr->getPointeeType(); 11262 isPointer = true; 11263 } 11264 // Desugar down to a function type. 11265 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11266 // Reconstruct the pointer/reference as appropriate. 11267 if (isPointer) FnType = S.Context.getPointerType(FnType); 11268 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11269 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11270 11271 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11272 << FnType; 11273 } 11274 11275 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11276 SourceLocation OpLoc, 11277 OverloadCandidate *Cand) { 11278 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11279 std::string TypeStr("operator"); 11280 TypeStr += Opc; 11281 TypeStr += "("; 11282 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11283 if (Cand->Conversions.size() == 1) { 11284 TypeStr += ")"; 11285 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11286 } else { 11287 TypeStr += ", "; 11288 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11289 TypeStr += ")"; 11290 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11291 } 11292 } 11293 11294 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11295 OverloadCandidate *Cand) { 11296 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11297 if (ICS.isBad()) break; // all meaningless after first invalid 11298 if (!ICS.isAmbiguous()) continue; 11299 11300 ICS.DiagnoseAmbiguousConversion( 11301 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11302 } 11303 } 11304 11305 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11306 if (Cand->Function) 11307 return Cand->Function->getLocation(); 11308 if (Cand->IsSurrogate) 11309 return Cand->Surrogate->getLocation(); 11310 return SourceLocation(); 11311 } 11312 11313 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11314 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11315 case Sema::TDK_Success: 11316 case Sema::TDK_NonDependentConversionFailure: 11317 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11318 11319 case Sema::TDK_Invalid: 11320 case Sema::TDK_Incomplete: 11321 case Sema::TDK_IncompletePack: 11322 return 1; 11323 11324 case Sema::TDK_Underqualified: 11325 case Sema::TDK_Inconsistent: 11326 return 2; 11327 11328 case Sema::TDK_SubstitutionFailure: 11329 case Sema::TDK_DeducedMismatch: 11330 case Sema::TDK_ConstraintsNotSatisfied: 11331 case Sema::TDK_DeducedMismatchNested: 11332 case Sema::TDK_NonDeducedMismatch: 11333 case Sema::TDK_MiscellaneousDeductionFailure: 11334 case Sema::TDK_CUDATargetMismatch: 11335 return 3; 11336 11337 case Sema::TDK_InstantiationDepth: 11338 return 4; 11339 11340 case Sema::TDK_InvalidExplicitArguments: 11341 return 5; 11342 11343 case Sema::TDK_TooManyArguments: 11344 case Sema::TDK_TooFewArguments: 11345 return 6; 11346 } 11347 llvm_unreachable("Unhandled deduction result"); 11348 } 11349 11350 namespace { 11351 struct CompareOverloadCandidatesForDisplay { 11352 Sema &S; 11353 SourceLocation Loc; 11354 size_t NumArgs; 11355 OverloadCandidateSet::CandidateSetKind CSK; 11356 11357 CompareOverloadCandidatesForDisplay( 11358 Sema &S, SourceLocation Loc, size_t NArgs, 11359 OverloadCandidateSet::CandidateSetKind CSK) 11360 : S(S), NumArgs(NArgs), CSK(CSK) {} 11361 11362 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11363 // If there are too many or too few arguments, that's the high-order bit we 11364 // want to sort by, even if the immediate failure kind was something else. 11365 if (C->FailureKind == ovl_fail_too_many_arguments || 11366 C->FailureKind == ovl_fail_too_few_arguments) 11367 return static_cast<OverloadFailureKind>(C->FailureKind); 11368 11369 if (C->Function) { 11370 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11371 return ovl_fail_too_many_arguments; 11372 if (NumArgs < C->Function->getMinRequiredArguments()) 11373 return ovl_fail_too_few_arguments; 11374 } 11375 11376 return static_cast<OverloadFailureKind>(C->FailureKind); 11377 } 11378 11379 bool operator()(const OverloadCandidate *L, 11380 const OverloadCandidate *R) { 11381 // Fast-path this check. 11382 if (L == R) return false; 11383 11384 // Order first by viability. 11385 if (L->Viable) { 11386 if (!R->Viable) return true; 11387 11388 // TODO: introduce a tri-valued comparison for overload 11389 // candidates. Would be more worthwhile if we had a sort 11390 // that could exploit it. 11391 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11392 return true; 11393 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11394 return false; 11395 } else if (R->Viable) 11396 return false; 11397 11398 assert(L->Viable == R->Viable); 11399 11400 // Criteria by which we can sort non-viable candidates: 11401 if (!L->Viable) { 11402 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11403 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11404 11405 // 1. Arity mismatches come after other candidates. 11406 if (LFailureKind == ovl_fail_too_many_arguments || 11407 LFailureKind == ovl_fail_too_few_arguments) { 11408 if (RFailureKind == ovl_fail_too_many_arguments || 11409 RFailureKind == ovl_fail_too_few_arguments) { 11410 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11411 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11412 if (LDist == RDist) { 11413 if (LFailureKind == RFailureKind) 11414 // Sort non-surrogates before surrogates. 11415 return !L->IsSurrogate && R->IsSurrogate; 11416 // Sort candidates requiring fewer parameters than there were 11417 // arguments given after candidates requiring more parameters 11418 // than there were arguments given. 11419 return LFailureKind == ovl_fail_too_many_arguments; 11420 } 11421 return LDist < RDist; 11422 } 11423 return false; 11424 } 11425 if (RFailureKind == ovl_fail_too_many_arguments || 11426 RFailureKind == ovl_fail_too_few_arguments) 11427 return true; 11428 11429 // 2. Bad conversions come first and are ordered by the number 11430 // of bad conversions and quality of good conversions. 11431 if (LFailureKind == ovl_fail_bad_conversion) { 11432 if (RFailureKind != ovl_fail_bad_conversion) 11433 return true; 11434 11435 // The conversion that can be fixed with a smaller number of changes, 11436 // comes first. 11437 unsigned numLFixes = L->Fix.NumConversionsFixed; 11438 unsigned numRFixes = R->Fix.NumConversionsFixed; 11439 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11440 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11441 if (numLFixes != numRFixes) { 11442 return numLFixes < numRFixes; 11443 } 11444 11445 // If there's any ordering between the defined conversions... 11446 // FIXME: this might not be transitive. 11447 assert(L->Conversions.size() == R->Conversions.size()); 11448 11449 int leftBetter = 0; 11450 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11451 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11452 switch (CompareImplicitConversionSequences(S, Loc, 11453 L->Conversions[I], 11454 R->Conversions[I])) { 11455 case ImplicitConversionSequence::Better: 11456 leftBetter++; 11457 break; 11458 11459 case ImplicitConversionSequence::Worse: 11460 leftBetter--; 11461 break; 11462 11463 case ImplicitConversionSequence::Indistinguishable: 11464 break; 11465 } 11466 } 11467 if (leftBetter > 0) return true; 11468 if (leftBetter < 0) return false; 11469 11470 } else if (RFailureKind == ovl_fail_bad_conversion) 11471 return false; 11472 11473 if (LFailureKind == ovl_fail_bad_deduction) { 11474 if (RFailureKind != ovl_fail_bad_deduction) 11475 return true; 11476 11477 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11478 return RankDeductionFailure(L->DeductionFailure) 11479 < RankDeductionFailure(R->DeductionFailure); 11480 } else if (RFailureKind == ovl_fail_bad_deduction) 11481 return false; 11482 11483 // TODO: others? 11484 } 11485 11486 // Sort everything else by location. 11487 SourceLocation LLoc = GetLocationForCandidate(L); 11488 SourceLocation RLoc = GetLocationForCandidate(R); 11489 11490 // Put candidates without locations (e.g. builtins) at the end. 11491 if (LLoc.isInvalid()) return false; 11492 if (RLoc.isInvalid()) return true; 11493 11494 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11495 } 11496 }; 11497 } 11498 11499 /// CompleteNonViableCandidate - Normally, overload resolution only 11500 /// computes up to the first bad conversion. Produces the FixIt set if 11501 /// possible. 11502 static void 11503 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11504 ArrayRef<Expr *> Args, 11505 OverloadCandidateSet::CandidateSetKind CSK) { 11506 assert(!Cand->Viable); 11507 11508 // Don't do anything on failures other than bad conversion. 11509 if (Cand->FailureKind != ovl_fail_bad_conversion) 11510 return; 11511 11512 // We only want the FixIts if all the arguments can be corrected. 11513 bool Unfixable = false; 11514 // Use a implicit copy initialization to check conversion fixes. 11515 Cand->Fix.setConversionChecker(TryCopyInitialization); 11516 11517 // Attempt to fix the bad conversion. 11518 unsigned ConvCount = Cand->Conversions.size(); 11519 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11520 ++ConvIdx) { 11521 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11522 if (Cand->Conversions[ConvIdx].isInitialized() && 11523 Cand->Conversions[ConvIdx].isBad()) { 11524 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11525 break; 11526 } 11527 } 11528 11529 // FIXME: this should probably be preserved from the overload 11530 // operation somehow. 11531 bool SuppressUserConversions = false; 11532 11533 unsigned ConvIdx = 0; 11534 unsigned ArgIdx = 0; 11535 ArrayRef<QualType> ParamTypes; 11536 bool Reversed = Cand->isReversed(); 11537 11538 if (Cand->IsSurrogate) { 11539 QualType ConvType 11540 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11541 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11542 ConvType = ConvPtrType->getPointeeType(); 11543 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11544 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11545 ConvIdx = 1; 11546 } else if (Cand->Function) { 11547 ParamTypes = 11548 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11549 if (isa<CXXMethodDecl>(Cand->Function) && 11550 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11551 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11552 ConvIdx = 1; 11553 if (CSK == OverloadCandidateSet::CSK_Operator && 11554 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11555 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11556 ArgIdx = 1; 11557 } 11558 } else { 11559 // Builtin operator. 11560 assert(ConvCount <= 3); 11561 ParamTypes = Cand->BuiltinParamTypes; 11562 } 11563 11564 // Fill in the rest of the conversions. 11565 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11566 ConvIdx != ConvCount; 11567 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11568 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11569 if (Cand->Conversions[ConvIdx].isInitialized()) { 11570 // We've already checked this conversion. 11571 } else if (ParamIdx < ParamTypes.size()) { 11572 if (ParamTypes[ParamIdx]->isDependentType()) 11573 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11574 Args[ArgIdx]->getType()); 11575 else { 11576 Cand->Conversions[ConvIdx] = 11577 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11578 SuppressUserConversions, 11579 /*InOverloadResolution=*/true, 11580 /*AllowObjCWritebackConversion=*/ 11581 S.getLangOpts().ObjCAutoRefCount); 11582 // Store the FixIt in the candidate if it exists. 11583 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11584 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11585 } 11586 } else 11587 Cand->Conversions[ConvIdx].setEllipsis(); 11588 } 11589 } 11590 11591 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11592 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11593 SourceLocation OpLoc, 11594 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11595 // Sort the candidates by viability and position. Sorting directly would 11596 // be prohibitive, so we make a set of pointers and sort those. 11597 SmallVector<OverloadCandidate*, 32> Cands; 11598 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11599 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11600 if (!Filter(*Cand)) 11601 continue; 11602 switch (OCD) { 11603 case OCD_AllCandidates: 11604 if (!Cand->Viable) { 11605 if (!Cand->Function && !Cand->IsSurrogate) { 11606 // This a non-viable builtin candidate. We do not, in general, 11607 // want to list every possible builtin candidate. 11608 continue; 11609 } 11610 CompleteNonViableCandidate(S, Cand, Args, Kind); 11611 } 11612 break; 11613 11614 case OCD_ViableCandidates: 11615 if (!Cand->Viable) 11616 continue; 11617 break; 11618 11619 case OCD_AmbiguousCandidates: 11620 if (!Cand->Best) 11621 continue; 11622 break; 11623 } 11624 11625 Cands.push_back(Cand); 11626 } 11627 11628 llvm::stable_sort( 11629 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11630 11631 return Cands; 11632 } 11633 11634 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11635 SourceLocation OpLoc) { 11636 bool DeferHint = false; 11637 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11638 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11639 // host device candidates. 11640 auto WrongSidedCands = 11641 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11642 return (Cand.Viable == false && 11643 Cand.FailureKind == ovl_fail_bad_target) || 11644 (Cand.Function->template hasAttr<CUDAHostAttr>() && 11645 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11646 }); 11647 DeferHint = !WrongSidedCands.empty(); 11648 } 11649 return DeferHint; 11650 } 11651 11652 /// When overload resolution fails, prints diagnostic messages containing the 11653 /// candidates in the candidate set. 11654 void OverloadCandidateSet::NoteCandidates( 11655 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11656 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11657 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11658 11659 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11660 11661 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11662 11663 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11664 11665 if (OCD == OCD_AmbiguousCandidates) 11666 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11667 } 11668 11669 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11670 ArrayRef<OverloadCandidate *> Cands, 11671 StringRef Opc, SourceLocation OpLoc) { 11672 bool ReportedAmbiguousConversions = false; 11673 11674 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11675 unsigned CandsShown = 0; 11676 auto I = Cands.begin(), E = Cands.end(); 11677 for (; I != E; ++I) { 11678 OverloadCandidate *Cand = *I; 11679 11680 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11681 ShowOverloads == Ovl_Best) { 11682 break; 11683 } 11684 ++CandsShown; 11685 11686 if (Cand->Function) 11687 NoteFunctionCandidate(S, Cand, Args.size(), 11688 /*TakingCandidateAddress=*/false, DestAS); 11689 else if (Cand->IsSurrogate) 11690 NoteSurrogateCandidate(S, Cand); 11691 else { 11692 assert(Cand->Viable && 11693 "Non-viable built-in candidates are not added to Cands."); 11694 // Generally we only see ambiguities including viable builtin 11695 // operators if overload resolution got screwed up by an 11696 // ambiguous user-defined conversion. 11697 // 11698 // FIXME: It's quite possible for different conversions to see 11699 // different ambiguities, though. 11700 if (!ReportedAmbiguousConversions) { 11701 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11702 ReportedAmbiguousConversions = true; 11703 } 11704 11705 // If this is a viable builtin, print it. 11706 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11707 } 11708 } 11709 11710 // Inform S.Diags that we've shown an overload set with N elements. This may 11711 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11712 S.Diags.overloadCandidatesShown(CandsShown); 11713 11714 if (I != E) 11715 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11716 shouldDeferDiags(S, Args, OpLoc)) 11717 << int(E - I); 11718 } 11719 11720 static SourceLocation 11721 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11722 return Cand->Specialization ? Cand->Specialization->getLocation() 11723 : SourceLocation(); 11724 } 11725 11726 namespace { 11727 struct CompareTemplateSpecCandidatesForDisplay { 11728 Sema &S; 11729 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11730 11731 bool operator()(const TemplateSpecCandidate *L, 11732 const TemplateSpecCandidate *R) { 11733 // Fast-path this check. 11734 if (L == R) 11735 return false; 11736 11737 // Assuming that both candidates are not matches... 11738 11739 // Sort by the ranking of deduction failures. 11740 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11741 return RankDeductionFailure(L->DeductionFailure) < 11742 RankDeductionFailure(R->DeductionFailure); 11743 11744 // Sort everything else by location. 11745 SourceLocation LLoc = GetLocationForCandidate(L); 11746 SourceLocation RLoc = GetLocationForCandidate(R); 11747 11748 // Put candidates without locations (e.g. builtins) at the end. 11749 if (LLoc.isInvalid()) 11750 return false; 11751 if (RLoc.isInvalid()) 11752 return true; 11753 11754 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11755 } 11756 }; 11757 } 11758 11759 /// Diagnose a template argument deduction failure. 11760 /// We are treating these failures as overload failures due to bad 11761 /// deductions. 11762 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11763 bool ForTakingAddress) { 11764 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11765 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11766 } 11767 11768 void TemplateSpecCandidateSet::destroyCandidates() { 11769 for (iterator i = begin(), e = end(); i != e; ++i) { 11770 i->DeductionFailure.Destroy(); 11771 } 11772 } 11773 11774 void TemplateSpecCandidateSet::clear() { 11775 destroyCandidates(); 11776 Candidates.clear(); 11777 } 11778 11779 /// NoteCandidates - When no template specialization match is found, prints 11780 /// diagnostic messages containing the non-matching specializations that form 11781 /// the candidate set. 11782 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11783 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11784 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11785 // Sort the candidates by position (assuming no candidate is a match). 11786 // Sorting directly would be prohibitive, so we make a set of pointers 11787 // and sort those. 11788 SmallVector<TemplateSpecCandidate *, 32> Cands; 11789 Cands.reserve(size()); 11790 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11791 if (Cand->Specialization) 11792 Cands.push_back(Cand); 11793 // Otherwise, this is a non-matching builtin candidate. We do not, 11794 // in general, want to list every possible builtin candidate. 11795 } 11796 11797 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11798 11799 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11800 // for generalization purposes (?). 11801 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11802 11803 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11804 unsigned CandsShown = 0; 11805 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11806 TemplateSpecCandidate *Cand = *I; 11807 11808 // Set an arbitrary limit on the number of candidates we'll spam 11809 // the user with. FIXME: This limit should depend on details of the 11810 // candidate list. 11811 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11812 break; 11813 ++CandsShown; 11814 11815 assert(Cand->Specialization && 11816 "Non-matching built-in candidates are not added to Cands."); 11817 Cand->NoteDeductionFailure(S, ForTakingAddress); 11818 } 11819 11820 if (I != E) 11821 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11822 } 11823 11824 // [PossiblyAFunctionType] --> [Return] 11825 // NonFunctionType --> NonFunctionType 11826 // R (A) --> R(A) 11827 // R (*)(A) --> R (A) 11828 // R (&)(A) --> R (A) 11829 // R (S::*)(A) --> R (A) 11830 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11831 QualType Ret = PossiblyAFunctionType; 11832 if (const PointerType *ToTypePtr = 11833 PossiblyAFunctionType->getAs<PointerType>()) 11834 Ret = ToTypePtr->getPointeeType(); 11835 else if (const ReferenceType *ToTypeRef = 11836 PossiblyAFunctionType->getAs<ReferenceType>()) 11837 Ret = ToTypeRef->getPointeeType(); 11838 else if (const MemberPointerType *MemTypePtr = 11839 PossiblyAFunctionType->getAs<MemberPointerType>()) 11840 Ret = MemTypePtr->getPointeeType(); 11841 Ret = 11842 Context.getCanonicalType(Ret).getUnqualifiedType(); 11843 return Ret; 11844 } 11845 11846 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11847 bool Complain = true) { 11848 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11849 S.DeduceReturnType(FD, Loc, Complain)) 11850 return true; 11851 11852 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11853 if (S.getLangOpts().CPlusPlus17 && 11854 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11855 !S.ResolveExceptionSpec(Loc, FPT)) 11856 return true; 11857 11858 return false; 11859 } 11860 11861 namespace { 11862 // A helper class to help with address of function resolution 11863 // - allows us to avoid passing around all those ugly parameters 11864 class AddressOfFunctionResolver { 11865 Sema& S; 11866 Expr* SourceExpr; 11867 const QualType& TargetType; 11868 QualType TargetFunctionType; // Extracted function type from target type 11869 11870 bool Complain; 11871 //DeclAccessPair& ResultFunctionAccessPair; 11872 ASTContext& Context; 11873 11874 bool TargetTypeIsNonStaticMemberFunction; 11875 bool FoundNonTemplateFunction; 11876 bool StaticMemberFunctionFromBoundPointer; 11877 bool HasComplained; 11878 11879 OverloadExpr::FindResult OvlExprInfo; 11880 OverloadExpr *OvlExpr; 11881 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11882 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11883 TemplateSpecCandidateSet FailedCandidates; 11884 11885 public: 11886 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11887 const QualType &TargetType, bool Complain) 11888 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11889 Complain(Complain), Context(S.getASTContext()), 11890 TargetTypeIsNonStaticMemberFunction( 11891 !!TargetType->getAs<MemberPointerType>()), 11892 FoundNonTemplateFunction(false), 11893 StaticMemberFunctionFromBoundPointer(false), 11894 HasComplained(false), 11895 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11896 OvlExpr(OvlExprInfo.Expression), 11897 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11898 ExtractUnqualifiedFunctionTypeFromTargetType(); 11899 11900 if (TargetFunctionType->isFunctionType()) { 11901 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11902 if (!UME->isImplicitAccess() && 11903 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11904 StaticMemberFunctionFromBoundPointer = true; 11905 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11906 DeclAccessPair dap; 11907 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11908 OvlExpr, false, &dap)) { 11909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11910 if (!Method->isStatic()) { 11911 // If the target type is a non-function type and the function found 11912 // is a non-static member function, pretend as if that was the 11913 // target, it's the only possible type to end up with. 11914 TargetTypeIsNonStaticMemberFunction = true; 11915 11916 // And skip adding the function if its not in the proper form. 11917 // We'll diagnose this due to an empty set of functions. 11918 if (!OvlExprInfo.HasFormOfMemberPointer) 11919 return; 11920 } 11921 11922 Matches.push_back(std::make_pair(dap, Fn)); 11923 } 11924 return; 11925 } 11926 11927 if (OvlExpr->hasExplicitTemplateArgs()) 11928 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11929 11930 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11931 // C++ [over.over]p4: 11932 // If more than one function is selected, [...] 11933 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11934 if (FoundNonTemplateFunction) 11935 EliminateAllTemplateMatches(); 11936 else 11937 EliminateAllExceptMostSpecializedTemplate(); 11938 } 11939 } 11940 11941 if (S.getLangOpts().CUDA && Matches.size() > 1) 11942 EliminateSuboptimalCudaMatches(); 11943 } 11944 11945 bool hasComplained() const { return HasComplained; } 11946 11947 private: 11948 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11949 QualType Discard; 11950 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11951 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11952 } 11953 11954 /// \return true if A is considered a better overload candidate for the 11955 /// desired type than B. 11956 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11957 // If A doesn't have exactly the correct type, we don't want to classify it 11958 // as "better" than anything else. This way, the user is required to 11959 // disambiguate for us if there are multiple candidates and no exact match. 11960 return candidateHasExactlyCorrectType(A) && 11961 (!candidateHasExactlyCorrectType(B) || 11962 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11963 } 11964 11965 /// \return true if we were able to eliminate all but one overload candidate, 11966 /// false otherwise. 11967 bool eliminiateSuboptimalOverloadCandidates() { 11968 // Same algorithm as overload resolution -- one pass to pick the "best", 11969 // another pass to be sure that nothing is better than the best. 11970 auto Best = Matches.begin(); 11971 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11972 if (isBetterCandidate(I->second, Best->second)) 11973 Best = I; 11974 11975 const FunctionDecl *BestFn = Best->second; 11976 auto IsBestOrInferiorToBest = [this, BestFn]( 11977 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11978 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11979 }; 11980 11981 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11982 // option, so we can potentially give the user a better error 11983 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11984 return false; 11985 Matches[0] = *Best; 11986 Matches.resize(1); 11987 return true; 11988 } 11989 11990 bool isTargetTypeAFunction() const { 11991 return TargetFunctionType->isFunctionType(); 11992 } 11993 11994 // [ToType] [Return] 11995 11996 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11997 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11998 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11999 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12000 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12001 } 12002 12003 // return true if any matching specializations were found 12004 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12005 const DeclAccessPair& CurAccessFunPair) { 12006 if (CXXMethodDecl *Method 12007 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12008 // Skip non-static function templates when converting to pointer, and 12009 // static when converting to member pointer. 12010 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12011 return false; 12012 } 12013 else if (TargetTypeIsNonStaticMemberFunction) 12014 return false; 12015 12016 // C++ [over.over]p2: 12017 // If the name is a function template, template argument deduction is 12018 // done (14.8.2.2), and if the argument deduction succeeds, the 12019 // resulting template argument list is used to generate a single 12020 // function template specialization, which is added to the set of 12021 // overloaded functions considered. 12022 FunctionDecl *Specialization = nullptr; 12023 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12024 if (Sema::TemplateDeductionResult Result 12025 = S.DeduceTemplateArguments(FunctionTemplate, 12026 &OvlExplicitTemplateArgs, 12027 TargetFunctionType, Specialization, 12028 Info, /*IsAddressOfFunction*/true)) { 12029 // Make a note of the failed deduction for diagnostics. 12030 FailedCandidates.addCandidate() 12031 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12032 MakeDeductionFailureInfo(Context, Result, Info)); 12033 return false; 12034 } 12035 12036 // Template argument deduction ensures that we have an exact match or 12037 // compatible pointer-to-function arguments that would be adjusted by ICS. 12038 // This function template specicalization works. 12039 assert(S.isSameOrCompatibleFunctionType( 12040 Context.getCanonicalType(Specialization->getType()), 12041 Context.getCanonicalType(TargetFunctionType))); 12042 12043 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12044 return false; 12045 12046 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12047 return true; 12048 } 12049 12050 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12051 const DeclAccessPair& CurAccessFunPair) { 12052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12053 // Skip non-static functions when converting to pointer, and static 12054 // when converting to member pointer. 12055 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12056 return false; 12057 } 12058 else if (TargetTypeIsNonStaticMemberFunction) 12059 return false; 12060 12061 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12062 if (S.getLangOpts().CUDA) 12063 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12064 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12065 return false; 12066 if (FunDecl->isMultiVersion()) { 12067 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12068 if (TA && !TA->isDefaultVersion()) 12069 return false; 12070 } 12071 12072 // If any candidate has a placeholder return type, trigger its deduction 12073 // now. 12074 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12075 Complain)) { 12076 HasComplained |= Complain; 12077 return false; 12078 } 12079 12080 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12081 return false; 12082 12083 // If we're in C, we need to support types that aren't exactly identical. 12084 if (!S.getLangOpts().CPlusPlus || 12085 candidateHasExactlyCorrectType(FunDecl)) { 12086 Matches.push_back(std::make_pair( 12087 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12088 FoundNonTemplateFunction = true; 12089 return true; 12090 } 12091 } 12092 12093 return false; 12094 } 12095 12096 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12097 bool Ret = false; 12098 12099 // If the overload expression doesn't have the form of a pointer to 12100 // member, don't try to convert it to a pointer-to-member type. 12101 if (IsInvalidFormOfPointerToMemberFunction()) 12102 return false; 12103 12104 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12105 E = OvlExpr->decls_end(); 12106 I != E; ++I) { 12107 // Look through any using declarations to find the underlying function. 12108 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12109 12110 // C++ [over.over]p3: 12111 // Non-member functions and static member functions match 12112 // targets of type "pointer-to-function" or "reference-to-function." 12113 // Nonstatic member functions match targets of 12114 // type "pointer-to-member-function." 12115 // Note that according to DR 247, the containing class does not matter. 12116 if (FunctionTemplateDecl *FunctionTemplate 12117 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12118 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12119 Ret = true; 12120 } 12121 // If we have explicit template arguments supplied, skip non-templates. 12122 else if (!OvlExpr->hasExplicitTemplateArgs() && 12123 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12124 Ret = true; 12125 } 12126 assert(Ret || Matches.empty()); 12127 return Ret; 12128 } 12129 12130 void EliminateAllExceptMostSpecializedTemplate() { 12131 // [...] and any given function template specialization F1 is 12132 // eliminated if the set contains a second function template 12133 // specialization whose function template is more specialized 12134 // than the function template of F1 according to the partial 12135 // ordering rules of 14.5.5.2. 12136 12137 // The algorithm specified above is quadratic. We instead use a 12138 // two-pass algorithm (similar to the one used to identify the 12139 // best viable function in an overload set) that identifies the 12140 // best function template (if it exists). 12141 12142 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12143 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12144 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12145 12146 // TODO: It looks like FailedCandidates does not serve much purpose 12147 // here, since the no_viable diagnostic has index 0. 12148 UnresolvedSetIterator Result = S.getMostSpecialized( 12149 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12150 SourceExpr->getBeginLoc(), S.PDiag(), 12151 S.PDiag(diag::err_addr_ovl_ambiguous) 12152 << Matches[0].second->getDeclName(), 12153 S.PDiag(diag::note_ovl_candidate) 12154 << (unsigned)oc_function << (unsigned)ocs_described_template, 12155 Complain, TargetFunctionType); 12156 12157 if (Result != MatchesCopy.end()) { 12158 // Make it the first and only element 12159 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12160 Matches[0].second = cast<FunctionDecl>(*Result); 12161 Matches.resize(1); 12162 } else 12163 HasComplained |= Complain; 12164 } 12165 12166 void EliminateAllTemplateMatches() { 12167 // [...] any function template specializations in the set are 12168 // eliminated if the set also contains a non-template function, [...] 12169 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12170 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12171 ++I; 12172 else { 12173 Matches[I] = Matches[--N]; 12174 Matches.resize(N); 12175 } 12176 } 12177 } 12178 12179 void EliminateSuboptimalCudaMatches() { 12180 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12181 } 12182 12183 public: 12184 void ComplainNoMatchesFound() const { 12185 assert(Matches.empty()); 12186 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12187 << OvlExpr->getName() << TargetFunctionType 12188 << OvlExpr->getSourceRange(); 12189 if (FailedCandidates.empty()) 12190 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12191 /*TakingAddress=*/true); 12192 else { 12193 // We have some deduction failure messages. Use them to diagnose 12194 // the function templates, and diagnose the non-template candidates 12195 // normally. 12196 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12197 IEnd = OvlExpr->decls_end(); 12198 I != IEnd; ++I) 12199 if (FunctionDecl *Fun = 12200 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12201 if (!functionHasPassObjectSizeParams(Fun)) 12202 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12203 /*TakingAddress=*/true); 12204 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12205 } 12206 } 12207 12208 bool IsInvalidFormOfPointerToMemberFunction() const { 12209 return TargetTypeIsNonStaticMemberFunction && 12210 !OvlExprInfo.HasFormOfMemberPointer; 12211 } 12212 12213 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12214 // TODO: Should we condition this on whether any functions might 12215 // have matched, or is it more appropriate to do that in callers? 12216 // TODO: a fixit wouldn't hurt. 12217 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12218 << TargetType << OvlExpr->getSourceRange(); 12219 } 12220 12221 bool IsStaticMemberFunctionFromBoundPointer() const { 12222 return StaticMemberFunctionFromBoundPointer; 12223 } 12224 12225 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12226 S.Diag(OvlExpr->getBeginLoc(), 12227 diag::err_invalid_form_pointer_member_function) 12228 << OvlExpr->getSourceRange(); 12229 } 12230 12231 void ComplainOfInvalidConversion() const { 12232 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12233 << OvlExpr->getName() << TargetType; 12234 } 12235 12236 void ComplainMultipleMatchesFound() const { 12237 assert(Matches.size() > 1); 12238 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12239 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12240 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12241 /*TakingAddress=*/true); 12242 } 12243 12244 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12245 12246 int getNumMatches() const { return Matches.size(); } 12247 12248 FunctionDecl* getMatchingFunctionDecl() const { 12249 if (Matches.size() != 1) return nullptr; 12250 return Matches[0].second; 12251 } 12252 12253 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12254 if (Matches.size() != 1) return nullptr; 12255 return &Matches[0].first; 12256 } 12257 }; 12258 } 12259 12260 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12261 /// an overloaded function (C++ [over.over]), where @p From is an 12262 /// expression with overloaded function type and @p ToType is the type 12263 /// we're trying to resolve to. For example: 12264 /// 12265 /// @code 12266 /// int f(double); 12267 /// int f(int); 12268 /// 12269 /// int (*pfd)(double) = f; // selects f(double) 12270 /// @endcode 12271 /// 12272 /// This routine returns the resulting FunctionDecl if it could be 12273 /// resolved, and NULL otherwise. When @p Complain is true, this 12274 /// routine will emit diagnostics if there is an error. 12275 FunctionDecl * 12276 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12277 QualType TargetType, 12278 bool Complain, 12279 DeclAccessPair &FoundResult, 12280 bool *pHadMultipleCandidates) { 12281 assert(AddressOfExpr->getType() == Context.OverloadTy); 12282 12283 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12284 Complain); 12285 int NumMatches = Resolver.getNumMatches(); 12286 FunctionDecl *Fn = nullptr; 12287 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12288 if (NumMatches == 0 && ShouldComplain) { 12289 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12290 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12291 else 12292 Resolver.ComplainNoMatchesFound(); 12293 } 12294 else if (NumMatches > 1 && ShouldComplain) 12295 Resolver.ComplainMultipleMatchesFound(); 12296 else if (NumMatches == 1) { 12297 Fn = Resolver.getMatchingFunctionDecl(); 12298 assert(Fn); 12299 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12300 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12301 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12302 if (Complain) { 12303 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12304 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12305 else 12306 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12307 } 12308 } 12309 12310 if (pHadMultipleCandidates) 12311 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12312 return Fn; 12313 } 12314 12315 /// Given an expression that refers to an overloaded function, try to 12316 /// resolve that function to a single function that can have its address taken. 12317 /// This will modify `Pair` iff it returns non-null. 12318 /// 12319 /// This routine can only succeed if from all of the candidates in the overload 12320 /// set for SrcExpr that can have their addresses taken, there is one candidate 12321 /// that is more constrained than the rest. 12322 FunctionDecl * 12323 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12324 OverloadExpr::FindResult R = OverloadExpr::find(E); 12325 OverloadExpr *Ovl = R.Expression; 12326 bool IsResultAmbiguous = false; 12327 FunctionDecl *Result = nullptr; 12328 DeclAccessPair DAP; 12329 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12330 12331 auto CheckMoreConstrained = 12332 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12333 SmallVector<const Expr *, 1> AC1, AC2; 12334 FD1->getAssociatedConstraints(AC1); 12335 FD2->getAssociatedConstraints(AC2); 12336 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12337 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12338 return None; 12339 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12340 return None; 12341 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12342 return None; 12343 return AtLeastAsConstrained1; 12344 }; 12345 12346 // Don't use the AddressOfResolver because we're specifically looking for 12347 // cases where we have one overload candidate that lacks 12348 // enable_if/pass_object_size/... 12349 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12350 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12351 if (!FD) 12352 return nullptr; 12353 12354 if (!checkAddressOfFunctionIsAvailable(FD)) 12355 continue; 12356 12357 // We have more than one result - see if it is more constrained than the 12358 // previous one. 12359 if (Result) { 12360 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12361 Result); 12362 if (!MoreConstrainedThanPrevious) { 12363 IsResultAmbiguous = true; 12364 AmbiguousDecls.push_back(FD); 12365 continue; 12366 } 12367 if (!*MoreConstrainedThanPrevious) 12368 continue; 12369 // FD is more constrained - replace Result with it. 12370 } 12371 IsResultAmbiguous = false; 12372 DAP = I.getPair(); 12373 Result = FD; 12374 } 12375 12376 if (IsResultAmbiguous) 12377 return nullptr; 12378 12379 if (Result) { 12380 SmallVector<const Expr *, 1> ResultAC; 12381 // We skipped over some ambiguous declarations which might be ambiguous with 12382 // the selected result. 12383 for (FunctionDecl *Skipped : AmbiguousDecls) 12384 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12385 return nullptr; 12386 Pair = DAP; 12387 } 12388 return Result; 12389 } 12390 12391 /// Given an overloaded function, tries to turn it into a non-overloaded 12392 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12393 /// will perform access checks, diagnose the use of the resultant decl, and, if 12394 /// requested, potentially perform a function-to-pointer decay. 12395 /// 12396 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12397 /// Otherwise, returns true. This may emit diagnostics and return true. 12398 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12399 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12400 Expr *E = SrcExpr.get(); 12401 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12402 12403 DeclAccessPair DAP; 12404 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12405 if (!Found || Found->isCPUDispatchMultiVersion() || 12406 Found->isCPUSpecificMultiVersion()) 12407 return false; 12408 12409 // Emitting multiple diagnostics for a function that is both inaccessible and 12410 // unavailable is consistent with our behavior elsewhere. So, always check 12411 // for both. 12412 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12413 CheckAddressOfMemberAccess(E, DAP); 12414 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12415 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12416 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12417 else 12418 SrcExpr = Fixed; 12419 return true; 12420 } 12421 12422 /// Given an expression that refers to an overloaded function, try to 12423 /// resolve that overloaded function expression down to a single function. 12424 /// 12425 /// This routine can only resolve template-ids that refer to a single function 12426 /// template, where that template-id refers to a single template whose template 12427 /// arguments are either provided by the template-id or have defaults, 12428 /// as described in C++0x [temp.arg.explicit]p3. 12429 /// 12430 /// If no template-ids are found, no diagnostics are emitted and NULL is 12431 /// returned. 12432 FunctionDecl * 12433 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12434 bool Complain, 12435 DeclAccessPair *FoundResult) { 12436 // C++ [over.over]p1: 12437 // [...] [Note: any redundant set of parentheses surrounding the 12438 // overloaded function name is ignored (5.1). ] 12439 // C++ [over.over]p1: 12440 // [...] The overloaded function name can be preceded by the & 12441 // operator. 12442 12443 // If we didn't actually find any template-ids, we're done. 12444 if (!ovl->hasExplicitTemplateArgs()) 12445 return nullptr; 12446 12447 TemplateArgumentListInfo ExplicitTemplateArgs; 12448 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12449 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12450 12451 // Look through all of the overloaded functions, searching for one 12452 // whose type matches exactly. 12453 FunctionDecl *Matched = nullptr; 12454 for (UnresolvedSetIterator I = ovl->decls_begin(), 12455 E = ovl->decls_end(); I != E; ++I) { 12456 // C++0x [temp.arg.explicit]p3: 12457 // [...] In contexts where deduction is done and fails, or in contexts 12458 // where deduction is not done, if a template argument list is 12459 // specified and it, along with any default template arguments, 12460 // identifies a single function template specialization, then the 12461 // template-id is an lvalue for the function template specialization. 12462 FunctionTemplateDecl *FunctionTemplate 12463 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12464 12465 // C++ [over.over]p2: 12466 // If the name is a function template, template argument deduction is 12467 // done (14.8.2.2), and if the argument deduction succeeds, the 12468 // resulting template argument list is used to generate a single 12469 // function template specialization, which is added to the set of 12470 // overloaded functions considered. 12471 FunctionDecl *Specialization = nullptr; 12472 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12473 if (TemplateDeductionResult Result 12474 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12475 Specialization, Info, 12476 /*IsAddressOfFunction*/true)) { 12477 // Make a note of the failed deduction for diagnostics. 12478 // TODO: Actually use the failed-deduction info? 12479 FailedCandidates.addCandidate() 12480 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12481 MakeDeductionFailureInfo(Context, Result, Info)); 12482 continue; 12483 } 12484 12485 assert(Specialization && "no specialization and no error?"); 12486 12487 // Multiple matches; we can't resolve to a single declaration. 12488 if (Matched) { 12489 if (Complain) { 12490 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12491 << ovl->getName(); 12492 NoteAllOverloadCandidates(ovl); 12493 } 12494 return nullptr; 12495 } 12496 12497 Matched = Specialization; 12498 if (FoundResult) *FoundResult = I.getPair(); 12499 } 12500 12501 if (Matched && 12502 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12503 return nullptr; 12504 12505 return Matched; 12506 } 12507 12508 // Resolve and fix an overloaded expression that can be resolved 12509 // because it identifies a single function template specialization. 12510 // 12511 // Last three arguments should only be supplied if Complain = true 12512 // 12513 // Return true if it was logically possible to so resolve the 12514 // expression, regardless of whether or not it succeeded. Always 12515 // returns true if 'complain' is set. 12516 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12517 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12518 bool complain, SourceRange OpRangeForComplaining, 12519 QualType DestTypeForComplaining, 12520 unsigned DiagIDForComplaining) { 12521 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12522 12523 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12524 12525 DeclAccessPair found; 12526 ExprResult SingleFunctionExpression; 12527 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12528 ovl.Expression, /*complain*/ false, &found)) { 12529 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12530 SrcExpr = ExprError(); 12531 return true; 12532 } 12533 12534 // It is only correct to resolve to an instance method if we're 12535 // resolving a form that's permitted to be a pointer to member. 12536 // Otherwise we'll end up making a bound member expression, which 12537 // is illegal in all the contexts we resolve like this. 12538 if (!ovl.HasFormOfMemberPointer && 12539 isa<CXXMethodDecl>(fn) && 12540 cast<CXXMethodDecl>(fn)->isInstance()) { 12541 if (!complain) return false; 12542 12543 Diag(ovl.Expression->getExprLoc(), 12544 diag::err_bound_member_function) 12545 << 0 << ovl.Expression->getSourceRange(); 12546 12547 // TODO: I believe we only end up here if there's a mix of 12548 // static and non-static candidates (otherwise the expression 12549 // would have 'bound member' type, not 'overload' type). 12550 // Ideally we would note which candidate was chosen and why 12551 // the static candidates were rejected. 12552 SrcExpr = ExprError(); 12553 return true; 12554 } 12555 12556 // Fix the expression to refer to 'fn'. 12557 SingleFunctionExpression = 12558 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12559 12560 // If desired, do function-to-pointer decay. 12561 if (doFunctionPointerConverion) { 12562 SingleFunctionExpression = 12563 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12564 if (SingleFunctionExpression.isInvalid()) { 12565 SrcExpr = ExprError(); 12566 return true; 12567 } 12568 } 12569 } 12570 12571 if (!SingleFunctionExpression.isUsable()) { 12572 if (complain) { 12573 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12574 << ovl.Expression->getName() 12575 << DestTypeForComplaining 12576 << OpRangeForComplaining 12577 << ovl.Expression->getQualifierLoc().getSourceRange(); 12578 NoteAllOverloadCandidates(SrcExpr.get()); 12579 12580 SrcExpr = ExprError(); 12581 return true; 12582 } 12583 12584 return false; 12585 } 12586 12587 SrcExpr = SingleFunctionExpression; 12588 return true; 12589 } 12590 12591 /// Add a single candidate to the overload set. 12592 static void AddOverloadedCallCandidate(Sema &S, 12593 DeclAccessPair FoundDecl, 12594 TemplateArgumentListInfo *ExplicitTemplateArgs, 12595 ArrayRef<Expr *> Args, 12596 OverloadCandidateSet &CandidateSet, 12597 bool PartialOverloading, 12598 bool KnownValid) { 12599 NamedDecl *Callee = FoundDecl.getDecl(); 12600 if (isa<UsingShadowDecl>(Callee)) 12601 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12602 12603 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12604 if (ExplicitTemplateArgs) { 12605 assert(!KnownValid && "Explicit template arguments?"); 12606 return; 12607 } 12608 // Prevent ill-formed function decls to be added as overload candidates. 12609 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12610 return; 12611 12612 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12613 /*SuppressUserConversions=*/false, 12614 PartialOverloading); 12615 return; 12616 } 12617 12618 if (FunctionTemplateDecl *FuncTemplate 12619 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12620 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12621 ExplicitTemplateArgs, Args, CandidateSet, 12622 /*SuppressUserConversions=*/false, 12623 PartialOverloading); 12624 return; 12625 } 12626 12627 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12628 } 12629 12630 /// Add the overload candidates named by callee and/or found by argument 12631 /// dependent lookup to the given overload set. 12632 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12633 ArrayRef<Expr *> Args, 12634 OverloadCandidateSet &CandidateSet, 12635 bool PartialOverloading) { 12636 12637 #ifndef NDEBUG 12638 // Verify that ArgumentDependentLookup is consistent with the rules 12639 // in C++0x [basic.lookup.argdep]p3: 12640 // 12641 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12642 // and let Y be the lookup set produced by argument dependent 12643 // lookup (defined as follows). If X contains 12644 // 12645 // -- a declaration of a class member, or 12646 // 12647 // -- a block-scope function declaration that is not a 12648 // using-declaration, or 12649 // 12650 // -- a declaration that is neither a function or a function 12651 // template 12652 // 12653 // then Y is empty. 12654 12655 if (ULE->requiresADL()) { 12656 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12657 E = ULE->decls_end(); I != E; ++I) { 12658 assert(!(*I)->getDeclContext()->isRecord()); 12659 assert(isa<UsingShadowDecl>(*I) || 12660 !(*I)->getDeclContext()->isFunctionOrMethod()); 12661 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12662 } 12663 } 12664 #endif 12665 12666 // It would be nice to avoid this copy. 12667 TemplateArgumentListInfo TABuffer; 12668 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12669 if (ULE->hasExplicitTemplateArgs()) { 12670 ULE->copyTemplateArgumentsInto(TABuffer); 12671 ExplicitTemplateArgs = &TABuffer; 12672 } 12673 12674 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12675 E = ULE->decls_end(); I != E; ++I) 12676 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12677 CandidateSet, PartialOverloading, 12678 /*KnownValid*/ true); 12679 12680 if (ULE->requiresADL()) 12681 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12682 Args, ExplicitTemplateArgs, 12683 CandidateSet, PartialOverloading); 12684 } 12685 12686 /// Add the call candidates from the given set of lookup results to the given 12687 /// overload set. Non-function lookup results are ignored. 12688 void Sema::AddOverloadedCallCandidates( 12689 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12690 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12691 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12692 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12693 CandidateSet, false, /*KnownValid*/ false); 12694 } 12695 12696 /// Determine whether a declaration with the specified name could be moved into 12697 /// a different namespace. 12698 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12699 switch (Name.getCXXOverloadedOperator()) { 12700 case OO_New: case OO_Array_New: 12701 case OO_Delete: case OO_Array_Delete: 12702 return false; 12703 12704 default: 12705 return true; 12706 } 12707 } 12708 12709 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12710 /// template, where the non-dependent name was declared after the template 12711 /// was defined. This is common in code written for a compilers which do not 12712 /// correctly implement two-stage name lookup. 12713 /// 12714 /// Returns true if a viable candidate was found and a diagnostic was issued. 12715 static bool DiagnoseTwoPhaseLookup( 12716 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12717 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12718 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12719 CXXRecordDecl **FoundInClass = nullptr) { 12720 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12721 return false; 12722 12723 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12724 if (DC->isTransparentContext()) 12725 continue; 12726 12727 SemaRef.LookupQualifiedName(R, DC); 12728 12729 if (!R.empty()) { 12730 R.suppressDiagnostics(); 12731 12732 OverloadCandidateSet Candidates(FnLoc, CSK); 12733 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12734 Candidates); 12735 12736 OverloadCandidateSet::iterator Best; 12737 OverloadingResult OR = 12738 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12739 12740 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12741 // We either found non-function declarations or a best viable function 12742 // at class scope. A class-scope lookup result disables ADL. Don't 12743 // look past this, but let the caller know that we found something that 12744 // either is, or might be, usable in this class. 12745 if (FoundInClass) { 12746 *FoundInClass = RD; 12747 if (OR == OR_Success) { 12748 R.clear(); 12749 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12750 R.resolveKind(); 12751 } 12752 } 12753 return false; 12754 } 12755 12756 if (OR != OR_Success) { 12757 // There wasn't a unique best function or function template. 12758 return false; 12759 } 12760 12761 // Find the namespaces where ADL would have looked, and suggest 12762 // declaring the function there instead. 12763 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12764 Sema::AssociatedClassSet AssociatedClasses; 12765 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12766 AssociatedNamespaces, 12767 AssociatedClasses); 12768 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12769 if (canBeDeclaredInNamespace(R.getLookupName())) { 12770 DeclContext *Std = SemaRef.getStdNamespace(); 12771 for (Sema::AssociatedNamespaceSet::iterator 12772 it = AssociatedNamespaces.begin(), 12773 end = AssociatedNamespaces.end(); it != end; ++it) { 12774 // Never suggest declaring a function within namespace 'std'. 12775 if (Std && Std->Encloses(*it)) 12776 continue; 12777 12778 // Never suggest declaring a function within a namespace with a 12779 // reserved name, like __gnu_cxx. 12780 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12781 if (NS && 12782 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12783 continue; 12784 12785 SuggestedNamespaces.insert(*it); 12786 } 12787 } 12788 12789 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12790 << R.getLookupName(); 12791 if (SuggestedNamespaces.empty()) { 12792 SemaRef.Diag(Best->Function->getLocation(), 12793 diag::note_not_found_by_two_phase_lookup) 12794 << R.getLookupName() << 0; 12795 } else if (SuggestedNamespaces.size() == 1) { 12796 SemaRef.Diag(Best->Function->getLocation(), 12797 diag::note_not_found_by_two_phase_lookup) 12798 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12799 } else { 12800 // FIXME: It would be useful to list the associated namespaces here, 12801 // but the diagnostics infrastructure doesn't provide a way to produce 12802 // a localized representation of a list of items. 12803 SemaRef.Diag(Best->Function->getLocation(), 12804 diag::note_not_found_by_two_phase_lookup) 12805 << R.getLookupName() << 2; 12806 } 12807 12808 // Try to recover by calling this function. 12809 return true; 12810 } 12811 12812 R.clear(); 12813 } 12814 12815 return false; 12816 } 12817 12818 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12819 /// template, where the non-dependent operator was declared after the template 12820 /// was defined. 12821 /// 12822 /// Returns true if a viable candidate was found and a diagnostic was issued. 12823 static bool 12824 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12825 SourceLocation OpLoc, 12826 ArrayRef<Expr *> Args) { 12827 DeclarationName OpName = 12828 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12829 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12830 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12831 OverloadCandidateSet::CSK_Operator, 12832 /*ExplicitTemplateArgs=*/nullptr, Args); 12833 } 12834 12835 namespace { 12836 class BuildRecoveryCallExprRAII { 12837 Sema &SemaRef; 12838 public: 12839 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12840 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12841 SemaRef.IsBuildingRecoveryCallExpr = true; 12842 } 12843 12844 ~BuildRecoveryCallExprRAII() { 12845 SemaRef.IsBuildingRecoveryCallExpr = false; 12846 } 12847 }; 12848 12849 } 12850 12851 /// Attempts to recover from a call where no functions were found. 12852 /// 12853 /// This function will do one of three things: 12854 /// * Diagnose, recover, and return a recovery expression. 12855 /// * Diagnose, fail to recover, and return ExprError(). 12856 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 12857 /// expected to diagnose as appropriate. 12858 static ExprResult 12859 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12860 UnresolvedLookupExpr *ULE, 12861 SourceLocation LParenLoc, 12862 MutableArrayRef<Expr *> Args, 12863 SourceLocation RParenLoc, 12864 bool EmptyLookup, bool AllowTypoCorrection) { 12865 // Do not try to recover if it is already building a recovery call. 12866 // This stops infinite loops for template instantiations like 12867 // 12868 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12869 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12870 if (SemaRef.IsBuildingRecoveryCallExpr) 12871 return ExprResult(); 12872 BuildRecoveryCallExprRAII RCE(SemaRef); 12873 12874 CXXScopeSpec SS; 12875 SS.Adopt(ULE->getQualifierLoc()); 12876 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12877 12878 TemplateArgumentListInfo TABuffer; 12879 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12880 if (ULE->hasExplicitTemplateArgs()) { 12881 ULE->copyTemplateArgumentsInto(TABuffer); 12882 ExplicitTemplateArgs = &TABuffer; 12883 } 12884 12885 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12886 Sema::LookupOrdinaryName); 12887 CXXRecordDecl *FoundInClass = nullptr; 12888 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 12889 OverloadCandidateSet::CSK_Normal, 12890 ExplicitTemplateArgs, Args, &FoundInClass)) { 12891 // OK, diagnosed a two-phase lookup issue. 12892 } else if (EmptyLookup) { 12893 // Try to recover from an empty lookup with typo correction. 12894 R.clear(); 12895 NoTypoCorrectionCCC NoTypoValidator{}; 12896 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12897 ExplicitTemplateArgs != nullptr, 12898 dyn_cast<MemberExpr>(Fn)); 12899 CorrectionCandidateCallback &Validator = 12900 AllowTypoCorrection 12901 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12902 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12903 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12904 Args)) 12905 return ExprError(); 12906 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 12907 // We found a usable declaration of the name in a dependent base of some 12908 // enclosing class. 12909 // FIXME: We should also explain why the candidates found by name lookup 12910 // were not viable. 12911 if (SemaRef.DiagnoseDependentMemberLookup(R)) 12912 return ExprError(); 12913 } else { 12914 // We had viable candidates and couldn't recover; let the caller diagnose 12915 // this. 12916 return ExprResult(); 12917 } 12918 12919 // If we get here, we should have issued a diagnostic and formed a recovery 12920 // lookup result. 12921 assert(!R.empty() && "lookup results empty despite recovery"); 12922 12923 // If recovery created an ambiguity, just bail out. 12924 if (R.isAmbiguous()) { 12925 R.suppressDiagnostics(); 12926 return ExprError(); 12927 } 12928 12929 // Build an implicit member call if appropriate. Just drop the 12930 // casts and such from the call, we don't really care. 12931 ExprResult NewFn = ExprError(); 12932 if ((*R.begin())->isCXXClassMember()) 12933 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12934 ExplicitTemplateArgs, S); 12935 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12936 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12937 ExplicitTemplateArgs); 12938 else 12939 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12940 12941 if (NewFn.isInvalid()) 12942 return ExprError(); 12943 12944 // This shouldn't cause an infinite loop because we're giving it 12945 // an expression with viable lookup results, which should never 12946 // end up here. 12947 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12948 MultiExprArg(Args.data(), Args.size()), 12949 RParenLoc); 12950 } 12951 12952 /// Constructs and populates an OverloadedCandidateSet from 12953 /// the given function. 12954 /// \returns true when an the ExprResult output parameter has been set. 12955 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12956 UnresolvedLookupExpr *ULE, 12957 MultiExprArg Args, 12958 SourceLocation RParenLoc, 12959 OverloadCandidateSet *CandidateSet, 12960 ExprResult *Result) { 12961 #ifndef NDEBUG 12962 if (ULE->requiresADL()) { 12963 // To do ADL, we must have found an unqualified name. 12964 assert(!ULE->getQualifier() && "qualified name with ADL"); 12965 12966 // We don't perform ADL for implicit declarations of builtins. 12967 // Verify that this was correctly set up. 12968 FunctionDecl *F; 12969 if (ULE->decls_begin() != ULE->decls_end() && 12970 ULE->decls_begin() + 1 == ULE->decls_end() && 12971 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12972 F->getBuiltinID() && F->isImplicit()) 12973 llvm_unreachable("performing ADL for builtin"); 12974 12975 // We don't perform ADL in C. 12976 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12977 } 12978 #endif 12979 12980 UnbridgedCastsSet UnbridgedCasts; 12981 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12982 *Result = ExprError(); 12983 return true; 12984 } 12985 12986 // Add the functions denoted by the callee to the set of candidate 12987 // functions, including those from argument-dependent lookup. 12988 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12989 12990 if (getLangOpts().MSVCCompat && 12991 CurContext->isDependentContext() && !isSFINAEContext() && 12992 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12993 12994 OverloadCandidateSet::iterator Best; 12995 if (CandidateSet->empty() || 12996 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12997 OR_No_Viable_Function) { 12998 // In Microsoft mode, if we are inside a template class member function 12999 // then create a type dependent CallExpr. The goal is to postpone name 13000 // lookup to instantiation time to be able to search into type dependent 13001 // base classes. 13002 CallExpr *CE = 13003 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue, 13004 RParenLoc, CurFPFeatureOverrides()); 13005 CE->markDependentForPostponedNameLookup(); 13006 *Result = CE; 13007 return true; 13008 } 13009 } 13010 13011 if (CandidateSet->empty()) 13012 return false; 13013 13014 UnbridgedCasts.restore(); 13015 return false; 13016 } 13017 13018 // Guess at what the return type for an unresolvable overload should be. 13019 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13020 OverloadCandidateSet::iterator *Best) { 13021 llvm::Optional<QualType> Result; 13022 // Adjust Type after seeing a candidate. 13023 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13024 if (!Candidate.Function) 13025 return; 13026 if (Candidate.Function->isInvalidDecl()) 13027 return; 13028 QualType T = Candidate.Function->getReturnType(); 13029 if (T.isNull()) 13030 return; 13031 if (!Result) 13032 Result = T; 13033 else if (Result != T) 13034 Result = QualType(); 13035 }; 13036 13037 // Look for an unambiguous type from a progressively larger subset. 13038 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13039 // 13040 // First, consider only the best candidate. 13041 if (Best && *Best != CS.end()) 13042 ConsiderCandidate(**Best); 13043 // Next, consider only viable candidates. 13044 if (!Result) 13045 for (const auto &C : CS) 13046 if (C.Viable) 13047 ConsiderCandidate(C); 13048 // Finally, consider all candidates. 13049 if (!Result) 13050 for (const auto &C : CS) 13051 ConsiderCandidate(C); 13052 13053 if (!Result) 13054 return QualType(); 13055 auto Value = Result.getValue(); 13056 if (Value.isNull() || Value->isUndeducedType()) 13057 return QualType(); 13058 return Value; 13059 } 13060 13061 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13062 /// the completed call expression. If overload resolution fails, emits 13063 /// diagnostics and returns ExprError() 13064 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13065 UnresolvedLookupExpr *ULE, 13066 SourceLocation LParenLoc, 13067 MultiExprArg Args, 13068 SourceLocation RParenLoc, 13069 Expr *ExecConfig, 13070 OverloadCandidateSet *CandidateSet, 13071 OverloadCandidateSet::iterator *Best, 13072 OverloadingResult OverloadResult, 13073 bool AllowTypoCorrection) { 13074 switch (OverloadResult) { 13075 case OR_Success: { 13076 FunctionDecl *FDecl = (*Best)->Function; 13077 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13078 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13079 return ExprError(); 13080 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13081 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13082 ExecConfig, /*IsExecConfig=*/false, 13083 (*Best)->IsADLCandidate); 13084 } 13085 13086 case OR_No_Viable_Function: { 13087 // Try to recover by looking for viable functions which the user might 13088 // have meant to call. 13089 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13090 Args, RParenLoc, 13091 CandidateSet->empty(), 13092 AllowTypoCorrection); 13093 if (Recovery.isInvalid() || Recovery.isUsable()) 13094 return Recovery; 13095 13096 // If the user passes in a function that we can't take the address of, we 13097 // generally end up emitting really bad error messages. Here, we attempt to 13098 // emit better ones. 13099 for (const Expr *Arg : Args) { 13100 if (!Arg->getType()->isFunctionType()) 13101 continue; 13102 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13103 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13104 if (FD && 13105 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13106 Arg->getExprLoc())) 13107 return ExprError(); 13108 } 13109 } 13110 13111 CandidateSet->NoteCandidates( 13112 PartialDiagnosticAt( 13113 Fn->getBeginLoc(), 13114 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13115 << ULE->getName() << Fn->getSourceRange()), 13116 SemaRef, OCD_AllCandidates, Args); 13117 break; 13118 } 13119 13120 case OR_Ambiguous: 13121 CandidateSet->NoteCandidates( 13122 PartialDiagnosticAt(Fn->getBeginLoc(), 13123 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13124 << ULE->getName() << Fn->getSourceRange()), 13125 SemaRef, OCD_AmbiguousCandidates, Args); 13126 break; 13127 13128 case OR_Deleted: { 13129 CandidateSet->NoteCandidates( 13130 PartialDiagnosticAt(Fn->getBeginLoc(), 13131 SemaRef.PDiag(diag::err_ovl_deleted_call) 13132 << ULE->getName() << Fn->getSourceRange()), 13133 SemaRef, OCD_AllCandidates, Args); 13134 13135 // We emitted an error for the unavailable/deleted function call but keep 13136 // the call in the AST. 13137 FunctionDecl *FDecl = (*Best)->Function; 13138 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13139 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13140 ExecConfig, /*IsExecConfig=*/false, 13141 (*Best)->IsADLCandidate); 13142 } 13143 } 13144 13145 // Overload resolution failed, try to recover. 13146 SmallVector<Expr *, 8> SubExprs = {Fn}; 13147 SubExprs.append(Args.begin(), Args.end()); 13148 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13149 chooseRecoveryType(*CandidateSet, Best)); 13150 } 13151 13152 static void markUnaddressableCandidatesUnviable(Sema &S, 13153 OverloadCandidateSet &CS) { 13154 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13155 if (I->Viable && 13156 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13157 I->Viable = false; 13158 I->FailureKind = ovl_fail_addr_not_available; 13159 } 13160 } 13161 } 13162 13163 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13164 /// (which eventually refers to the declaration Func) and the call 13165 /// arguments Args/NumArgs, attempt to resolve the function call down 13166 /// to a specific function. If overload resolution succeeds, returns 13167 /// the call expression produced by overload resolution. 13168 /// Otherwise, emits diagnostics and returns ExprError. 13169 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13170 UnresolvedLookupExpr *ULE, 13171 SourceLocation LParenLoc, 13172 MultiExprArg Args, 13173 SourceLocation RParenLoc, 13174 Expr *ExecConfig, 13175 bool AllowTypoCorrection, 13176 bool CalleesAddressIsTaken) { 13177 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13178 OverloadCandidateSet::CSK_Normal); 13179 ExprResult result; 13180 13181 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13182 &result)) 13183 return result; 13184 13185 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13186 // functions that aren't addressible are considered unviable. 13187 if (CalleesAddressIsTaken) 13188 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13189 13190 OverloadCandidateSet::iterator Best; 13191 OverloadingResult OverloadResult = 13192 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13193 13194 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13195 ExecConfig, &CandidateSet, &Best, 13196 OverloadResult, AllowTypoCorrection); 13197 } 13198 13199 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13200 return Functions.size() > 1 || 13201 (Functions.size() == 1 && 13202 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13203 } 13204 13205 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13206 NestedNameSpecifierLoc NNSLoc, 13207 DeclarationNameInfo DNI, 13208 const UnresolvedSetImpl &Fns, 13209 bool PerformADL) { 13210 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13211 PerformADL, IsOverloaded(Fns), 13212 Fns.begin(), Fns.end()); 13213 } 13214 13215 /// Create a unary operation that may resolve to an overloaded 13216 /// operator. 13217 /// 13218 /// \param OpLoc The location of the operator itself (e.g., '*'). 13219 /// 13220 /// \param Opc The UnaryOperatorKind that describes this operator. 13221 /// 13222 /// \param Fns The set of non-member functions that will be 13223 /// considered by overload resolution. The caller needs to build this 13224 /// set based on the context using, e.g., 13225 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13226 /// set should not contain any member functions; those will be added 13227 /// by CreateOverloadedUnaryOp(). 13228 /// 13229 /// \param Input The input argument. 13230 ExprResult 13231 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13232 const UnresolvedSetImpl &Fns, 13233 Expr *Input, bool PerformADL) { 13234 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13235 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13236 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13237 // TODO: provide better source location info. 13238 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13239 13240 if (checkPlaceholderForOverload(*this, Input)) 13241 return ExprError(); 13242 13243 Expr *Args[2] = { Input, nullptr }; 13244 unsigned NumArgs = 1; 13245 13246 // For post-increment and post-decrement, add the implicit '0' as 13247 // the second argument, so that we know this is a post-increment or 13248 // post-decrement. 13249 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13250 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13251 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13252 SourceLocation()); 13253 NumArgs = 2; 13254 } 13255 13256 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13257 13258 if (Input->isTypeDependent()) { 13259 if (Fns.empty()) 13260 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13261 VK_RValue, OK_Ordinary, OpLoc, false, 13262 CurFPFeatureOverrides()); 13263 13264 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13265 ExprResult Fn = CreateUnresolvedLookupExpr( 13266 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13267 if (Fn.isInvalid()) 13268 return ExprError(); 13269 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13270 Context.DependentTy, VK_RValue, OpLoc, 13271 CurFPFeatureOverrides()); 13272 } 13273 13274 // Build an empty overload set. 13275 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13276 13277 // Add the candidates from the given function set. 13278 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13279 13280 // Add operator candidates that are member functions. 13281 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13282 13283 // Add candidates from ADL. 13284 if (PerformADL) { 13285 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13286 /*ExplicitTemplateArgs*/nullptr, 13287 CandidateSet); 13288 } 13289 13290 // Add builtin operator candidates. 13291 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13292 13293 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13294 13295 // Perform overload resolution. 13296 OverloadCandidateSet::iterator Best; 13297 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13298 case OR_Success: { 13299 // We found a built-in operator or an overloaded operator. 13300 FunctionDecl *FnDecl = Best->Function; 13301 13302 if (FnDecl) { 13303 Expr *Base = nullptr; 13304 // We matched an overloaded operator. Build a call to that 13305 // operator. 13306 13307 // Convert the arguments. 13308 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13309 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13310 13311 ExprResult InputRes = 13312 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13313 Best->FoundDecl, Method); 13314 if (InputRes.isInvalid()) 13315 return ExprError(); 13316 Base = Input = InputRes.get(); 13317 } else { 13318 // Convert the arguments. 13319 ExprResult InputInit 13320 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13321 Context, 13322 FnDecl->getParamDecl(0)), 13323 SourceLocation(), 13324 Input); 13325 if (InputInit.isInvalid()) 13326 return ExprError(); 13327 Input = InputInit.get(); 13328 } 13329 13330 // Build the actual expression node. 13331 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13332 Base, HadMultipleCandidates, 13333 OpLoc); 13334 if (FnExpr.isInvalid()) 13335 return ExprError(); 13336 13337 // Determine the result type. 13338 QualType ResultTy = FnDecl->getReturnType(); 13339 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13340 ResultTy = ResultTy.getNonLValueExprType(Context); 13341 13342 Args[0] = Input; 13343 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13344 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13345 CurFPFeatureOverrides(), Best->IsADLCandidate); 13346 13347 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13348 return ExprError(); 13349 13350 if (CheckFunctionCall(FnDecl, TheCall, 13351 FnDecl->getType()->castAs<FunctionProtoType>())) 13352 return ExprError(); 13353 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13354 } else { 13355 // We matched a built-in operator. Convert the arguments, then 13356 // break out so that we will build the appropriate built-in 13357 // operator node. 13358 ExprResult InputRes = PerformImplicitConversion( 13359 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13360 CCK_ForBuiltinOverloadedOp); 13361 if (InputRes.isInvalid()) 13362 return ExprError(); 13363 Input = InputRes.get(); 13364 break; 13365 } 13366 } 13367 13368 case OR_No_Viable_Function: 13369 // This is an erroneous use of an operator which can be overloaded by 13370 // a non-member function. Check for non-member operators which were 13371 // defined too late to be candidates. 13372 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13373 // FIXME: Recover by calling the found function. 13374 return ExprError(); 13375 13376 // No viable function; fall through to handling this as a 13377 // built-in operator, which will produce an error message for us. 13378 break; 13379 13380 case OR_Ambiguous: 13381 CandidateSet.NoteCandidates( 13382 PartialDiagnosticAt(OpLoc, 13383 PDiag(diag::err_ovl_ambiguous_oper_unary) 13384 << UnaryOperator::getOpcodeStr(Opc) 13385 << Input->getType() << Input->getSourceRange()), 13386 *this, OCD_AmbiguousCandidates, ArgsArray, 13387 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13388 return ExprError(); 13389 13390 case OR_Deleted: 13391 CandidateSet.NoteCandidates( 13392 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13393 << UnaryOperator::getOpcodeStr(Opc) 13394 << Input->getSourceRange()), 13395 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13396 OpLoc); 13397 return ExprError(); 13398 } 13399 13400 // Either we found no viable overloaded operator or we matched a 13401 // built-in operator. In either case, fall through to trying to 13402 // build a built-in operation. 13403 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13404 } 13405 13406 /// Perform lookup for an overloaded binary operator. 13407 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13408 OverloadedOperatorKind Op, 13409 const UnresolvedSetImpl &Fns, 13410 ArrayRef<Expr *> Args, bool PerformADL) { 13411 SourceLocation OpLoc = CandidateSet.getLocation(); 13412 13413 OverloadedOperatorKind ExtraOp = 13414 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13415 ? getRewrittenOverloadedOperator(Op) 13416 : OO_None; 13417 13418 // Add the candidates from the given function set. This also adds the 13419 // rewritten candidates using these functions if necessary. 13420 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13421 13422 // Add operator candidates that are member functions. 13423 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13424 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13425 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13426 OverloadCandidateParamOrder::Reversed); 13427 13428 // In C++20, also add any rewritten member candidates. 13429 if (ExtraOp) { 13430 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13431 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13432 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13433 CandidateSet, 13434 OverloadCandidateParamOrder::Reversed); 13435 } 13436 13437 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13438 // performed for an assignment operator (nor for operator[] nor operator->, 13439 // which don't get here). 13440 if (Op != OO_Equal && PerformADL) { 13441 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13442 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13443 /*ExplicitTemplateArgs*/ nullptr, 13444 CandidateSet); 13445 if (ExtraOp) { 13446 DeclarationName ExtraOpName = 13447 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13448 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13449 /*ExplicitTemplateArgs*/ nullptr, 13450 CandidateSet); 13451 } 13452 } 13453 13454 // Add builtin operator candidates. 13455 // 13456 // FIXME: We don't add any rewritten candidates here. This is strictly 13457 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13458 // resulting in our selecting a rewritten builtin candidate. For example: 13459 // 13460 // enum class E { e }; 13461 // bool operator!=(E, E) requires false; 13462 // bool k = E::e != E::e; 13463 // 13464 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13465 // it seems unreasonable to consider rewritten builtin candidates. A core 13466 // issue has been filed proposing to removed this requirement. 13467 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13468 } 13469 13470 /// Create a binary operation that may resolve to an overloaded 13471 /// operator. 13472 /// 13473 /// \param OpLoc The location of the operator itself (e.g., '+'). 13474 /// 13475 /// \param Opc The BinaryOperatorKind that describes this operator. 13476 /// 13477 /// \param Fns The set of non-member functions that will be 13478 /// considered by overload resolution. The caller needs to build this 13479 /// set based on the context using, e.g., 13480 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13481 /// set should not contain any member functions; those will be added 13482 /// by CreateOverloadedBinOp(). 13483 /// 13484 /// \param LHS Left-hand argument. 13485 /// \param RHS Right-hand argument. 13486 /// \param PerformADL Whether to consider operator candidates found by ADL. 13487 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13488 /// C++20 operator rewrites. 13489 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13490 /// the function in question. Such a function is never a candidate in 13491 /// our overload resolution. This also enables synthesizing a three-way 13492 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13493 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13494 BinaryOperatorKind Opc, 13495 const UnresolvedSetImpl &Fns, Expr *LHS, 13496 Expr *RHS, bool PerformADL, 13497 bool AllowRewrittenCandidates, 13498 FunctionDecl *DefaultedFn) { 13499 Expr *Args[2] = { LHS, RHS }; 13500 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13501 13502 if (!getLangOpts().CPlusPlus20) 13503 AllowRewrittenCandidates = false; 13504 13505 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13506 13507 // If either side is type-dependent, create an appropriate dependent 13508 // expression. 13509 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13510 if (Fns.empty()) { 13511 // If there are no functions to store, just build a dependent 13512 // BinaryOperator or CompoundAssignment. 13513 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13514 return CompoundAssignOperator::Create( 13515 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13516 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13517 Context.DependentTy); 13518 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13519 Context.DependentTy, VK_RValue, OK_Ordinary, 13520 OpLoc, CurFPFeatureOverrides()); 13521 } 13522 13523 // FIXME: save results of ADL from here? 13524 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13525 // TODO: provide better source location info in DNLoc component. 13526 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13527 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13528 ExprResult Fn = CreateUnresolvedLookupExpr( 13529 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13530 if (Fn.isInvalid()) 13531 return ExprError(); 13532 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13533 Context.DependentTy, VK_RValue, OpLoc, 13534 CurFPFeatureOverrides()); 13535 } 13536 13537 // Always do placeholder-like conversions on the RHS. 13538 if (checkPlaceholderForOverload(*this, Args[1])) 13539 return ExprError(); 13540 13541 // Do placeholder-like conversion on the LHS; note that we should 13542 // not get here with a PseudoObject LHS. 13543 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13544 if (checkPlaceholderForOverload(*this, Args[0])) 13545 return ExprError(); 13546 13547 // If this is the assignment operator, we only perform overload resolution 13548 // if the left-hand side is a class or enumeration type. This is actually 13549 // a hack. The standard requires that we do overload resolution between the 13550 // various built-in candidates, but as DR507 points out, this can lead to 13551 // problems. So we do it this way, which pretty much follows what GCC does. 13552 // Note that we go the traditional code path for compound assignment forms. 13553 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13554 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13555 13556 // If this is the .* operator, which is not overloadable, just 13557 // create a built-in binary operator. 13558 if (Opc == BO_PtrMemD) 13559 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13560 13561 // Build the overload set. 13562 OverloadCandidateSet CandidateSet( 13563 OpLoc, OverloadCandidateSet::CSK_Operator, 13564 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13565 if (DefaultedFn) 13566 CandidateSet.exclude(DefaultedFn); 13567 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13568 13569 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13570 13571 // Perform overload resolution. 13572 OverloadCandidateSet::iterator Best; 13573 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13574 case OR_Success: { 13575 // We found a built-in operator or an overloaded operator. 13576 FunctionDecl *FnDecl = Best->Function; 13577 13578 bool IsReversed = Best->isReversed(); 13579 if (IsReversed) 13580 std::swap(Args[0], Args[1]); 13581 13582 if (FnDecl) { 13583 Expr *Base = nullptr; 13584 // We matched an overloaded operator. Build a call to that 13585 // operator. 13586 13587 OverloadedOperatorKind ChosenOp = 13588 FnDecl->getDeclName().getCXXOverloadedOperator(); 13589 13590 // C++2a [over.match.oper]p9: 13591 // If a rewritten operator== candidate is selected by overload 13592 // resolution for an operator@, its return type shall be cv bool 13593 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13594 !FnDecl->getReturnType()->isBooleanType()) { 13595 bool IsExtension = 13596 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13597 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13598 : diag::err_ovl_rewrite_equalequal_not_bool) 13599 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13600 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13601 Diag(FnDecl->getLocation(), diag::note_declared_at); 13602 if (!IsExtension) 13603 return ExprError(); 13604 } 13605 13606 if (AllowRewrittenCandidates && !IsReversed && 13607 CandidateSet.getRewriteInfo().isReversible()) { 13608 // We could have reversed this operator, but didn't. Check if some 13609 // reversed form was a viable candidate, and if so, if it had a 13610 // better conversion for either parameter. If so, this call is 13611 // formally ambiguous, and allowing it is an extension. 13612 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13613 for (OverloadCandidate &Cand : CandidateSet) { 13614 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13615 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13616 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13617 if (CompareImplicitConversionSequences( 13618 *this, OpLoc, Cand.Conversions[ArgIdx], 13619 Best->Conversions[ArgIdx]) == 13620 ImplicitConversionSequence::Better) { 13621 AmbiguousWith.push_back(Cand.Function); 13622 break; 13623 } 13624 } 13625 } 13626 } 13627 13628 if (!AmbiguousWith.empty()) { 13629 bool AmbiguousWithSelf = 13630 AmbiguousWith.size() == 1 && 13631 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13632 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13633 << BinaryOperator::getOpcodeStr(Opc) 13634 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13635 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13636 if (AmbiguousWithSelf) { 13637 Diag(FnDecl->getLocation(), 13638 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13639 } else { 13640 Diag(FnDecl->getLocation(), 13641 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13642 for (auto *F : AmbiguousWith) 13643 Diag(F->getLocation(), 13644 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13645 } 13646 } 13647 } 13648 13649 // Convert the arguments. 13650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13651 // Best->Access is only meaningful for class members. 13652 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13653 13654 ExprResult Arg1 = 13655 PerformCopyInitialization( 13656 InitializedEntity::InitializeParameter(Context, 13657 FnDecl->getParamDecl(0)), 13658 SourceLocation(), Args[1]); 13659 if (Arg1.isInvalid()) 13660 return ExprError(); 13661 13662 ExprResult Arg0 = 13663 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13664 Best->FoundDecl, Method); 13665 if (Arg0.isInvalid()) 13666 return ExprError(); 13667 Base = Args[0] = Arg0.getAs<Expr>(); 13668 Args[1] = RHS = Arg1.getAs<Expr>(); 13669 } else { 13670 // Convert the arguments. 13671 ExprResult Arg0 = PerformCopyInitialization( 13672 InitializedEntity::InitializeParameter(Context, 13673 FnDecl->getParamDecl(0)), 13674 SourceLocation(), Args[0]); 13675 if (Arg0.isInvalid()) 13676 return ExprError(); 13677 13678 ExprResult Arg1 = 13679 PerformCopyInitialization( 13680 InitializedEntity::InitializeParameter(Context, 13681 FnDecl->getParamDecl(1)), 13682 SourceLocation(), Args[1]); 13683 if (Arg1.isInvalid()) 13684 return ExprError(); 13685 Args[0] = LHS = Arg0.getAs<Expr>(); 13686 Args[1] = RHS = Arg1.getAs<Expr>(); 13687 } 13688 13689 // Build the actual expression node. 13690 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13691 Best->FoundDecl, Base, 13692 HadMultipleCandidates, OpLoc); 13693 if (FnExpr.isInvalid()) 13694 return ExprError(); 13695 13696 // Determine the result type. 13697 QualType ResultTy = FnDecl->getReturnType(); 13698 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13699 ResultTy = ResultTy.getNonLValueExprType(Context); 13700 13701 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13702 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13703 CurFPFeatureOverrides(), Best->IsADLCandidate); 13704 13705 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13706 FnDecl)) 13707 return ExprError(); 13708 13709 ArrayRef<const Expr *> ArgsArray(Args, 2); 13710 const Expr *ImplicitThis = nullptr; 13711 // Cut off the implicit 'this'. 13712 if (isa<CXXMethodDecl>(FnDecl)) { 13713 ImplicitThis = ArgsArray[0]; 13714 ArgsArray = ArgsArray.slice(1); 13715 } 13716 13717 // Check for a self move. 13718 if (Op == OO_Equal) 13719 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13720 13721 if (ImplicitThis) { 13722 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13723 QualType ThisTypeFromDecl = Context.getPointerType( 13724 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13725 13726 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13727 ThisTypeFromDecl); 13728 } 13729 13730 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13731 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13732 VariadicDoesNotApply); 13733 13734 ExprResult R = MaybeBindToTemporary(TheCall); 13735 if (R.isInvalid()) 13736 return ExprError(); 13737 13738 R = CheckForImmediateInvocation(R, FnDecl); 13739 if (R.isInvalid()) 13740 return ExprError(); 13741 13742 // For a rewritten candidate, we've already reversed the arguments 13743 // if needed. Perform the rest of the rewrite now. 13744 if ((Best->RewriteKind & CRK_DifferentOperator) || 13745 (Op == OO_Spaceship && IsReversed)) { 13746 if (Op == OO_ExclaimEqual) { 13747 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13748 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13749 } else { 13750 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13751 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13752 Expr *ZeroLiteral = 13753 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13754 13755 Sema::CodeSynthesisContext Ctx; 13756 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13757 Ctx.Entity = FnDecl; 13758 pushCodeSynthesisContext(Ctx); 13759 13760 R = CreateOverloadedBinOp( 13761 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13762 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13763 /*AllowRewrittenCandidates=*/false); 13764 13765 popCodeSynthesisContext(); 13766 } 13767 if (R.isInvalid()) 13768 return ExprError(); 13769 } else { 13770 assert(ChosenOp == Op && "unexpected operator name"); 13771 } 13772 13773 // Make a note in the AST if we did any rewriting. 13774 if (Best->RewriteKind != CRK_None) 13775 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13776 13777 return R; 13778 } else { 13779 // We matched a built-in operator. Convert the arguments, then 13780 // break out so that we will build the appropriate built-in 13781 // operator node. 13782 ExprResult ArgsRes0 = PerformImplicitConversion( 13783 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13784 AA_Passing, CCK_ForBuiltinOverloadedOp); 13785 if (ArgsRes0.isInvalid()) 13786 return ExprError(); 13787 Args[0] = ArgsRes0.get(); 13788 13789 ExprResult ArgsRes1 = PerformImplicitConversion( 13790 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13791 AA_Passing, CCK_ForBuiltinOverloadedOp); 13792 if (ArgsRes1.isInvalid()) 13793 return ExprError(); 13794 Args[1] = ArgsRes1.get(); 13795 break; 13796 } 13797 } 13798 13799 case OR_No_Viable_Function: { 13800 // C++ [over.match.oper]p9: 13801 // If the operator is the operator , [...] and there are no 13802 // viable functions, then the operator is assumed to be the 13803 // built-in operator and interpreted according to clause 5. 13804 if (Opc == BO_Comma) 13805 break; 13806 13807 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13808 // compare result using '==' and '<'. 13809 if (DefaultedFn && Opc == BO_Cmp) { 13810 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13811 Args[1], DefaultedFn); 13812 if (E.isInvalid() || E.isUsable()) 13813 return E; 13814 } 13815 13816 // For class as left operand for assignment or compound assignment 13817 // operator do not fall through to handling in built-in, but report that 13818 // no overloaded assignment operator found 13819 ExprResult Result = ExprError(); 13820 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13821 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13822 Args, OpLoc); 13823 if (Args[0]->getType()->isRecordType() && 13824 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13825 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13826 << BinaryOperator::getOpcodeStr(Opc) 13827 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13828 if (Args[0]->getType()->isIncompleteType()) { 13829 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13830 << Args[0]->getType() 13831 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13832 } 13833 } else { 13834 // This is an erroneous use of an operator which can be overloaded by 13835 // a non-member function. Check for non-member operators which were 13836 // defined too late to be candidates. 13837 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13838 // FIXME: Recover by calling the found function. 13839 return ExprError(); 13840 13841 // No viable function; try to create a built-in operation, which will 13842 // produce an error. Then, show the non-viable candidates. 13843 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13844 } 13845 assert(Result.isInvalid() && 13846 "C++ binary operator overloading is missing candidates!"); 13847 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13848 return Result; 13849 } 13850 13851 case OR_Ambiguous: 13852 CandidateSet.NoteCandidates( 13853 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13854 << BinaryOperator::getOpcodeStr(Opc) 13855 << Args[0]->getType() 13856 << Args[1]->getType() 13857 << Args[0]->getSourceRange() 13858 << Args[1]->getSourceRange()), 13859 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13860 OpLoc); 13861 return ExprError(); 13862 13863 case OR_Deleted: 13864 if (isImplicitlyDeleted(Best->Function)) { 13865 FunctionDecl *DeletedFD = Best->Function; 13866 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13867 if (DFK.isSpecialMember()) { 13868 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13869 << Args[0]->getType() << DFK.asSpecialMember(); 13870 } else { 13871 assert(DFK.isComparison()); 13872 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13873 << Args[0]->getType() << DeletedFD; 13874 } 13875 13876 // The user probably meant to call this special member. Just 13877 // explain why it's deleted. 13878 NoteDeletedFunction(DeletedFD); 13879 return ExprError(); 13880 } 13881 CandidateSet.NoteCandidates( 13882 PartialDiagnosticAt( 13883 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13884 << getOperatorSpelling(Best->Function->getDeclName() 13885 .getCXXOverloadedOperator()) 13886 << Args[0]->getSourceRange() 13887 << Args[1]->getSourceRange()), 13888 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13889 OpLoc); 13890 return ExprError(); 13891 } 13892 13893 // We matched a built-in operator; build it. 13894 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13895 } 13896 13897 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13898 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13899 FunctionDecl *DefaultedFn) { 13900 const ComparisonCategoryInfo *Info = 13901 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13902 // If we're not producing a known comparison category type, we can't 13903 // synthesize a three-way comparison. Let the caller diagnose this. 13904 if (!Info) 13905 return ExprResult((Expr*)nullptr); 13906 13907 // If we ever want to perform this synthesis more generally, we will need to 13908 // apply the temporary materialization conversion to the operands. 13909 assert(LHS->isGLValue() && RHS->isGLValue() && 13910 "cannot use prvalue expressions more than once"); 13911 Expr *OrigLHS = LHS; 13912 Expr *OrigRHS = RHS; 13913 13914 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13915 // each of them multiple times below. 13916 LHS = new (Context) 13917 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13918 LHS->getObjectKind(), LHS); 13919 RHS = new (Context) 13920 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13921 RHS->getObjectKind(), RHS); 13922 13923 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13924 DefaultedFn); 13925 if (Eq.isInvalid()) 13926 return ExprError(); 13927 13928 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13929 true, DefaultedFn); 13930 if (Less.isInvalid()) 13931 return ExprError(); 13932 13933 ExprResult Greater; 13934 if (Info->isPartial()) { 13935 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13936 DefaultedFn); 13937 if (Greater.isInvalid()) 13938 return ExprError(); 13939 } 13940 13941 // Form the list of comparisons we're going to perform. 13942 struct Comparison { 13943 ExprResult Cmp; 13944 ComparisonCategoryResult Result; 13945 } Comparisons[4] = 13946 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13947 : ComparisonCategoryResult::Equivalent}, 13948 {Less, ComparisonCategoryResult::Less}, 13949 {Greater, ComparisonCategoryResult::Greater}, 13950 {ExprResult(), ComparisonCategoryResult::Unordered}, 13951 }; 13952 13953 int I = Info->isPartial() ? 3 : 2; 13954 13955 // Combine the comparisons with suitable conditional expressions. 13956 ExprResult Result; 13957 for (; I >= 0; --I) { 13958 // Build a reference to the comparison category constant. 13959 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13960 // FIXME: Missing a constant for a comparison category. Diagnose this? 13961 if (!VI) 13962 return ExprResult((Expr*)nullptr); 13963 ExprResult ThisResult = 13964 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13965 if (ThisResult.isInvalid()) 13966 return ExprError(); 13967 13968 // Build a conditional unless this is the final case. 13969 if (Result.get()) { 13970 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13971 ThisResult.get(), Result.get()); 13972 if (Result.isInvalid()) 13973 return ExprError(); 13974 } else { 13975 Result = ThisResult; 13976 } 13977 } 13978 13979 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13980 // bind the OpaqueValueExprs before they're (repeatedly) used. 13981 Expr *SyntacticForm = BinaryOperator::Create( 13982 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13983 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13984 CurFPFeatureOverrides()); 13985 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13986 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13987 } 13988 13989 ExprResult 13990 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13991 SourceLocation RLoc, 13992 Expr *Base, Expr *Idx) { 13993 Expr *Args[2] = { Base, Idx }; 13994 DeclarationName OpName = 13995 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13996 13997 // If either side is type-dependent, create an appropriate dependent 13998 // expression. 13999 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 14000 14001 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14002 // CHECKME: no 'operator' keyword? 14003 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14004 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14005 ExprResult Fn = CreateUnresolvedLookupExpr( 14006 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14007 if (Fn.isInvalid()) 14008 return ExprError(); 14009 // Can't add any actual overloads yet 14010 14011 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14012 Context.DependentTy, VK_RValue, RLoc, 14013 CurFPFeatureOverrides()); 14014 } 14015 14016 // Handle placeholders on both operands. 14017 if (checkPlaceholderForOverload(*this, Args[0])) 14018 return ExprError(); 14019 if (checkPlaceholderForOverload(*this, Args[1])) 14020 return ExprError(); 14021 14022 // Build an empty overload set. 14023 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14024 14025 // Subscript can only be overloaded as a member function. 14026 14027 // Add operator candidates that are member functions. 14028 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14029 14030 // Add builtin operator candidates. 14031 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14032 14033 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14034 14035 // Perform overload resolution. 14036 OverloadCandidateSet::iterator Best; 14037 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14038 case OR_Success: { 14039 // We found a built-in operator or an overloaded operator. 14040 FunctionDecl *FnDecl = Best->Function; 14041 14042 if (FnDecl) { 14043 // We matched an overloaded operator. Build a call to that 14044 // operator. 14045 14046 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 14047 14048 // Convert the arguments. 14049 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14050 ExprResult Arg0 = 14051 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 14052 Best->FoundDecl, Method); 14053 if (Arg0.isInvalid()) 14054 return ExprError(); 14055 Args[0] = Arg0.get(); 14056 14057 // Convert the arguments. 14058 ExprResult InputInit 14059 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14060 Context, 14061 FnDecl->getParamDecl(0)), 14062 SourceLocation(), 14063 Args[1]); 14064 if (InputInit.isInvalid()) 14065 return ExprError(); 14066 14067 Args[1] = InputInit.getAs<Expr>(); 14068 14069 // Build the actual expression node. 14070 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14071 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14072 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14073 Best->FoundDecl, 14074 Base, 14075 HadMultipleCandidates, 14076 OpLocInfo.getLoc(), 14077 OpLocInfo.getInfo()); 14078 if (FnExpr.isInvalid()) 14079 return ExprError(); 14080 14081 // Determine the result type 14082 QualType ResultTy = FnDecl->getReturnType(); 14083 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14084 ResultTy = ResultTy.getNonLValueExprType(Context); 14085 14086 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14087 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 14088 CurFPFeatureOverrides()); 14089 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14090 return ExprError(); 14091 14092 if (CheckFunctionCall(Method, TheCall, 14093 Method->getType()->castAs<FunctionProtoType>())) 14094 return ExprError(); 14095 14096 return MaybeBindToTemporary(TheCall); 14097 } else { 14098 // We matched a built-in operator. Convert the arguments, then 14099 // break out so that we will build the appropriate built-in 14100 // operator node. 14101 ExprResult ArgsRes0 = PerformImplicitConversion( 14102 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14103 AA_Passing, CCK_ForBuiltinOverloadedOp); 14104 if (ArgsRes0.isInvalid()) 14105 return ExprError(); 14106 Args[0] = ArgsRes0.get(); 14107 14108 ExprResult ArgsRes1 = PerformImplicitConversion( 14109 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14110 AA_Passing, CCK_ForBuiltinOverloadedOp); 14111 if (ArgsRes1.isInvalid()) 14112 return ExprError(); 14113 Args[1] = ArgsRes1.get(); 14114 14115 break; 14116 } 14117 } 14118 14119 case OR_No_Viable_Function: { 14120 PartialDiagnostic PD = CandidateSet.empty() 14121 ? (PDiag(diag::err_ovl_no_oper) 14122 << Args[0]->getType() << /*subscript*/ 0 14123 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 14124 : (PDiag(diag::err_ovl_no_viable_subscript) 14125 << Args[0]->getType() << Args[0]->getSourceRange() 14126 << Args[1]->getSourceRange()); 14127 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14128 OCD_AllCandidates, Args, "[]", LLoc); 14129 return ExprError(); 14130 } 14131 14132 case OR_Ambiguous: 14133 CandidateSet.NoteCandidates( 14134 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14135 << "[]" << Args[0]->getType() 14136 << Args[1]->getType() 14137 << Args[0]->getSourceRange() 14138 << Args[1]->getSourceRange()), 14139 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14140 return ExprError(); 14141 14142 case OR_Deleted: 14143 CandidateSet.NoteCandidates( 14144 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14145 << "[]" << Args[0]->getSourceRange() 14146 << Args[1]->getSourceRange()), 14147 *this, OCD_AllCandidates, Args, "[]", LLoc); 14148 return ExprError(); 14149 } 14150 14151 // We matched a built-in operator; build it. 14152 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14153 } 14154 14155 /// BuildCallToMemberFunction - Build a call to a member 14156 /// function. MemExpr is the expression that refers to the member 14157 /// function (and includes the object parameter), Args/NumArgs are the 14158 /// arguments to the function call (not including the object 14159 /// parameter). The caller needs to validate that the member 14160 /// expression refers to a non-static member function or an overloaded 14161 /// member function. 14162 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14163 SourceLocation LParenLoc, 14164 MultiExprArg Args, 14165 SourceLocation RParenLoc, 14166 bool AllowRecovery) { 14167 assert(MemExprE->getType() == Context.BoundMemberTy || 14168 MemExprE->getType() == Context.OverloadTy); 14169 14170 // Dig out the member expression. This holds both the object 14171 // argument and the member function we're referring to. 14172 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14173 14174 // Determine whether this is a call to a pointer-to-member function. 14175 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14176 assert(op->getType() == Context.BoundMemberTy); 14177 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14178 14179 QualType fnType = 14180 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14181 14182 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14183 QualType resultType = proto->getCallResultType(Context); 14184 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14185 14186 // Check that the object type isn't more qualified than the 14187 // member function we're calling. 14188 Qualifiers funcQuals = proto->getMethodQuals(); 14189 14190 QualType objectType = op->getLHS()->getType(); 14191 if (op->getOpcode() == BO_PtrMemI) 14192 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14193 Qualifiers objectQuals = objectType.getQualifiers(); 14194 14195 Qualifiers difference = objectQuals - funcQuals; 14196 difference.removeObjCGCAttr(); 14197 difference.removeAddressSpace(); 14198 if (difference) { 14199 std::string qualsString = difference.getAsString(); 14200 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14201 << fnType.getUnqualifiedType() 14202 << qualsString 14203 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14204 } 14205 14206 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14207 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14208 CurFPFeatureOverrides(), proto->getNumParams()); 14209 14210 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14211 call, nullptr)) 14212 return ExprError(); 14213 14214 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14215 return ExprError(); 14216 14217 if (CheckOtherCall(call, proto)) 14218 return ExprError(); 14219 14220 return MaybeBindToTemporary(call); 14221 } 14222 14223 // We only try to build a recovery expr at this level if we can preserve 14224 // the return type, otherwise we return ExprError() and let the caller 14225 // recover. 14226 auto BuildRecoveryExpr = [&](QualType Type) { 14227 if (!AllowRecovery) 14228 return ExprError(); 14229 std::vector<Expr *> SubExprs = {MemExprE}; 14230 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); }); 14231 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14232 Type); 14233 }; 14234 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14235 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14236 RParenLoc, CurFPFeatureOverrides()); 14237 14238 UnbridgedCastsSet UnbridgedCasts; 14239 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14240 return ExprError(); 14241 14242 MemberExpr *MemExpr; 14243 CXXMethodDecl *Method = nullptr; 14244 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14245 NestedNameSpecifier *Qualifier = nullptr; 14246 if (isa<MemberExpr>(NakedMemExpr)) { 14247 MemExpr = cast<MemberExpr>(NakedMemExpr); 14248 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14249 FoundDecl = MemExpr->getFoundDecl(); 14250 Qualifier = MemExpr->getQualifier(); 14251 UnbridgedCasts.restore(); 14252 } else { 14253 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14254 Qualifier = UnresExpr->getQualifier(); 14255 14256 QualType ObjectType = UnresExpr->getBaseType(); 14257 Expr::Classification ObjectClassification 14258 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14259 : UnresExpr->getBase()->Classify(Context); 14260 14261 // Add overload candidates 14262 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14263 OverloadCandidateSet::CSK_Normal); 14264 14265 // FIXME: avoid copy. 14266 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14267 if (UnresExpr->hasExplicitTemplateArgs()) { 14268 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14269 TemplateArgs = &TemplateArgsBuffer; 14270 } 14271 14272 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14273 E = UnresExpr->decls_end(); I != E; ++I) { 14274 14275 NamedDecl *Func = *I; 14276 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14277 if (isa<UsingShadowDecl>(Func)) 14278 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14279 14280 14281 // Microsoft supports direct constructor calls. 14282 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14283 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14284 CandidateSet, 14285 /*SuppressUserConversions*/ false); 14286 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14287 // If explicit template arguments were provided, we can't call a 14288 // non-template member function. 14289 if (TemplateArgs) 14290 continue; 14291 14292 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14293 ObjectClassification, Args, CandidateSet, 14294 /*SuppressUserConversions=*/false); 14295 } else { 14296 AddMethodTemplateCandidate( 14297 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14298 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14299 /*SuppressUserConversions=*/false); 14300 } 14301 } 14302 14303 DeclarationName DeclName = UnresExpr->getMemberName(); 14304 14305 UnbridgedCasts.restore(); 14306 14307 OverloadCandidateSet::iterator Best; 14308 bool Succeeded = false; 14309 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14310 Best)) { 14311 case OR_Success: 14312 Method = cast<CXXMethodDecl>(Best->Function); 14313 FoundDecl = Best->FoundDecl; 14314 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14315 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14316 break; 14317 // If FoundDecl is different from Method (such as if one is a template 14318 // and the other a specialization), make sure DiagnoseUseOfDecl is 14319 // called on both. 14320 // FIXME: This would be more comprehensively addressed by modifying 14321 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14322 // being used. 14323 if (Method != FoundDecl.getDecl() && 14324 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14325 break; 14326 Succeeded = true; 14327 break; 14328 14329 case OR_No_Viable_Function: 14330 CandidateSet.NoteCandidates( 14331 PartialDiagnosticAt( 14332 UnresExpr->getMemberLoc(), 14333 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14334 << DeclName << MemExprE->getSourceRange()), 14335 *this, OCD_AllCandidates, Args); 14336 break; 14337 case OR_Ambiguous: 14338 CandidateSet.NoteCandidates( 14339 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14340 PDiag(diag::err_ovl_ambiguous_member_call) 14341 << DeclName << MemExprE->getSourceRange()), 14342 *this, OCD_AmbiguousCandidates, Args); 14343 break; 14344 case OR_Deleted: 14345 CandidateSet.NoteCandidates( 14346 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14347 PDiag(diag::err_ovl_deleted_member_call) 14348 << DeclName << MemExprE->getSourceRange()), 14349 *this, OCD_AllCandidates, Args); 14350 break; 14351 } 14352 // Overload resolution fails, try to recover. 14353 if (!Succeeded) 14354 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14355 14356 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14357 14358 // If overload resolution picked a static member, build a 14359 // non-member call based on that function. 14360 if (Method->isStatic()) { 14361 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14362 RParenLoc); 14363 } 14364 14365 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14366 } 14367 14368 QualType ResultType = Method->getReturnType(); 14369 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14370 ResultType = ResultType.getNonLValueExprType(Context); 14371 14372 assert(Method && "Member call to something that isn't a method?"); 14373 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14374 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14375 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14376 CurFPFeatureOverrides(), Proto->getNumParams()); 14377 14378 // Check for a valid return type. 14379 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14380 TheCall, Method)) 14381 return BuildRecoveryExpr(ResultType); 14382 14383 // Convert the object argument (for a non-static member function call). 14384 // We only need to do this if there was actually an overload; otherwise 14385 // it was done at lookup. 14386 if (!Method->isStatic()) { 14387 ExprResult ObjectArg = 14388 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14389 FoundDecl, Method); 14390 if (ObjectArg.isInvalid()) 14391 return ExprError(); 14392 MemExpr->setBase(ObjectArg.get()); 14393 } 14394 14395 // Convert the rest of the arguments 14396 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14397 RParenLoc)) 14398 return BuildRecoveryExpr(ResultType); 14399 14400 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14401 14402 if (CheckFunctionCall(Method, TheCall, Proto)) 14403 return ExprError(); 14404 14405 // In the case the method to call was not selected by the overloading 14406 // resolution process, we still need to handle the enable_if attribute. Do 14407 // that here, so it will not hide previous -- and more relevant -- errors. 14408 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14409 if (const EnableIfAttr *Attr = 14410 CheckEnableIf(Method, LParenLoc, Args, true)) { 14411 Diag(MemE->getMemberLoc(), 14412 diag::err_ovl_no_viable_member_function_in_call) 14413 << Method << Method->getSourceRange(); 14414 Diag(Method->getLocation(), 14415 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14416 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14417 return ExprError(); 14418 } 14419 } 14420 14421 if ((isa<CXXConstructorDecl>(CurContext) || 14422 isa<CXXDestructorDecl>(CurContext)) && 14423 TheCall->getMethodDecl()->isPure()) { 14424 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14425 14426 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14427 MemExpr->performsVirtualDispatch(getLangOpts())) { 14428 Diag(MemExpr->getBeginLoc(), 14429 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14430 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14431 << MD->getParent(); 14432 14433 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14434 if (getLangOpts().AppleKext) 14435 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14436 << MD->getParent() << MD->getDeclName(); 14437 } 14438 } 14439 14440 if (CXXDestructorDecl *DD = 14441 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14442 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14443 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14444 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14445 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14446 MemExpr->getMemberLoc()); 14447 } 14448 14449 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14450 TheCall->getMethodDecl()); 14451 } 14452 14453 /// BuildCallToObjectOfClassType - Build a call to an object of class 14454 /// type (C++ [over.call.object]), which can end up invoking an 14455 /// overloaded function call operator (@c operator()) or performing a 14456 /// user-defined conversion on the object argument. 14457 ExprResult 14458 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14459 SourceLocation LParenLoc, 14460 MultiExprArg Args, 14461 SourceLocation RParenLoc) { 14462 if (checkPlaceholderForOverload(*this, Obj)) 14463 return ExprError(); 14464 ExprResult Object = Obj; 14465 14466 UnbridgedCastsSet UnbridgedCasts; 14467 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14468 return ExprError(); 14469 14470 assert(Object.get()->getType()->isRecordType() && 14471 "Requires object type argument"); 14472 14473 // C++ [over.call.object]p1: 14474 // If the primary-expression E in the function call syntax 14475 // evaluates to a class object of type "cv T", then the set of 14476 // candidate functions includes at least the function call 14477 // operators of T. The function call operators of T are obtained by 14478 // ordinary lookup of the name operator() in the context of 14479 // (E).operator(). 14480 OverloadCandidateSet CandidateSet(LParenLoc, 14481 OverloadCandidateSet::CSK_Operator); 14482 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14483 14484 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14485 diag::err_incomplete_object_call, Object.get())) 14486 return true; 14487 14488 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14489 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14490 LookupQualifiedName(R, Record->getDecl()); 14491 R.suppressDiagnostics(); 14492 14493 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14494 Oper != OperEnd; ++Oper) { 14495 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14496 Object.get()->Classify(Context), Args, CandidateSet, 14497 /*SuppressUserConversion=*/false); 14498 } 14499 14500 // C++ [over.call.object]p2: 14501 // In addition, for each (non-explicit in C++0x) conversion function 14502 // declared in T of the form 14503 // 14504 // operator conversion-type-id () cv-qualifier; 14505 // 14506 // where cv-qualifier is the same cv-qualification as, or a 14507 // greater cv-qualification than, cv, and where conversion-type-id 14508 // denotes the type "pointer to function of (P1,...,Pn) returning 14509 // R", or the type "reference to pointer to function of 14510 // (P1,...,Pn) returning R", or the type "reference to function 14511 // of (P1,...,Pn) returning R", a surrogate call function [...] 14512 // is also considered as a candidate function. Similarly, 14513 // surrogate call functions are added to the set of candidate 14514 // functions for each conversion function declared in an 14515 // accessible base class provided the function is not hidden 14516 // within T by another intervening declaration. 14517 const auto &Conversions = 14518 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14519 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14520 NamedDecl *D = *I; 14521 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14522 if (isa<UsingShadowDecl>(D)) 14523 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14524 14525 // Skip over templated conversion functions; they aren't 14526 // surrogates. 14527 if (isa<FunctionTemplateDecl>(D)) 14528 continue; 14529 14530 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14531 if (!Conv->isExplicit()) { 14532 // Strip the reference type (if any) and then the pointer type (if 14533 // any) to get down to what might be a function type. 14534 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14535 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14536 ConvType = ConvPtrType->getPointeeType(); 14537 14538 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14539 { 14540 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14541 Object.get(), Args, CandidateSet); 14542 } 14543 } 14544 } 14545 14546 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14547 14548 // Perform overload resolution. 14549 OverloadCandidateSet::iterator Best; 14550 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14551 Best)) { 14552 case OR_Success: 14553 // Overload resolution succeeded; we'll build the appropriate call 14554 // below. 14555 break; 14556 14557 case OR_No_Viable_Function: { 14558 PartialDiagnostic PD = 14559 CandidateSet.empty() 14560 ? (PDiag(diag::err_ovl_no_oper) 14561 << Object.get()->getType() << /*call*/ 1 14562 << Object.get()->getSourceRange()) 14563 : (PDiag(diag::err_ovl_no_viable_object_call) 14564 << Object.get()->getType() << Object.get()->getSourceRange()); 14565 CandidateSet.NoteCandidates( 14566 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14567 OCD_AllCandidates, Args); 14568 break; 14569 } 14570 case OR_Ambiguous: 14571 CandidateSet.NoteCandidates( 14572 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14573 PDiag(diag::err_ovl_ambiguous_object_call) 14574 << Object.get()->getType() 14575 << Object.get()->getSourceRange()), 14576 *this, OCD_AmbiguousCandidates, Args); 14577 break; 14578 14579 case OR_Deleted: 14580 CandidateSet.NoteCandidates( 14581 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14582 PDiag(diag::err_ovl_deleted_object_call) 14583 << Object.get()->getType() 14584 << Object.get()->getSourceRange()), 14585 *this, OCD_AllCandidates, Args); 14586 break; 14587 } 14588 14589 if (Best == CandidateSet.end()) 14590 return true; 14591 14592 UnbridgedCasts.restore(); 14593 14594 if (Best->Function == nullptr) { 14595 // Since there is no function declaration, this is one of the 14596 // surrogate candidates. Dig out the conversion function. 14597 CXXConversionDecl *Conv 14598 = cast<CXXConversionDecl>( 14599 Best->Conversions[0].UserDefined.ConversionFunction); 14600 14601 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14602 Best->FoundDecl); 14603 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14604 return ExprError(); 14605 assert(Conv == Best->FoundDecl.getDecl() && 14606 "Found Decl & conversion-to-functionptr should be same, right?!"); 14607 // We selected one of the surrogate functions that converts the 14608 // object parameter to a function pointer. Perform the conversion 14609 // on the object argument, then let BuildCallExpr finish the job. 14610 14611 // Create an implicit member expr to refer to the conversion operator. 14612 // and then call it. 14613 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14614 Conv, HadMultipleCandidates); 14615 if (Call.isInvalid()) 14616 return ExprError(); 14617 // Record usage of conversion in an implicit cast. 14618 Call = ImplicitCastExpr::Create( 14619 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14620 nullptr, VK_RValue, CurFPFeatureOverrides()); 14621 14622 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14623 } 14624 14625 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14626 14627 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14628 // that calls this method, using Object for the implicit object 14629 // parameter and passing along the remaining arguments. 14630 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14631 14632 // An error diagnostic has already been printed when parsing the declaration. 14633 if (Method->isInvalidDecl()) 14634 return ExprError(); 14635 14636 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14637 unsigned NumParams = Proto->getNumParams(); 14638 14639 DeclarationNameInfo OpLocInfo( 14640 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14641 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14642 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14643 Obj, HadMultipleCandidates, 14644 OpLocInfo.getLoc(), 14645 OpLocInfo.getInfo()); 14646 if (NewFn.isInvalid()) 14647 return true; 14648 14649 // The number of argument slots to allocate in the call. If we have default 14650 // arguments we need to allocate space for them as well. We additionally 14651 // need one more slot for the object parameter. 14652 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14653 14654 // Build the full argument list for the method call (the implicit object 14655 // parameter is placed at the beginning of the list). 14656 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14657 14658 bool IsError = false; 14659 14660 // Initialize the implicit object parameter. 14661 ExprResult ObjRes = 14662 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14663 Best->FoundDecl, Method); 14664 if (ObjRes.isInvalid()) 14665 IsError = true; 14666 else 14667 Object = ObjRes; 14668 MethodArgs[0] = Object.get(); 14669 14670 // Check the argument types. 14671 for (unsigned i = 0; i != NumParams; i++) { 14672 Expr *Arg; 14673 if (i < Args.size()) { 14674 Arg = Args[i]; 14675 14676 // Pass the argument. 14677 14678 ExprResult InputInit 14679 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14680 Context, 14681 Method->getParamDecl(i)), 14682 SourceLocation(), Arg); 14683 14684 IsError |= InputInit.isInvalid(); 14685 Arg = InputInit.getAs<Expr>(); 14686 } else { 14687 ExprResult DefArg 14688 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14689 if (DefArg.isInvalid()) { 14690 IsError = true; 14691 break; 14692 } 14693 14694 Arg = DefArg.getAs<Expr>(); 14695 } 14696 14697 MethodArgs[i + 1] = Arg; 14698 } 14699 14700 // If this is a variadic call, handle args passed through "...". 14701 if (Proto->isVariadic()) { 14702 // Promote the arguments (C99 6.5.2.2p7). 14703 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14704 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14705 nullptr); 14706 IsError |= Arg.isInvalid(); 14707 MethodArgs[i + 1] = Arg.get(); 14708 } 14709 } 14710 14711 if (IsError) 14712 return true; 14713 14714 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14715 14716 // Once we've built TheCall, all of the expressions are properly owned. 14717 QualType ResultTy = Method->getReturnType(); 14718 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14719 ResultTy = ResultTy.getNonLValueExprType(Context); 14720 14721 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14722 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14723 CurFPFeatureOverrides()); 14724 14725 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14726 return true; 14727 14728 if (CheckFunctionCall(Method, TheCall, Proto)) 14729 return true; 14730 14731 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14732 } 14733 14734 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14735 /// (if one exists), where @c Base is an expression of class type and 14736 /// @c Member is the name of the member we're trying to find. 14737 ExprResult 14738 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14739 bool *NoArrowOperatorFound) { 14740 assert(Base->getType()->isRecordType() && 14741 "left-hand side must have class type"); 14742 14743 if (checkPlaceholderForOverload(*this, Base)) 14744 return ExprError(); 14745 14746 SourceLocation Loc = Base->getExprLoc(); 14747 14748 // C++ [over.ref]p1: 14749 // 14750 // [...] An expression x->m is interpreted as (x.operator->())->m 14751 // for a class object x of type T if T::operator->() exists and if 14752 // the operator is selected as the best match function by the 14753 // overload resolution mechanism (13.3). 14754 DeclarationName OpName = 14755 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14756 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14757 14758 if (RequireCompleteType(Loc, Base->getType(), 14759 diag::err_typecheck_incomplete_tag, Base)) 14760 return ExprError(); 14761 14762 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14763 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14764 R.suppressDiagnostics(); 14765 14766 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14767 Oper != OperEnd; ++Oper) { 14768 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14769 None, CandidateSet, /*SuppressUserConversion=*/false); 14770 } 14771 14772 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14773 14774 // Perform overload resolution. 14775 OverloadCandidateSet::iterator Best; 14776 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14777 case OR_Success: 14778 // Overload resolution succeeded; we'll build the call below. 14779 break; 14780 14781 case OR_No_Viable_Function: { 14782 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14783 if (CandidateSet.empty()) { 14784 QualType BaseType = Base->getType(); 14785 if (NoArrowOperatorFound) { 14786 // Report this specific error to the caller instead of emitting a 14787 // diagnostic, as requested. 14788 *NoArrowOperatorFound = true; 14789 return ExprError(); 14790 } 14791 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14792 << BaseType << Base->getSourceRange(); 14793 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14794 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14795 << FixItHint::CreateReplacement(OpLoc, "."); 14796 } 14797 } else 14798 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14799 << "operator->" << Base->getSourceRange(); 14800 CandidateSet.NoteCandidates(*this, Base, Cands); 14801 return ExprError(); 14802 } 14803 case OR_Ambiguous: 14804 CandidateSet.NoteCandidates( 14805 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14806 << "->" << Base->getType() 14807 << Base->getSourceRange()), 14808 *this, OCD_AmbiguousCandidates, Base); 14809 return ExprError(); 14810 14811 case OR_Deleted: 14812 CandidateSet.NoteCandidates( 14813 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14814 << "->" << Base->getSourceRange()), 14815 *this, OCD_AllCandidates, Base); 14816 return ExprError(); 14817 } 14818 14819 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14820 14821 // Convert the object parameter. 14822 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14823 ExprResult BaseResult = 14824 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14825 Best->FoundDecl, Method); 14826 if (BaseResult.isInvalid()) 14827 return ExprError(); 14828 Base = BaseResult.get(); 14829 14830 // Build the operator call. 14831 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14832 Base, HadMultipleCandidates, OpLoc); 14833 if (FnExpr.isInvalid()) 14834 return ExprError(); 14835 14836 QualType ResultTy = Method->getReturnType(); 14837 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14838 ResultTy = ResultTy.getNonLValueExprType(Context); 14839 CXXOperatorCallExpr *TheCall = 14840 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14841 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14842 14843 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14844 return ExprError(); 14845 14846 if (CheckFunctionCall(Method, TheCall, 14847 Method->getType()->castAs<FunctionProtoType>())) 14848 return ExprError(); 14849 14850 return MaybeBindToTemporary(TheCall); 14851 } 14852 14853 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14854 /// a literal operator described by the provided lookup results. 14855 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14856 DeclarationNameInfo &SuffixInfo, 14857 ArrayRef<Expr*> Args, 14858 SourceLocation LitEndLoc, 14859 TemplateArgumentListInfo *TemplateArgs) { 14860 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14861 14862 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14863 OverloadCandidateSet::CSK_Normal); 14864 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14865 TemplateArgs); 14866 14867 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14868 14869 // Perform overload resolution. This will usually be trivial, but might need 14870 // to perform substitutions for a literal operator template. 14871 OverloadCandidateSet::iterator Best; 14872 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14873 case OR_Success: 14874 case OR_Deleted: 14875 break; 14876 14877 case OR_No_Viable_Function: 14878 CandidateSet.NoteCandidates( 14879 PartialDiagnosticAt(UDSuffixLoc, 14880 PDiag(diag::err_ovl_no_viable_function_in_call) 14881 << R.getLookupName()), 14882 *this, OCD_AllCandidates, Args); 14883 return ExprError(); 14884 14885 case OR_Ambiguous: 14886 CandidateSet.NoteCandidates( 14887 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14888 << R.getLookupName()), 14889 *this, OCD_AmbiguousCandidates, Args); 14890 return ExprError(); 14891 } 14892 14893 FunctionDecl *FD = Best->Function; 14894 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14895 nullptr, HadMultipleCandidates, 14896 SuffixInfo.getLoc(), 14897 SuffixInfo.getInfo()); 14898 if (Fn.isInvalid()) 14899 return true; 14900 14901 // Check the argument types. This should almost always be a no-op, except 14902 // that array-to-pointer decay is applied to string literals. 14903 Expr *ConvArgs[2]; 14904 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14905 ExprResult InputInit = PerformCopyInitialization( 14906 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14907 SourceLocation(), Args[ArgIdx]); 14908 if (InputInit.isInvalid()) 14909 return true; 14910 ConvArgs[ArgIdx] = InputInit.get(); 14911 } 14912 14913 QualType ResultTy = FD->getReturnType(); 14914 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14915 ResultTy = ResultTy.getNonLValueExprType(Context); 14916 14917 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14918 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14919 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14920 14921 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14922 return ExprError(); 14923 14924 if (CheckFunctionCall(FD, UDL, nullptr)) 14925 return ExprError(); 14926 14927 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14928 } 14929 14930 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14931 /// given LookupResult is non-empty, it is assumed to describe a member which 14932 /// will be invoked. Otherwise, the function will be found via argument 14933 /// dependent lookup. 14934 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14935 /// otherwise CallExpr is set to ExprError() and some non-success value 14936 /// is returned. 14937 Sema::ForRangeStatus 14938 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14939 SourceLocation RangeLoc, 14940 const DeclarationNameInfo &NameInfo, 14941 LookupResult &MemberLookup, 14942 OverloadCandidateSet *CandidateSet, 14943 Expr *Range, ExprResult *CallExpr) { 14944 Scope *S = nullptr; 14945 14946 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14947 if (!MemberLookup.empty()) { 14948 ExprResult MemberRef = 14949 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14950 /*IsPtr=*/false, CXXScopeSpec(), 14951 /*TemplateKWLoc=*/SourceLocation(), 14952 /*FirstQualifierInScope=*/nullptr, 14953 MemberLookup, 14954 /*TemplateArgs=*/nullptr, S); 14955 if (MemberRef.isInvalid()) { 14956 *CallExpr = ExprError(); 14957 return FRS_DiagnosticIssued; 14958 } 14959 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14960 if (CallExpr->isInvalid()) { 14961 *CallExpr = ExprError(); 14962 return FRS_DiagnosticIssued; 14963 } 14964 } else { 14965 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14966 NestedNameSpecifierLoc(), 14967 NameInfo, UnresolvedSet<0>()); 14968 if (FnR.isInvalid()) 14969 return FRS_DiagnosticIssued; 14970 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14971 14972 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14973 CandidateSet, CallExpr); 14974 if (CandidateSet->empty() || CandidateSetError) { 14975 *CallExpr = ExprError(); 14976 return FRS_NoViableFunction; 14977 } 14978 OverloadCandidateSet::iterator Best; 14979 OverloadingResult OverloadResult = 14980 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14981 14982 if (OverloadResult == OR_No_Viable_Function) { 14983 *CallExpr = ExprError(); 14984 return FRS_NoViableFunction; 14985 } 14986 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14987 Loc, nullptr, CandidateSet, &Best, 14988 OverloadResult, 14989 /*AllowTypoCorrection=*/false); 14990 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14991 *CallExpr = ExprError(); 14992 return FRS_DiagnosticIssued; 14993 } 14994 } 14995 return FRS_Success; 14996 } 14997 14998 14999 /// FixOverloadedFunctionReference - E is an expression that refers to 15000 /// a C++ overloaded function (possibly with some parentheses and 15001 /// perhaps a '&' around it). We have resolved the overloaded function 15002 /// to the function declaration Fn, so patch up the expression E to 15003 /// refer (possibly indirectly) to Fn. Returns the new expr. 15004 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15005 FunctionDecl *Fn) { 15006 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15007 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15008 Found, Fn); 15009 if (SubExpr == PE->getSubExpr()) 15010 return PE; 15011 15012 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15013 } 15014 15015 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15016 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15017 Found, Fn); 15018 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15019 SubExpr->getType()) && 15020 "Implicit cast type cannot be determined from overload"); 15021 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15022 if (SubExpr == ICE->getSubExpr()) 15023 return ICE; 15024 15025 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15026 SubExpr, nullptr, ICE->getValueKind(), 15027 CurFPFeatureOverrides()); 15028 } 15029 15030 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15031 if (!GSE->isResultDependent()) { 15032 Expr *SubExpr = 15033 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15034 if (SubExpr == GSE->getResultExpr()) 15035 return GSE; 15036 15037 // Replace the resulting type information before rebuilding the generic 15038 // selection expression. 15039 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15040 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15041 unsigned ResultIdx = GSE->getResultIndex(); 15042 AssocExprs[ResultIdx] = SubExpr; 15043 15044 return GenericSelectionExpr::Create( 15045 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15046 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15047 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15048 ResultIdx); 15049 } 15050 // Rather than fall through to the unreachable, return the original generic 15051 // selection expression. 15052 return GSE; 15053 } 15054 15055 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15056 assert(UnOp->getOpcode() == UO_AddrOf && 15057 "Can only take the address of an overloaded function"); 15058 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15059 if (Method->isStatic()) { 15060 // Do nothing: static member functions aren't any different 15061 // from non-member functions. 15062 } else { 15063 // Fix the subexpression, which really has to be an 15064 // UnresolvedLookupExpr holding an overloaded member function 15065 // or template. 15066 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15067 Found, Fn); 15068 if (SubExpr == UnOp->getSubExpr()) 15069 return UnOp; 15070 15071 assert(isa<DeclRefExpr>(SubExpr) 15072 && "fixed to something other than a decl ref"); 15073 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15074 && "fixed to a member ref with no nested name qualifier"); 15075 15076 // We have taken the address of a pointer to member 15077 // function. Perform the computation here so that we get the 15078 // appropriate pointer to member type. 15079 QualType ClassType 15080 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15081 QualType MemPtrType 15082 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15083 // Under the MS ABI, lock down the inheritance model now. 15084 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15085 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15086 15087 return UnaryOperator::Create( 15088 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 15089 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15090 } 15091 } 15092 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15093 Found, Fn); 15094 if (SubExpr == UnOp->getSubExpr()) 15095 return UnOp; 15096 15097 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf, 15098 Context.getPointerType(SubExpr->getType()), 15099 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), 15100 false, CurFPFeatureOverrides()); 15101 } 15102 15103 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15104 // FIXME: avoid copy. 15105 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15106 if (ULE->hasExplicitTemplateArgs()) { 15107 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15108 TemplateArgs = &TemplateArgsBuffer; 15109 } 15110 15111 DeclRefExpr *DRE = 15112 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15113 ULE->getQualifierLoc(), Found.getDecl(), 15114 ULE->getTemplateKeywordLoc(), TemplateArgs); 15115 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15116 return DRE; 15117 } 15118 15119 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15120 // FIXME: avoid copy. 15121 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15122 if (MemExpr->hasExplicitTemplateArgs()) { 15123 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15124 TemplateArgs = &TemplateArgsBuffer; 15125 } 15126 15127 Expr *Base; 15128 15129 // If we're filling in a static method where we used to have an 15130 // implicit member access, rewrite to a simple decl ref. 15131 if (MemExpr->isImplicitAccess()) { 15132 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15133 DeclRefExpr *DRE = BuildDeclRefExpr( 15134 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15135 MemExpr->getQualifierLoc(), Found.getDecl(), 15136 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15137 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15138 return DRE; 15139 } else { 15140 SourceLocation Loc = MemExpr->getMemberLoc(); 15141 if (MemExpr->getQualifier()) 15142 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15143 Base = 15144 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15145 } 15146 } else 15147 Base = MemExpr->getBase(); 15148 15149 ExprValueKind valueKind; 15150 QualType type; 15151 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15152 valueKind = VK_LValue; 15153 type = Fn->getType(); 15154 } else { 15155 valueKind = VK_RValue; 15156 type = Context.BoundMemberTy; 15157 } 15158 15159 return BuildMemberExpr( 15160 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15161 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15162 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15163 type, valueKind, OK_Ordinary, TemplateArgs); 15164 } 15165 15166 llvm_unreachable("Invalid reference to overloaded function"); 15167 } 15168 15169 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15170 DeclAccessPair Found, 15171 FunctionDecl *Fn) { 15172 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15173 } 15174