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_OCL_Scalar_Widening, 141 ICR_Complex_Real_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Writeback_Conversion, 145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 146 // it was omitted by the patch that added 147 // ICK_Zero_Event_Conversion 148 ICR_C_Conversion, 149 ICR_C_Conversion_Extension 150 }; 151 return Rank[(int)Kind]; 152 } 153 154 /// GetImplicitConversionName - Return the name of this kind of 155 /// implicit conversion. 156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 158 "No conversion", 159 "Lvalue-to-rvalue", 160 "Array-to-pointer", 161 "Function-to-pointer", 162 "Function pointer conversion", 163 "Qualification", 164 "Integral promotion", 165 "Floating point promotion", 166 "Complex promotion", 167 "Integral conversion", 168 "Floating conversion", 169 "Complex conversion", 170 "Floating-integral conversion", 171 "Pointer conversion", 172 "Pointer-to-member conversion", 173 "Boolean conversion", 174 "Compatible-types conversion", 175 "Derived-to-base conversion", 176 "Vector conversion", 177 "Vector splat", 178 "Complex-real conversion", 179 "Block Pointer conversion", 180 "Transparent Union Conversion", 181 "Writeback conversion", 182 "OpenCL Zero Event Conversion", 183 "C specific type conversion", 184 "Incompatible pointer conversion" 185 }; 186 return Name[Kind]; 187 } 188 189 /// StandardConversionSequence - Set the standard conversion 190 /// sequence to the identity conversion. 191 void StandardConversionSequence::setAsIdentityConversion() { 192 First = ICK_Identity; 193 Second = ICK_Identity; 194 Third = ICK_Identity; 195 DeprecatedStringLiteralToCharPtr = false; 196 QualificationIncludesObjCLifetime = false; 197 ReferenceBinding = false; 198 DirectBinding = false; 199 IsLvalueReference = true; 200 BindsToFunctionLvalue = false; 201 BindsToRvalue = false; 202 BindsImplicitObjectArgumentWithoutRefQualifier = false; 203 ObjCLifetimeConversionBinding = false; 204 CopyConstructor = nullptr; 205 } 206 207 /// getRank - Retrieve the rank of this standard conversion sequence 208 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 209 /// implicit conversions. 210 ImplicitConversionRank StandardConversionSequence::getRank() const { 211 ImplicitConversionRank Rank = ICR_Exact_Match; 212 if (GetConversionRank(First) > Rank) 213 Rank = GetConversionRank(First); 214 if (GetConversionRank(Second) > Rank) 215 Rank = GetConversionRank(Second); 216 if (GetConversionRank(Third) > Rank) 217 Rank = GetConversionRank(Third); 218 return Rank; 219 } 220 221 /// isPointerConversionToBool - Determines whether this conversion is 222 /// a conversion of a pointer or pointer-to-member to bool. This is 223 /// used as part of the ranking of standard conversion sequences 224 /// (C++ 13.3.3.2p4). 225 bool StandardConversionSequence::isPointerConversionToBool() const { 226 // Note that FromType has not necessarily been transformed by the 227 // array-to-pointer or function-to-pointer implicit conversions, so 228 // check for their presence as well as checking whether FromType is 229 // a pointer. 230 if (getToType(1)->isBooleanType() && 231 (getFromType()->isPointerType() || 232 getFromType()->isMemberPointerType() || 233 getFromType()->isObjCObjectPointerType() || 234 getFromType()->isBlockPointerType() || 235 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 236 return true; 237 238 return false; 239 } 240 241 /// isPointerConversionToVoidPointer - Determines whether this 242 /// conversion is a conversion of a pointer to a void pointer. This is 243 /// used as part of the ranking of standard conversion sequences (C++ 244 /// 13.3.3.2p4). 245 bool 246 StandardConversionSequence:: 247 isPointerConversionToVoidPointer(ASTContext& Context) const { 248 QualType FromType = getFromType(); 249 QualType ToType = getToType(1); 250 251 // Note that FromType has not necessarily been transformed by the 252 // array-to-pointer implicit conversion, so check for its presence 253 // and redo the conversion to get a pointer. 254 if (First == ICK_Array_To_Pointer) 255 FromType = Context.getArrayDecayedType(FromType); 256 257 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 258 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 259 return ToPtrType->getPointeeType()->isVoidType(); 260 261 return false; 262 } 263 264 /// Skip any implicit casts which could be either part of a narrowing conversion 265 /// or after one in an implicit conversion. 266 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 267 const Expr *Converted) { 268 // We can have cleanups wrapping the converted expression; these need to be 269 // preserved so that destructors run if necessary. 270 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 271 Expr *Inner = 272 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 273 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 274 EWC->getObjects()); 275 } 276 277 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 278 switch (ICE->getCastKind()) { 279 case CK_NoOp: 280 case CK_IntegralCast: 281 case CK_IntegralToBoolean: 282 case CK_IntegralToFloating: 283 case CK_BooleanToSignedIntegral: 284 case CK_FloatingToIntegral: 285 case CK_FloatingToBoolean: 286 case CK_FloatingCast: 287 Converted = ICE->getSubExpr(); 288 continue; 289 290 default: 291 return Converted; 292 } 293 } 294 295 return Converted; 296 } 297 298 /// Check if this standard conversion sequence represents a narrowing 299 /// conversion, according to C++11 [dcl.init.list]p7. 300 /// 301 /// \param Ctx The AST context. 302 /// \param Converted The result of applying this standard conversion sequence. 303 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 304 /// value of the expression prior to the narrowing conversion. 305 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 306 /// type of the expression prior to the narrowing conversion. 307 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 308 /// from floating point types to integral types should be ignored. 309 NarrowingKind StandardConversionSequence::getNarrowingKind( 310 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 311 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 312 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 313 314 // C++11 [dcl.init.list]p7: 315 // A narrowing conversion is an implicit conversion ... 316 QualType FromType = getToType(0); 317 QualType ToType = getToType(1); 318 319 // A conversion to an enumeration type is narrowing if the conversion to 320 // the underlying type is narrowing. This only arises for expressions of 321 // the form 'Enum{init}'. 322 if (auto *ET = ToType->getAs<EnumType>()) 323 ToType = ET->getDecl()->getIntegerType(); 324 325 switch (Second) { 326 // 'bool' is an integral type; dispatch to the right place to handle it. 327 case ICK_Boolean_Conversion: 328 if (FromType->isRealFloatingType()) 329 goto FloatingIntegralConversion; 330 if (FromType->isIntegralOrUnscopedEnumerationType()) 331 goto IntegralConversion; 332 // -- from a pointer type or pointer-to-member type to bool, or 333 return NK_Type_Narrowing; 334 335 // -- from a floating-point type to an integer type, or 336 // 337 // -- from an integer type or unscoped enumeration type to a floating-point 338 // type, except where the source is a constant expression and the actual 339 // value after conversion will fit into the target type and will produce 340 // the original value when converted back to the original type, or 341 case ICK_Floating_Integral: 342 FloatingIntegralConversion: 343 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 344 return NK_Type_Narrowing; 345 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 346 ToType->isRealFloatingType()) { 347 if (IgnoreFloatToIntegralConversion) 348 return NK_Not_Narrowing; 349 llvm::APSInt IntConstantValue; 350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 351 assert(Initializer && "Unknown conversion expression"); 352 353 // If it's value-dependent, we can't tell whether it's narrowing. 354 if (Initializer->isValueDependent()) 355 return NK_Dependent_Narrowing; 356 357 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 358 // Convert the integer to the floating type. 359 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 360 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 361 llvm::APFloat::rmNearestTiesToEven); 362 // And back. 363 llvm::APSInt ConvertedValue = IntConstantValue; 364 bool ignored; 365 Result.convertToInteger(ConvertedValue, 366 llvm::APFloat::rmTowardZero, &ignored); 367 // If the resulting value is different, this was a narrowing conversion. 368 if (IntConstantValue != ConvertedValue) { 369 ConstantValue = APValue(IntConstantValue); 370 ConstantType = Initializer->getType(); 371 return NK_Constant_Narrowing; 372 } 373 } else { 374 // Variables are always narrowings. 375 return NK_Variable_Narrowing; 376 } 377 } 378 return NK_Not_Narrowing; 379 380 // -- from long double to double or float, or from double to float, except 381 // where the source is a constant expression and the actual value after 382 // conversion is within the range of values that can be represented (even 383 // if it cannot be represented exactly), or 384 case ICK_Floating_Conversion: 385 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 386 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 387 // FromType is larger than ToType. 388 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 389 390 // If it's value-dependent, we can't tell whether it's narrowing. 391 if (Initializer->isValueDependent()) 392 return NK_Dependent_Narrowing; 393 394 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 395 // Constant! 396 assert(ConstantValue.isFloat()); 397 llvm::APFloat FloatVal = ConstantValue.getFloat(); 398 // Convert the source value into the target type. 399 bool ignored; 400 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 401 Ctx.getFloatTypeSemantics(ToType), 402 llvm::APFloat::rmNearestTiesToEven, &ignored); 403 // If there was no overflow, the source value is within the range of 404 // values that can be represented. 405 if (ConvertStatus & llvm::APFloat::opOverflow) { 406 ConstantType = Initializer->getType(); 407 return NK_Constant_Narrowing; 408 } 409 } else { 410 return NK_Variable_Narrowing; 411 } 412 } 413 return NK_Not_Narrowing; 414 415 // -- from an integer type or unscoped enumeration type to an integer type 416 // that cannot represent all the values of the original type, except where 417 // the source is a constant expression and the actual value after 418 // conversion will fit into the target type and will produce the original 419 // value when converted back to the original type. 420 case ICK_Integral_Conversion: 421 IntegralConversion: { 422 assert(FromType->isIntegralOrUnscopedEnumerationType()); 423 assert(ToType->isIntegralOrUnscopedEnumerationType()); 424 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 425 const unsigned FromWidth = Ctx.getIntWidth(FromType); 426 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 427 const unsigned ToWidth = Ctx.getIntWidth(ToType); 428 429 if (FromWidth > ToWidth || 430 (FromWidth == ToWidth && FromSigned != ToSigned) || 431 (FromSigned && !ToSigned)) { 432 // Not all values of FromType can be represented in ToType. 433 llvm::APSInt InitializerValue; 434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 435 436 // If it's value-dependent, we can't tell whether it's narrowing. 437 if (Initializer->isValueDependent()) 438 return NK_Dependent_Narrowing; 439 440 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 441 // Such conversions on variables are always narrowing. 442 return NK_Variable_Narrowing; 443 } 444 bool Narrowing = false; 445 if (FromWidth < ToWidth) { 446 // Negative -> unsigned is narrowing. Otherwise, more bits is never 447 // narrowing. 448 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 449 Narrowing = true; 450 } else { 451 // Add a bit to the InitializerValue so we don't have to worry about 452 // signed vs. unsigned comparisons. 453 InitializerValue = InitializerValue.extend( 454 InitializerValue.getBitWidth() + 1); 455 // Convert the initializer to and from the target width and signed-ness. 456 llvm::APSInt ConvertedValue = InitializerValue; 457 ConvertedValue = ConvertedValue.trunc(ToWidth); 458 ConvertedValue.setIsSigned(ToSigned); 459 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 460 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 461 // If the result is different, this was a narrowing conversion. 462 if (ConvertedValue != InitializerValue) 463 Narrowing = true; 464 } 465 if (Narrowing) { 466 ConstantType = Initializer->getType(); 467 ConstantValue = APValue(InitializerValue); 468 return NK_Constant_Narrowing; 469 } 470 } 471 return NK_Not_Narrowing; 472 } 473 474 default: 475 // Other kinds of conversions are not narrowings. 476 return NK_Not_Narrowing; 477 } 478 } 479 480 /// dump - Print this standard conversion sequence to standard 481 /// error. Useful for debugging overloading issues. 482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 483 raw_ostream &OS = llvm::errs(); 484 bool PrintedSomething = false; 485 if (First != ICK_Identity) { 486 OS << GetImplicitConversionName(First); 487 PrintedSomething = true; 488 } 489 490 if (Second != ICK_Identity) { 491 if (PrintedSomething) { 492 OS << " -> "; 493 } 494 OS << GetImplicitConversionName(Second); 495 496 if (CopyConstructor) { 497 OS << " (by copy constructor)"; 498 } else if (DirectBinding) { 499 OS << " (direct reference binding)"; 500 } else if (ReferenceBinding) { 501 OS << " (reference binding)"; 502 } 503 PrintedSomething = true; 504 } 505 506 if (Third != ICK_Identity) { 507 if (PrintedSomething) { 508 OS << " -> "; 509 } 510 OS << GetImplicitConversionName(Third); 511 PrintedSomething = true; 512 } 513 514 if (!PrintedSomething) { 515 OS << "No conversions required"; 516 } 517 } 518 519 /// dump - Print this user-defined conversion sequence to standard 520 /// error. Useful for debugging overloading issues. 521 void UserDefinedConversionSequence::dump() const { 522 raw_ostream &OS = llvm::errs(); 523 if (Before.First || Before.Second || Before.Third) { 524 Before.dump(); 525 OS << " -> "; 526 } 527 if (ConversionFunction) 528 OS << '\'' << *ConversionFunction << '\''; 529 else 530 OS << "aggregate initialization"; 531 if (After.First || After.Second || After.Third) { 532 OS << " -> "; 533 After.dump(); 534 } 535 } 536 537 /// dump - Print this implicit conversion sequence to standard 538 /// error. Useful for debugging overloading issues. 539 void ImplicitConversionSequence::dump() const { 540 raw_ostream &OS = llvm::errs(); 541 if (isStdInitializerListElement()) 542 OS << "Worst std::initializer_list element conversion: "; 543 switch (ConversionKind) { 544 case StandardConversion: 545 OS << "Standard conversion: "; 546 Standard.dump(); 547 break; 548 case UserDefinedConversion: 549 OS << "User-defined conversion: "; 550 UserDefined.dump(); 551 break; 552 case EllipsisConversion: 553 OS << "Ellipsis conversion"; 554 break; 555 case AmbiguousConversion: 556 OS << "Ambiguous conversion"; 557 break; 558 case BadConversion: 559 OS << "Bad conversion"; 560 break; 561 } 562 563 OS << "\n"; 564 } 565 566 void AmbiguousConversionSequence::construct() { 567 new (&conversions()) ConversionSet(); 568 } 569 570 void AmbiguousConversionSequence::destruct() { 571 conversions().~ConversionSet(); 572 } 573 574 void 575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 576 FromTypePtr = O.FromTypePtr; 577 ToTypePtr = O.ToTypePtr; 578 new (&conversions()) ConversionSet(O.conversions()); 579 } 580 581 namespace { 582 // Structure used by DeductionFailureInfo to store 583 // template argument information. 584 struct DFIArguments { 585 TemplateArgument FirstArg; 586 TemplateArgument SecondArg; 587 }; 588 // Structure used by DeductionFailureInfo to store 589 // template parameter and template argument information. 590 struct DFIParamWithArguments : DFIArguments { 591 TemplateParameter Param; 592 }; 593 // Structure used by DeductionFailureInfo to store template argument 594 // information and the index of the problematic call argument. 595 struct DFIDeducedMismatchArgs : DFIArguments { 596 TemplateArgumentList *TemplateArgs; 597 unsigned CallArgIndex; 598 }; 599 // Structure used by DeductionFailureInfo to store information about 600 // unsatisfied constraints. 601 struct CNSInfo { 602 TemplateArgumentList *TemplateArgs; 603 ConstraintSatisfaction Satisfaction; 604 }; 605 } 606 607 /// Convert from Sema's representation of template deduction information 608 /// to the form used in overload-candidate information. 609 DeductionFailureInfo 610 clang::MakeDeductionFailureInfo(ASTContext &Context, 611 Sema::TemplateDeductionResult TDK, 612 TemplateDeductionInfo &Info) { 613 DeductionFailureInfo Result; 614 Result.Result = static_cast<unsigned>(TDK); 615 Result.HasDiagnostic = false; 616 switch (TDK) { 617 case Sema::TDK_Invalid: 618 case Sema::TDK_InstantiationDepth: 619 case Sema::TDK_TooManyArguments: 620 case Sema::TDK_TooFewArguments: 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 case Sema::TDK_CUDATargetMismatch: 623 Result.Data = nullptr; 624 break; 625 626 case Sema::TDK_Incomplete: 627 case Sema::TDK_InvalidExplicitArguments: 628 Result.Data = Info.Param.getOpaqueValue(); 629 break; 630 631 case Sema::TDK_DeducedMismatch: 632 case Sema::TDK_DeducedMismatchNested: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 auto *Saved = new (Context) DFIDeducedMismatchArgs; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Saved->TemplateArgs = Info.take(); 638 Saved->CallArgIndex = Info.CallArgIndex; 639 Result.Data = Saved; 640 break; 641 } 642 643 case Sema::TDK_NonDeducedMismatch: { 644 // FIXME: Should allocate from normal heap so that we can free this later. 645 DFIArguments *Saved = new (Context) DFIArguments; 646 Saved->FirstArg = Info.FirstArg; 647 Saved->SecondArg = Info.SecondArg; 648 Result.Data = Saved; 649 break; 650 } 651 652 case Sema::TDK_IncompletePack: 653 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: { 656 // FIXME: Should allocate from normal heap so that we can free this later. 657 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 658 Saved->Param = Info.Param; 659 Saved->FirstArg = Info.FirstArg; 660 Saved->SecondArg = Info.SecondArg; 661 Result.Data = Saved; 662 break; 663 } 664 665 case Sema::TDK_SubstitutionFailure: 666 Result.Data = Info.take(); 667 if (Info.hasSFINAEDiagnostic()) { 668 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 669 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 670 Info.takeSFINAEDiagnostic(*Diag); 671 Result.HasDiagnostic = true; 672 } 673 break; 674 675 case Sema::TDK_ConstraintsNotSatisfied: { 676 CNSInfo *Saved = new (Context) CNSInfo; 677 Saved->TemplateArgs = Info.take(); 678 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 679 Result.Data = Saved; 680 break; 681 } 682 683 case Sema::TDK_Success: 684 case Sema::TDK_NonDependentConversionFailure: 685 llvm_unreachable("not a deduction failure"); 686 } 687 688 return Result; 689 } 690 691 void DeductionFailureInfo::Destroy() { 692 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 693 case Sema::TDK_Success: 694 case Sema::TDK_Invalid: 695 case Sema::TDK_InstantiationDepth: 696 case Sema::TDK_Incomplete: 697 case Sema::TDK_TooManyArguments: 698 case Sema::TDK_TooFewArguments: 699 case Sema::TDK_InvalidExplicitArguments: 700 case Sema::TDK_CUDATargetMismatch: 701 case Sema::TDK_NonDependentConversionFailure: 702 break; 703 704 case Sema::TDK_IncompletePack: 705 case Sema::TDK_Inconsistent: 706 case Sema::TDK_Underqualified: 707 case Sema::TDK_DeducedMismatch: 708 case Sema::TDK_DeducedMismatchNested: 709 case Sema::TDK_NonDeducedMismatch: 710 // FIXME: Destroy the data? 711 Data = nullptr; 712 break; 713 714 case Sema::TDK_SubstitutionFailure: 715 // FIXME: Destroy the template argument list? 716 Data = nullptr; 717 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 718 Diag->~PartialDiagnosticAt(); 719 HasDiagnostic = false; 720 } 721 break; 722 723 case Sema::TDK_ConstraintsNotSatisfied: 724 // FIXME: Destroy the template argument list? 725 Data = nullptr; 726 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 727 Diag->~PartialDiagnosticAt(); 728 HasDiagnostic = false; 729 } 730 break; 731 732 // Unhandled 733 case Sema::TDK_MiscellaneousDeductionFailure: 734 break; 735 } 736 } 737 738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 739 if (HasDiagnostic) 740 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 741 return nullptr; 742 } 743 744 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 745 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 746 case Sema::TDK_Success: 747 case Sema::TDK_Invalid: 748 case Sema::TDK_InstantiationDepth: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_SubstitutionFailure: 752 case Sema::TDK_DeducedMismatch: 753 case Sema::TDK_DeducedMismatchNested: 754 case Sema::TDK_NonDeducedMismatch: 755 case Sema::TDK_CUDATargetMismatch: 756 case Sema::TDK_NonDependentConversionFailure: 757 case Sema::TDK_ConstraintsNotSatisfied: 758 return TemplateParameter(); 759 760 case Sema::TDK_Incomplete: 761 case Sema::TDK_InvalidExplicitArguments: 762 return TemplateParameter::getFromOpaqueValue(Data); 763 764 case Sema::TDK_IncompletePack: 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 return static_cast<DFIParamWithArguments*>(Data)->Param; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return TemplateParameter(); 775 } 776 777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 778 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 779 case Sema::TDK_Success: 780 case Sema::TDK_Invalid: 781 case Sema::TDK_InstantiationDepth: 782 case Sema::TDK_TooManyArguments: 783 case Sema::TDK_TooFewArguments: 784 case Sema::TDK_Incomplete: 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_InvalidExplicitArguments: 787 case Sema::TDK_Inconsistent: 788 case Sema::TDK_Underqualified: 789 case Sema::TDK_NonDeducedMismatch: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_DeducedMismatch: 795 case Sema::TDK_DeducedMismatchNested: 796 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 797 798 case Sema::TDK_SubstitutionFailure: 799 return static_cast<TemplateArgumentList*>(Data); 800 801 case Sema::TDK_ConstraintsNotSatisfied: 802 return static_cast<CNSInfo*>(Data)->TemplateArgs; 803 804 // Unhandled 805 case Sema::TDK_MiscellaneousDeductionFailure: 806 break; 807 } 808 809 return nullptr; 810 } 811 812 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 813 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 814 case Sema::TDK_Success: 815 case Sema::TDK_Invalid: 816 case Sema::TDK_InstantiationDepth: 817 case Sema::TDK_Incomplete: 818 case Sema::TDK_TooManyArguments: 819 case Sema::TDK_TooFewArguments: 820 case Sema::TDK_InvalidExplicitArguments: 821 case Sema::TDK_SubstitutionFailure: 822 case Sema::TDK_CUDATargetMismatch: 823 case Sema::TDK_NonDependentConversionFailure: 824 case Sema::TDK_ConstraintsNotSatisfied: 825 return nullptr; 826 827 case Sema::TDK_IncompletePack: 828 case Sema::TDK_Inconsistent: 829 case Sema::TDK_Underqualified: 830 case Sema::TDK_DeducedMismatch: 831 case Sema::TDK_DeducedMismatchNested: 832 case Sema::TDK_NonDeducedMismatch: 833 return &static_cast<DFIArguments*>(Data)->FirstArg; 834 835 // Unhandled 836 case Sema::TDK_MiscellaneousDeductionFailure: 837 break; 838 } 839 840 return nullptr; 841 } 842 843 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 844 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 845 case Sema::TDK_Success: 846 case Sema::TDK_Invalid: 847 case Sema::TDK_InstantiationDepth: 848 case Sema::TDK_Incomplete: 849 case Sema::TDK_IncompletePack: 850 case Sema::TDK_TooManyArguments: 851 case Sema::TDK_TooFewArguments: 852 case Sema::TDK_InvalidExplicitArguments: 853 case Sema::TDK_SubstitutionFailure: 854 case Sema::TDK_CUDATargetMismatch: 855 case Sema::TDK_NonDependentConversionFailure: 856 case Sema::TDK_ConstraintsNotSatisfied: 857 return nullptr; 858 859 case Sema::TDK_Inconsistent: 860 case Sema::TDK_Underqualified: 861 case Sema::TDK_DeducedMismatch: 862 case Sema::TDK_DeducedMismatchNested: 863 case Sema::TDK_NonDeducedMismatch: 864 return &static_cast<DFIArguments*>(Data)->SecondArg; 865 866 // Unhandled 867 case Sema::TDK_MiscellaneousDeductionFailure: 868 break; 869 } 870 871 return nullptr; 872 } 873 874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 875 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 876 case Sema::TDK_DeducedMismatch: 877 case Sema::TDK_DeducedMismatchNested: 878 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 879 880 default: 881 return llvm::None; 882 } 883 } 884 885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 886 OverloadedOperatorKind Op) { 887 if (!AllowRewrittenCandidates) 888 return false; 889 return Op == OO_EqualEqual || Op == OO_Spaceship; 890 } 891 892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 893 ASTContext &Ctx, const FunctionDecl *FD) { 894 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 895 return false; 896 // Don't bother adding a reversed candidate that can never be a better 897 // match than the non-reversed version. 898 return FD->getNumParams() != 2 || 899 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 900 FD->getParamDecl(1)->getType()) || 901 FD->hasAttr<EnableIfAttr>(); 902 } 903 904 void OverloadCandidateSet::destroyCandidates() { 905 for (iterator i = begin(), e = end(); i != e; ++i) { 906 for (auto &C : i->Conversions) 907 C.~ImplicitConversionSequence(); 908 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 909 i->DeductionFailure.Destroy(); 910 } 911 } 912 913 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 914 destroyCandidates(); 915 SlabAllocator.Reset(); 916 NumInlineBytesUsed = 0; 917 Candidates.clear(); 918 Functions.clear(); 919 Kind = CSK; 920 } 921 922 namespace { 923 class UnbridgedCastsSet { 924 struct Entry { 925 Expr **Addr; 926 Expr *Saved; 927 }; 928 SmallVector<Entry, 2> Entries; 929 930 public: 931 void save(Sema &S, Expr *&E) { 932 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 933 Entry entry = { &E, E }; 934 Entries.push_back(entry); 935 E = S.stripARCUnbridgedCast(E); 936 } 937 938 void restore() { 939 for (SmallVectorImpl<Entry>::iterator 940 i = Entries.begin(), e = Entries.end(); i != e; ++i) 941 *i->Addr = i->Saved; 942 } 943 }; 944 } 945 946 /// checkPlaceholderForOverload - Do any interesting placeholder-like 947 /// preprocessing on the given expression. 948 /// 949 /// \param unbridgedCasts a collection to which to add unbridged casts; 950 /// without this, they will be immediately diagnosed as errors 951 /// 952 /// Return true on unrecoverable error. 953 static bool 954 checkPlaceholderForOverload(Sema &S, Expr *&E, 955 UnbridgedCastsSet *unbridgedCasts = nullptr) { 956 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 957 // We can't handle overloaded expressions here because overload 958 // resolution might reasonably tweak them. 959 if (placeholder->getKind() == BuiltinType::Overload) return false; 960 961 // If the context potentially accepts unbridged ARC casts, strip 962 // the unbridged cast and add it to the collection for later restoration. 963 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 964 unbridgedCasts) { 965 unbridgedCasts->save(S, E); 966 return false; 967 } 968 969 // Go ahead and check everything else. 970 ExprResult result = S.CheckPlaceholderExpr(E); 971 if (result.isInvalid()) 972 return true; 973 974 E = result.get(); 975 return false; 976 } 977 978 // Nothing to do. 979 return false; 980 } 981 982 /// checkArgPlaceholdersForOverload - Check a set of call operands for 983 /// placeholders. 984 static bool checkArgPlaceholdersForOverload(Sema &S, 985 MultiExprArg Args, 986 UnbridgedCastsSet &unbridged) { 987 for (unsigned i = 0, e = Args.size(); i != e; ++i) 988 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 989 return true; 990 991 return false; 992 } 993 994 /// Determine whether the given New declaration is an overload of the 995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 996 /// New and Old cannot be overloaded, e.g., if New has the same signature as 997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 998 /// functions (or function templates) at all. When it does return Ovl_Match or 999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1001 /// declaration. 1002 /// 1003 /// Example: Given the following input: 1004 /// 1005 /// void f(int, float); // #1 1006 /// void f(int, int); // #2 1007 /// int f(int, int); // #3 1008 /// 1009 /// When we process #1, there is no previous declaration of "f", so IsOverload 1010 /// will not be used. 1011 /// 1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1015 /// unchanged. 1016 /// 1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1021 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1022 /// 1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1024 /// by a using declaration. The rules for whether to hide shadow declarations 1025 /// ignore some properties which otherwise figure into a function template's 1026 /// signature. 1027 Sema::OverloadKind 1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1029 NamedDecl *&Match, bool NewIsUsingDecl) { 1030 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1031 I != E; ++I) { 1032 NamedDecl *OldD = *I; 1033 1034 bool OldIsUsingDecl = false; 1035 if (isa<UsingShadowDecl>(OldD)) { 1036 OldIsUsingDecl = true; 1037 1038 // We can always introduce two using declarations into the same 1039 // context, even if they have identical signatures. 1040 if (NewIsUsingDecl) continue; 1041 1042 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1043 } 1044 1045 // A using-declaration does not conflict with another declaration 1046 // if one of them is hidden. 1047 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1048 continue; 1049 1050 // If either declaration was introduced by a using declaration, 1051 // we'll need to use slightly different rules for matching. 1052 // Essentially, these rules are the normal rules, except that 1053 // function templates hide function templates with different 1054 // return types or template parameter lists. 1055 bool UseMemberUsingDeclRules = 1056 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1057 !New->getFriendObjectKind(); 1058 1059 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1060 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1061 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1062 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1063 continue; 1064 } 1065 1066 if (!isa<FunctionTemplateDecl>(OldD) && 1067 !shouldLinkPossiblyHiddenDecl(*I, New)) 1068 continue; 1069 1070 Match = *I; 1071 return Ovl_Match; 1072 } 1073 1074 // Builtins that have custom typechecking or have a reference should 1075 // not be overloadable or redeclarable. 1076 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1077 Match = *I; 1078 return Ovl_NonFunction; 1079 } 1080 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1081 // We can overload with these, which can show up when doing 1082 // redeclaration checks for UsingDecls. 1083 assert(Old.getLookupKind() == LookupUsingDeclName); 1084 } else if (isa<TagDecl>(OldD)) { 1085 // We can always overload with tags by hiding them. 1086 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1087 // Optimistically assume that an unresolved using decl will 1088 // overload; if it doesn't, we'll have to diagnose during 1089 // template instantiation. 1090 // 1091 // Exception: if the scope is dependent and this is not a class 1092 // member, the using declaration can only introduce an enumerator. 1093 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1094 Match = *I; 1095 return Ovl_NonFunction; 1096 } 1097 } else { 1098 // (C++ 13p1): 1099 // Only function declarations can be overloaded; object and type 1100 // declarations cannot be overloaded. 1101 Match = *I; 1102 return Ovl_NonFunction; 1103 } 1104 } 1105 1106 // C++ [temp.friend]p1: 1107 // For a friend function declaration that is not a template declaration: 1108 // -- if the name of the friend is a qualified or unqualified template-id, 1109 // [...], otherwise 1110 // -- if the name of the friend is a qualified-id and a matching 1111 // non-template function is found in the specified class or namespace, 1112 // the friend declaration refers to that function, otherwise, 1113 // -- if the name of the friend is a qualified-id and a matching function 1114 // template is found in the specified class or namespace, the friend 1115 // declaration refers to the deduced specialization of that function 1116 // template, otherwise 1117 // -- the name shall be an unqualified-id [...] 1118 // If we get here for a qualified friend declaration, we've just reached the 1119 // third bullet. If the type of the friend is dependent, skip this lookup 1120 // until instantiation. 1121 if (New->getFriendObjectKind() && New->getQualifier() && 1122 !New->getDescribedFunctionTemplate() && 1123 !New->getDependentSpecializationInfo() && 1124 !New->getType()->isDependentType()) { 1125 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1126 TemplateSpecResult.addAllDecls(Old); 1127 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1128 /*QualifiedFriend*/true)) { 1129 New->setInvalidDecl(); 1130 return Ovl_Overload; 1131 } 1132 1133 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1134 return Ovl_Match; 1135 } 1136 1137 return Ovl_Overload; 1138 } 1139 1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1141 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1142 bool ConsiderRequiresClauses) { 1143 // C++ [basic.start.main]p2: This function shall not be overloaded. 1144 if (New->isMain()) 1145 return false; 1146 1147 // MSVCRT user defined entry points cannot be overloaded. 1148 if (New->isMSVCRTEntryPoint()) 1149 return false; 1150 1151 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1152 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1153 1154 // C++ [temp.fct]p2: 1155 // A function template can be overloaded with other function templates 1156 // and with normal (non-template) functions. 1157 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1158 return true; 1159 1160 // Is the function New an overload of the function Old? 1161 QualType OldQType = Context.getCanonicalType(Old->getType()); 1162 QualType NewQType = Context.getCanonicalType(New->getType()); 1163 1164 // Compare the signatures (C++ 1.3.10) of the two functions to 1165 // determine whether they are overloads. If we find any mismatch 1166 // in the signature, they are overloads. 1167 1168 // If either of these functions is a K&R-style function (no 1169 // prototype), then we consider them to have matching signatures. 1170 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1171 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1172 return false; 1173 1174 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1175 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1176 1177 // The signature of a function includes the types of its 1178 // parameters (C++ 1.3.10), which includes the presence or absence 1179 // of the ellipsis; see C++ DR 357). 1180 if (OldQType != NewQType && 1181 (OldType->getNumParams() != NewType->getNumParams() || 1182 OldType->isVariadic() != NewType->isVariadic() || 1183 !FunctionParamTypesAreEqual(OldType, NewType))) 1184 return true; 1185 1186 // C++ [temp.over.link]p4: 1187 // The signature of a function template consists of its function 1188 // signature, its return type and its template parameter list. The names 1189 // of the template parameters are significant only for establishing the 1190 // relationship between the template parameters and the rest of the 1191 // signature. 1192 // 1193 // We check the return type and template parameter lists for function 1194 // templates first; the remaining checks follow. 1195 // 1196 // However, we don't consider either of these when deciding whether 1197 // a member introduced by a shadow declaration is hidden. 1198 if (!UseMemberUsingDeclRules && NewTemplate && 1199 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1200 OldTemplate->getTemplateParameters(), 1201 false, TPL_TemplateMatch) || 1202 !Context.hasSameType(Old->getDeclaredReturnType(), 1203 New->getDeclaredReturnType()))) 1204 return true; 1205 1206 // If the function is a class member, its signature includes the 1207 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1208 // 1209 // As part of this, also check whether one of the member functions 1210 // is static, in which case they are not overloads (C++ 1211 // 13.1p2). While not part of the definition of the signature, 1212 // this check is important to determine whether these functions 1213 // can be overloaded. 1214 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1215 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1216 if (OldMethod && NewMethod && 1217 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1218 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1219 if (!UseMemberUsingDeclRules && 1220 (OldMethod->getRefQualifier() == RQ_None || 1221 NewMethod->getRefQualifier() == RQ_None)) { 1222 // C++0x [over.load]p2: 1223 // - Member function declarations with the same name and the same 1224 // parameter-type-list as well as member function template 1225 // declarations with the same name, the same parameter-type-list, and 1226 // the same template parameter lists cannot be overloaded if any of 1227 // them, but not all, have a ref-qualifier (8.3.5). 1228 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1229 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1230 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1231 } 1232 return true; 1233 } 1234 1235 // We may not have applied the implicit const for a constexpr member 1236 // function yet (because we haven't yet resolved whether this is a static 1237 // or non-static member function). Add it now, on the assumption that this 1238 // is a redeclaration of OldMethod. 1239 auto OldQuals = OldMethod->getMethodQualifiers(); 1240 auto NewQuals = NewMethod->getMethodQualifiers(); 1241 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1242 !isa<CXXConstructorDecl>(NewMethod)) 1243 NewQuals.addConst(); 1244 // We do not allow overloading based off of '__restrict'. 1245 OldQuals.removeRestrict(); 1246 NewQuals.removeRestrict(); 1247 if (OldQuals != NewQuals) 1248 return true; 1249 } 1250 1251 // Though pass_object_size is placed on parameters and takes an argument, we 1252 // consider it to be a function-level modifier for the sake of function 1253 // identity. Either the function has one or more parameters with 1254 // pass_object_size or it doesn't. 1255 if (functionHasPassObjectSizeParams(New) != 1256 functionHasPassObjectSizeParams(Old)) 1257 return true; 1258 1259 // enable_if attributes are an order-sensitive part of the signature. 1260 for (specific_attr_iterator<EnableIfAttr> 1261 NewI = New->specific_attr_begin<EnableIfAttr>(), 1262 NewE = New->specific_attr_end<EnableIfAttr>(), 1263 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1264 OldE = Old->specific_attr_end<EnableIfAttr>(); 1265 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1266 if (NewI == NewE || OldI == OldE) 1267 return true; 1268 llvm::FoldingSetNodeID NewID, OldID; 1269 NewI->getCond()->Profile(NewID, Context, true); 1270 OldI->getCond()->Profile(OldID, Context, true); 1271 if (NewID != OldID) 1272 return true; 1273 } 1274 1275 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1276 // Don't allow overloading of destructors. (In theory we could, but it 1277 // would be a giant change to clang.) 1278 if (!isa<CXXDestructorDecl>(New)) { 1279 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1280 OldTarget = IdentifyCUDATarget(Old); 1281 if (NewTarget != CFT_InvalidTarget) { 1282 assert((OldTarget != CFT_InvalidTarget) && 1283 "Unexpected invalid target."); 1284 1285 // Allow overloading of functions with same signature and different CUDA 1286 // target attributes. 1287 if (NewTarget != OldTarget) 1288 return true; 1289 } 1290 } 1291 } 1292 1293 if (ConsiderRequiresClauses) { 1294 Expr *NewRC = New->getTrailingRequiresClause(), 1295 *OldRC = Old->getTrailingRequiresClause(); 1296 if ((NewRC != nullptr) != (OldRC != nullptr)) 1297 // RC are most certainly different - these are overloads. 1298 return true; 1299 1300 if (NewRC) { 1301 llvm::FoldingSetNodeID NewID, OldID; 1302 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1303 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1304 if (NewID != OldID) 1305 // RCs are not equivalent - these are overloads. 1306 return true; 1307 } 1308 } 1309 1310 // The signatures match; this is not an overload. 1311 return false; 1312 } 1313 1314 /// Tries a user-defined conversion from From to ToType. 1315 /// 1316 /// Produces an implicit conversion sequence for when a standard conversion 1317 /// is not an option. See TryImplicitConversion for more information. 1318 static ImplicitConversionSequence 1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1320 bool SuppressUserConversions, 1321 AllowedExplicit AllowExplicit, 1322 bool InOverloadResolution, 1323 bool CStyle, 1324 bool AllowObjCWritebackConversion, 1325 bool AllowObjCConversionOnExplicit) { 1326 ImplicitConversionSequence ICS; 1327 1328 if (SuppressUserConversions) { 1329 // We're not in the case above, so there is no conversion that 1330 // we can perform. 1331 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1332 return ICS; 1333 } 1334 1335 // Attempt user-defined conversion. 1336 OverloadCandidateSet Conversions(From->getExprLoc(), 1337 OverloadCandidateSet::CSK_Normal); 1338 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1339 Conversions, AllowExplicit, 1340 AllowObjCConversionOnExplicit)) { 1341 case OR_Success: 1342 case OR_Deleted: 1343 ICS.setUserDefined(); 1344 // C++ [over.ics.user]p4: 1345 // A conversion of an expression of class type to the same class 1346 // type is given Exact Match rank, and a conversion of an 1347 // expression of class type to a base class of that type is 1348 // given Conversion rank, in spite of the fact that a copy 1349 // constructor (i.e., a user-defined conversion function) is 1350 // called for those cases. 1351 if (CXXConstructorDecl *Constructor 1352 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1353 QualType FromCanon 1354 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1355 QualType ToCanon 1356 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1357 if (Constructor->isCopyConstructor() && 1358 (FromCanon == ToCanon || 1359 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1360 // Turn this into a "standard" conversion sequence, so that it 1361 // gets ranked with standard conversion sequences. 1362 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1363 ICS.setStandard(); 1364 ICS.Standard.setAsIdentityConversion(); 1365 ICS.Standard.setFromType(From->getType()); 1366 ICS.Standard.setAllToTypes(ToType); 1367 ICS.Standard.CopyConstructor = Constructor; 1368 ICS.Standard.FoundCopyConstructor = Found; 1369 if (ToCanon != FromCanon) 1370 ICS.Standard.Second = ICK_Derived_To_Base; 1371 } 1372 } 1373 break; 1374 1375 case OR_Ambiguous: 1376 ICS.setAmbiguous(); 1377 ICS.Ambiguous.setFromType(From->getType()); 1378 ICS.Ambiguous.setToType(ToType); 1379 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1380 Cand != Conversions.end(); ++Cand) 1381 if (Cand->Best) 1382 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1383 break; 1384 1385 // Fall through. 1386 case OR_No_Viable_Function: 1387 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1388 break; 1389 } 1390 1391 return ICS; 1392 } 1393 1394 /// TryImplicitConversion - Attempt to perform an implicit conversion 1395 /// from the given expression (Expr) to the given type (ToType). This 1396 /// function returns an implicit conversion sequence that can be used 1397 /// to perform the initialization. Given 1398 /// 1399 /// void f(float f); 1400 /// void g(int i) { f(i); } 1401 /// 1402 /// this routine would produce an implicit conversion sequence to 1403 /// describe the initialization of f from i, which will be a standard 1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1406 // 1407 /// Note that this routine only determines how the conversion can be 1408 /// performed; it does not actually perform the conversion. As such, 1409 /// it will not produce any diagnostics if no conversion is available, 1410 /// but will instead return an implicit conversion sequence of kind 1411 /// "BadConversion". 1412 /// 1413 /// If @p SuppressUserConversions, then user-defined conversions are 1414 /// not permitted. 1415 /// If @p AllowExplicit, then explicit user-defined conversions are 1416 /// permitted. 1417 /// 1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1419 /// writeback conversion, which allows __autoreleasing id* parameters to 1420 /// be initialized with __strong id* or __weak id* arguments. 1421 static ImplicitConversionSequence 1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1423 bool SuppressUserConversions, 1424 AllowedExplicit AllowExplicit, 1425 bool InOverloadResolution, 1426 bool CStyle, 1427 bool AllowObjCWritebackConversion, 1428 bool AllowObjCConversionOnExplicit) { 1429 ImplicitConversionSequence ICS; 1430 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1431 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1432 ICS.setStandard(); 1433 return ICS; 1434 } 1435 1436 if (!S.getLangOpts().CPlusPlus) { 1437 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1438 return ICS; 1439 } 1440 1441 // C++ [over.ics.user]p4: 1442 // A conversion of an expression of class type to the same class 1443 // type is given Exact Match rank, and a conversion of an 1444 // expression of class type to a base class of that type is 1445 // given Conversion rank, in spite of the fact that a copy/move 1446 // constructor (i.e., a user-defined conversion function) is 1447 // called for those cases. 1448 QualType FromType = From->getType(); 1449 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1450 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1451 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1452 ICS.setStandard(); 1453 ICS.Standard.setAsIdentityConversion(); 1454 ICS.Standard.setFromType(FromType); 1455 ICS.Standard.setAllToTypes(ToType); 1456 1457 // We don't actually check at this point whether there is a valid 1458 // copy/move constructor, since overloading just assumes that it 1459 // exists. When we actually perform initialization, we'll find the 1460 // appropriate constructor to copy the returned object, if needed. 1461 ICS.Standard.CopyConstructor = nullptr; 1462 1463 // Determine whether this is considered a derived-to-base conversion. 1464 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1465 ICS.Standard.Second = ICK_Derived_To_Base; 1466 1467 return ICS; 1468 } 1469 1470 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1471 AllowExplicit, InOverloadResolution, CStyle, 1472 AllowObjCWritebackConversion, 1473 AllowObjCConversionOnExplicit); 1474 } 1475 1476 ImplicitConversionSequence 1477 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1478 bool SuppressUserConversions, 1479 AllowedExplicit AllowExplicit, 1480 bool InOverloadResolution, 1481 bool CStyle, 1482 bool AllowObjCWritebackConversion) { 1483 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1484 AllowExplicit, InOverloadResolution, CStyle, 1485 AllowObjCWritebackConversion, 1486 /*AllowObjCConversionOnExplicit=*/false); 1487 } 1488 1489 /// PerformImplicitConversion - Perform an implicit conversion of the 1490 /// expression From to the type ToType. Returns the 1491 /// converted expression. Flavor is the kind of conversion we're 1492 /// performing, used in the error message. If @p AllowExplicit, 1493 /// explicit user-defined conversions are permitted. 1494 ExprResult 1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, bool AllowExplicit) { 1497 ImplicitConversionSequence ICS; 1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1499 } 1500 1501 ExprResult 1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1503 AssignmentAction Action, bool AllowExplicit, 1504 ImplicitConversionSequence& ICS) { 1505 if (checkPlaceholderForOverload(*this, From)) 1506 return ExprError(); 1507 1508 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1509 bool AllowObjCWritebackConversion 1510 = getLangOpts().ObjCAutoRefCount && 1511 (Action == AA_Passing || Action == AA_Sending); 1512 if (getLangOpts().ObjC) 1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1514 From->getType(), From); 1515 ICS = ::TryImplicitConversion(*this, From, ToType, 1516 /*SuppressUserConversions=*/false, 1517 AllowExplicit ? AllowedExplicit::All 1518 : AllowedExplicit::None, 1519 /*InOverloadResolution=*/false, 1520 /*CStyle=*/false, AllowObjCWritebackConversion, 1521 /*AllowObjCConversionOnExplicit=*/false); 1522 return PerformImplicitConversion(From, ToType, ICS, Action); 1523 } 1524 1525 /// Determine whether the conversion from FromType to ToType is a valid 1526 /// conversion that strips "noexcept" or "noreturn" off the nested function 1527 /// type. 1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1529 QualType &ResultTy) { 1530 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1531 return false; 1532 1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1534 // or F(t noexcept) -> F(t) 1535 // where F adds one of the following at most once: 1536 // - a pointer 1537 // - a member pointer 1538 // - a block pointer 1539 // Changes here need matching changes in FindCompositePointerType. 1540 CanQualType CanTo = Context.getCanonicalType(ToType); 1541 CanQualType CanFrom = Context.getCanonicalType(FromType); 1542 Type::TypeClass TyClass = CanTo->getTypeClass(); 1543 if (TyClass != CanFrom->getTypeClass()) return false; 1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1545 if (TyClass == Type::Pointer) { 1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1548 } else if (TyClass == Type::BlockPointer) { 1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1551 } else if (TyClass == Type::MemberPointer) { 1552 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1553 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1554 // A function pointer conversion cannot change the class of the function. 1555 if (ToMPT->getClass() != FromMPT->getClass()) 1556 return false; 1557 CanTo = ToMPT->getPointeeType(); 1558 CanFrom = FromMPT->getPointeeType(); 1559 } else { 1560 return false; 1561 } 1562 1563 TyClass = CanTo->getTypeClass(); 1564 if (TyClass != CanFrom->getTypeClass()) return false; 1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1566 return false; 1567 } 1568 1569 const auto *FromFn = cast<FunctionType>(CanFrom); 1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1571 1572 const auto *ToFn = cast<FunctionType>(CanTo); 1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1574 1575 bool Changed = false; 1576 1577 // Drop 'noreturn' if not present in target type. 1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1580 Changed = true; 1581 } 1582 1583 // Drop 'noexcept' if not present in target type. 1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1587 FromFn = cast<FunctionType>( 1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1589 EST_None) 1590 .getTypePtr()); 1591 Changed = true; 1592 } 1593 1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1595 // only if the ExtParameterInfo lists of the two function prototypes can be 1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1598 bool CanUseToFPT, CanUseFromFPT; 1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1600 CanUseFromFPT, NewParamInfos) && 1601 CanUseToFPT && !CanUseFromFPT) { 1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1603 ExtInfo.ExtParameterInfos = 1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1606 FromFPT->getParamTypes(), ExtInfo); 1607 FromFn = QT->getAs<FunctionType>(); 1608 Changed = true; 1609 } 1610 } 1611 1612 if (!Changed) 1613 return false; 1614 1615 assert(QualType(FromFn, 0).isCanonical()); 1616 if (QualType(FromFn, 0) != CanTo) return false; 1617 1618 ResultTy = ToType; 1619 return true; 1620 } 1621 1622 /// Determine whether the conversion from FromType to ToType is a valid 1623 /// vector conversion. 1624 /// 1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1626 /// conversion. 1627 static bool IsVectorConversion(Sema &S, QualType FromType, 1628 QualType ToType, ImplicitConversionKind &ICK) { 1629 // We need at least one of these types to be a vector type to have a vector 1630 // conversion. 1631 if (!ToType->isVectorType() && !FromType->isVectorType()) 1632 return false; 1633 1634 // Identical types require no conversions. 1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1636 return false; 1637 1638 // There are no conversions between extended vector types, only identity. 1639 if (ToType->isExtVectorType()) { 1640 // There are no conversions between extended vector types other than the 1641 // identity conversion. 1642 if (FromType->isExtVectorType()) 1643 return false; 1644 1645 // Vector splat from any arithmetic type to a vector. 1646 if (FromType->isArithmeticType()) { 1647 ICK = ICK_Vector_Splat; 1648 return true; 1649 } 1650 } 1651 1652 // We can perform the conversion between vector types in the following cases: 1653 // 1)vector types are equivalent AltiVec and GCC vector types 1654 // 2)lax vector conversions are permitted and the vector types are of the 1655 // same size 1656 // 3)the destination type does not have the ARM MVE strict-polymorphism 1657 // attribute, which inhibits lax vector conversion for overload resolution 1658 // only 1659 if (ToType->isVectorType() && FromType->isVectorType()) { 1660 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1661 (S.isLaxVectorConversion(FromType, ToType) && 1662 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1663 ICK = ICK_Vector_Conversion; 1664 return true; 1665 } 1666 } 1667 1668 return false; 1669 } 1670 1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1672 bool InOverloadResolution, 1673 StandardConversionSequence &SCS, 1674 bool CStyle); 1675 1676 /// IsStandardConversion - Determines whether there is a standard 1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1678 /// expression From to the type ToType. Standard conversion sequences 1679 /// only consider non-class types; for conversions that involve class 1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1681 /// contain the standard conversion sequence required to perform this 1682 /// conversion and this routine will return true. Otherwise, this 1683 /// routine will return false and the value of SCS is unspecified. 1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1685 bool InOverloadResolution, 1686 StandardConversionSequence &SCS, 1687 bool CStyle, 1688 bool AllowObjCWritebackConversion) { 1689 QualType FromType = From->getType(); 1690 1691 // Standard conversions (C++ [conv]) 1692 SCS.setAsIdentityConversion(); 1693 SCS.IncompatibleObjC = false; 1694 SCS.setFromType(FromType); 1695 SCS.CopyConstructor = nullptr; 1696 1697 // There are no standard conversions for class types in C++, so 1698 // abort early. When overloading in C, however, we do permit them. 1699 if (S.getLangOpts().CPlusPlus && 1700 (FromType->isRecordType() || ToType->isRecordType())) 1701 return false; 1702 1703 // The first conversion can be an lvalue-to-rvalue conversion, 1704 // array-to-pointer conversion, or function-to-pointer conversion 1705 // (C++ 4p1). 1706 1707 if (FromType == S.Context.OverloadTy) { 1708 DeclAccessPair AccessPair; 1709 if (FunctionDecl *Fn 1710 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1711 AccessPair)) { 1712 // We were able to resolve the address of the overloaded function, 1713 // so we can convert to the type of that function. 1714 FromType = Fn->getType(); 1715 SCS.setFromType(FromType); 1716 1717 // we can sometimes resolve &foo<int> regardless of ToType, so check 1718 // if the type matches (identity) or we are converting to bool 1719 if (!S.Context.hasSameUnqualifiedType( 1720 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1721 QualType resultTy; 1722 // if the function type matches except for [[noreturn]], it's ok 1723 if (!S.IsFunctionConversion(FromType, 1724 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1725 // otherwise, only a boolean conversion is standard 1726 if (!ToType->isBooleanType()) 1727 return false; 1728 } 1729 1730 // Check if the "from" expression is taking the address of an overloaded 1731 // function and recompute the FromType accordingly. Take advantage of the 1732 // fact that non-static member functions *must* have such an address-of 1733 // expression. 1734 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1735 if (Method && !Method->isStatic()) { 1736 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1737 "Non-unary operator on non-static member address"); 1738 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1739 == UO_AddrOf && 1740 "Non-address-of operator on non-static member address"); 1741 const Type *ClassType 1742 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1743 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1744 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1745 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1746 UO_AddrOf && 1747 "Non-address-of operator for overloaded function expression"); 1748 FromType = S.Context.getPointerType(FromType); 1749 } 1750 1751 // Check that we've computed the proper type after overload resolution. 1752 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1753 // be calling it from within an NDEBUG block. 1754 assert(S.Context.hasSameType( 1755 FromType, 1756 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1757 } else { 1758 return false; 1759 } 1760 } 1761 // Lvalue-to-rvalue conversion (C++11 4.1): 1762 // A glvalue (3.10) of a non-function, non-array type T can 1763 // be converted to a prvalue. 1764 bool argIsLValue = From->isGLValue(); 1765 if (argIsLValue && 1766 !FromType->isFunctionType() && !FromType->isArrayType() && 1767 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1768 SCS.First = ICK_Lvalue_To_Rvalue; 1769 1770 // C11 6.3.2.1p2: 1771 // ... if the lvalue has atomic type, the value has the non-atomic version 1772 // of the type of the lvalue ... 1773 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1774 FromType = Atomic->getValueType(); 1775 1776 // If T is a non-class type, the type of the rvalue is the 1777 // cv-unqualified version of T. Otherwise, the type of the rvalue 1778 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1779 // just strip the qualifiers because they don't matter. 1780 FromType = FromType.getUnqualifiedType(); 1781 } else if (FromType->isArrayType()) { 1782 // Array-to-pointer conversion (C++ 4.2) 1783 SCS.First = ICK_Array_To_Pointer; 1784 1785 // An lvalue or rvalue of type "array of N T" or "array of unknown 1786 // bound of T" can be converted to an rvalue of type "pointer to 1787 // T" (C++ 4.2p1). 1788 FromType = S.Context.getArrayDecayedType(FromType); 1789 1790 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1791 // This conversion is deprecated in C++03 (D.4) 1792 SCS.DeprecatedStringLiteralToCharPtr = true; 1793 1794 // For the purpose of ranking in overload resolution 1795 // (13.3.3.1.1), this conversion is considered an 1796 // array-to-pointer conversion followed by a qualification 1797 // conversion (4.4). (C++ 4.2p2) 1798 SCS.Second = ICK_Identity; 1799 SCS.Third = ICK_Qualification; 1800 SCS.QualificationIncludesObjCLifetime = false; 1801 SCS.setAllToTypes(FromType); 1802 return true; 1803 } 1804 } else if (FromType->isFunctionType() && argIsLValue) { 1805 // Function-to-pointer conversion (C++ 4.3). 1806 SCS.First = ICK_Function_To_Pointer; 1807 1808 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1809 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1810 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1811 return false; 1812 1813 // An lvalue of function type T can be converted to an rvalue of 1814 // type "pointer to T." The result is a pointer to the 1815 // function. (C++ 4.3p1). 1816 FromType = S.Context.getPointerType(FromType); 1817 } else { 1818 // We don't require any conversions for the first step. 1819 SCS.First = ICK_Identity; 1820 } 1821 SCS.setToType(0, FromType); 1822 1823 // The second conversion can be an integral promotion, floating 1824 // point promotion, integral conversion, floating point conversion, 1825 // floating-integral conversion, pointer conversion, 1826 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1827 // For overloading in C, this can also be a "compatible-type" 1828 // conversion. 1829 bool IncompatibleObjC = false; 1830 ImplicitConversionKind SecondICK = ICK_Identity; 1831 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1832 // The unqualified versions of the types are the same: there's no 1833 // conversion to do. 1834 SCS.Second = ICK_Identity; 1835 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1836 // Integral promotion (C++ 4.5). 1837 SCS.Second = ICK_Integral_Promotion; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1840 // Floating point promotion (C++ 4.6). 1841 SCS.Second = ICK_Floating_Promotion; 1842 FromType = ToType.getUnqualifiedType(); 1843 } else if (S.IsComplexPromotion(FromType, ToType)) { 1844 // Complex promotion (Clang extension) 1845 SCS.Second = ICK_Complex_Promotion; 1846 FromType = ToType.getUnqualifiedType(); 1847 } else if (ToType->isBooleanType() && 1848 (FromType->isArithmeticType() || 1849 FromType->isAnyPointerType() || 1850 FromType->isBlockPointerType() || 1851 FromType->isMemberPointerType())) { 1852 // Boolean conversions (C++ 4.12). 1853 SCS.Second = ICK_Boolean_Conversion; 1854 FromType = S.Context.BoolTy; 1855 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1856 ToType->isIntegralType(S.Context)) { 1857 // Integral conversions (C++ 4.7). 1858 SCS.Second = ICK_Integral_Conversion; 1859 FromType = ToType.getUnqualifiedType(); 1860 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1861 // Complex conversions (C99 6.3.1.6) 1862 SCS.Second = ICK_Complex_Conversion; 1863 FromType = ToType.getUnqualifiedType(); 1864 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1865 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1866 // Complex-real conversions (C99 6.3.1.7) 1867 SCS.Second = ICK_Complex_Real; 1868 FromType = ToType.getUnqualifiedType(); 1869 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1870 // FIXME: disable conversions between long double and __float128 if 1871 // their representation is different until there is back end support 1872 // We of course allow this conversion if long double is really double. 1873 1874 // Conversions between bfloat and other floats are not permitted. 1875 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1876 return false; 1877 if (&S.Context.getFloatTypeSemantics(FromType) != 1878 &S.Context.getFloatTypeSemantics(ToType)) { 1879 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1880 ToType == S.Context.LongDoubleTy) || 1881 (FromType == S.Context.LongDoubleTy && 1882 ToType == S.Context.Float128Ty)); 1883 if (Float128AndLongDouble && 1884 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1885 &llvm::APFloat::PPCDoubleDouble())) 1886 return false; 1887 } 1888 // Floating point conversions (C++ 4.8). 1889 SCS.Second = ICK_Floating_Conversion; 1890 FromType = ToType.getUnqualifiedType(); 1891 } else if ((FromType->isRealFloatingType() && 1892 ToType->isIntegralType(S.Context)) || 1893 (FromType->isIntegralOrUnscopedEnumerationType() && 1894 ToType->isRealFloatingType())) { 1895 // Conversions between bfloat and int are not permitted. 1896 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1897 return false; 1898 1899 // Floating-integral conversions (C++ 4.9). 1900 SCS.Second = ICK_Floating_Integral; 1901 FromType = ToType.getUnqualifiedType(); 1902 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1903 SCS.Second = ICK_Block_Pointer_Conversion; 1904 } else if (AllowObjCWritebackConversion && 1905 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1906 SCS.Second = ICK_Writeback_Conversion; 1907 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1908 FromType, IncompatibleObjC)) { 1909 // Pointer conversions (C++ 4.10). 1910 SCS.Second = ICK_Pointer_Conversion; 1911 SCS.IncompatibleObjC = IncompatibleObjC; 1912 FromType = FromType.getUnqualifiedType(); 1913 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1914 InOverloadResolution, FromType)) { 1915 // Pointer to member conversions (4.11). 1916 SCS.Second = ICK_Pointer_Member; 1917 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1918 SCS.Second = SecondICK; 1919 FromType = ToType.getUnqualifiedType(); 1920 } else if (!S.getLangOpts().CPlusPlus && 1921 S.Context.typesAreCompatible(ToType, FromType)) { 1922 // Compatible conversions (Clang extension for C function overloading) 1923 SCS.Second = ICK_Compatible_Conversion; 1924 FromType = ToType.getUnqualifiedType(); 1925 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1926 InOverloadResolution, 1927 SCS, CStyle)) { 1928 SCS.Second = ICK_TransparentUnionConversion; 1929 FromType = ToType; 1930 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1931 CStyle)) { 1932 // tryAtomicConversion has updated the standard conversion sequence 1933 // appropriately. 1934 return true; 1935 } else if (ToType->isEventT() && 1936 From->isIntegerConstantExpr(S.getASTContext()) && 1937 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1938 SCS.Second = ICK_Zero_Event_Conversion; 1939 FromType = ToType; 1940 } else if (ToType->isQueueT() && 1941 From->isIntegerConstantExpr(S.getASTContext()) && 1942 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1943 SCS.Second = ICK_Zero_Queue_Conversion; 1944 FromType = ToType; 1945 } else if (ToType->isSamplerT() && 1946 From->isIntegerConstantExpr(S.getASTContext())) { 1947 SCS.Second = ICK_Compatible_Conversion; 1948 FromType = ToType; 1949 } else { 1950 // No second conversion required. 1951 SCS.Second = ICK_Identity; 1952 } 1953 SCS.setToType(1, FromType); 1954 1955 // The third conversion can be a function pointer conversion or a 1956 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1957 bool ObjCLifetimeConversion; 1958 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1959 // Function pointer conversions (removing 'noexcept') including removal of 1960 // 'noreturn' (Clang extension). 1961 SCS.Third = ICK_Function_Conversion; 1962 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1963 ObjCLifetimeConversion)) { 1964 SCS.Third = ICK_Qualification; 1965 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1966 FromType = ToType; 1967 } else { 1968 // No conversion required 1969 SCS.Third = ICK_Identity; 1970 } 1971 1972 // C++ [over.best.ics]p6: 1973 // [...] Any difference in top-level cv-qualification is 1974 // subsumed by the initialization itself and does not constitute 1975 // a conversion. [...] 1976 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1977 QualType CanonTo = S.Context.getCanonicalType(ToType); 1978 if (CanonFrom.getLocalUnqualifiedType() 1979 == CanonTo.getLocalUnqualifiedType() && 1980 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1981 FromType = ToType; 1982 CanonFrom = CanonTo; 1983 } 1984 1985 SCS.setToType(2, FromType); 1986 1987 if (CanonFrom == CanonTo) 1988 return true; 1989 1990 // If we have not converted the argument type to the parameter type, 1991 // this is a bad conversion sequence, unless we're resolving an overload in C. 1992 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1993 return false; 1994 1995 ExprResult ER = ExprResult{From}; 1996 Sema::AssignConvertType Conv = 1997 S.CheckSingleAssignmentConstraints(ToType, ER, 1998 /*Diagnose=*/false, 1999 /*DiagnoseCFAudited=*/false, 2000 /*ConvertRHS=*/false); 2001 ImplicitConversionKind SecondConv; 2002 switch (Conv) { 2003 case Sema::Compatible: 2004 SecondConv = ICK_C_Only_Conversion; 2005 break; 2006 // For our purposes, discarding qualifiers is just as bad as using an 2007 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2008 // qualifiers, as well. 2009 case Sema::CompatiblePointerDiscardsQualifiers: 2010 case Sema::IncompatiblePointer: 2011 case Sema::IncompatiblePointerSign: 2012 SecondConv = ICK_Incompatible_Pointer_Conversion; 2013 break; 2014 default: 2015 return false; 2016 } 2017 2018 // First can only be an lvalue conversion, so we pretend that this was the 2019 // second conversion. First should already be valid from earlier in the 2020 // function. 2021 SCS.Second = SecondConv; 2022 SCS.setToType(1, ToType); 2023 2024 // Third is Identity, because Second should rank us worse than any other 2025 // conversion. This could also be ICK_Qualification, but it's simpler to just 2026 // lump everything in with the second conversion, and we don't gain anything 2027 // from making this ICK_Qualification. 2028 SCS.Third = ICK_Identity; 2029 SCS.setToType(2, ToType); 2030 return true; 2031 } 2032 2033 static bool 2034 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2035 QualType &ToType, 2036 bool InOverloadResolution, 2037 StandardConversionSequence &SCS, 2038 bool CStyle) { 2039 2040 const RecordType *UT = ToType->getAsUnionType(); 2041 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2042 return false; 2043 // The field to initialize within the transparent union. 2044 RecordDecl *UD = UT->getDecl(); 2045 // It's compatible if the expression matches any of the fields. 2046 for (const auto *it : UD->fields()) { 2047 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2048 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2049 ToType = it->getType(); 2050 return true; 2051 } 2052 } 2053 return false; 2054 } 2055 2056 /// IsIntegralPromotion - Determines whether the conversion from the 2057 /// expression From (whose potentially-adjusted type is FromType) to 2058 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2059 /// sets PromotedType to the promoted type. 2060 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2061 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2062 // All integers are built-in. 2063 if (!To) { 2064 return false; 2065 } 2066 2067 // An rvalue of type char, signed char, unsigned char, short int, or 2068 // unsigned short int can be converted to an rvalue of type int if 2069 // int can represent all the values of the source type; otherwise, 2070 // the source rvalue can be converted to an rvalue of type unsigned 2071 // int (C++ 4.5p1). 2072 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2073 !FromType->isEnumeralType()) { 2074 if (// We can promote any signed, promotable integer type to an int 2075 (FromType->isSignedIntegerType() || 2076 // We can promote any unsigned integer type whose size is 2077 // less than int to an int. 2078 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2079 return To->getKind() == BuiltinType::Int; 2080 } 2081 2082 return To->getKind() == BuiltinType::UInt; 2083 } 2084 2085 // C++11 [conv.prom]p3: 2086 // A prvalue of an unscoped enumeration type whose underlying type is not 2087 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2088 // following types that can represent all the values of the enumeration 2089 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2090 // unsigned int, long int, unsigned long int, long long int, or unsigned 2091 // long long int. If none of the types in that list can represent all the 2092 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2093 // type can be converted to an rvalue a prvalue of the extended integer type 2094 // with lowest integer conversion rank (4.13) greater than the rank of long 2095 // long in which all the values of the enumeration can be represented. If 2096 // there are two such extended types, the signed one is chosen. 2097 // C++11 [conv.prom]p4: 2098 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2099 // can be converted to a prvalue of its underlying type. Moreover, if 2100 // integral promotion can be applied to its underlying type, a prvalue of an 2101 // unscoped enumeration type whose underlying type is fixed can also be 2102 // converted to a prvalue of the promoted underlying type. 2103 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2104 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2105 // provided for a scoped enumeration. 2106 if (FromEnumType->getDecl()->isScoped()) 2107 return false; 2108 2109 // We can perform an integral promotion to the underlying type of the enum, 2110 // even if that's not the promoted type. Note that the check for promoting 2111 // the underlying type is based on the type alone, and does not consider 2112 // the bitfield-ness of the actual source expression. 2113 if (FromEnumType->getDecl()->isFixed()) { 2114 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2115 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2116 IsIntegralPromotion(nullptr, Underlying, ToType); 2117 } 2118 2119 // We have already pre-calculated the promotion type, so this is trivial. 2120 if (ToType->isIntegerType() && 2121 isCompleteType(From->getBeginLoc(), FromType)) 2122 return Context.hasSameUnqualifiedType( 2123 ToType, FromEnumType->getDecl()->getPromotionType()); 2124 2125 // C++ [conv.prom]p5: 2126 // If the bit-field has an enumerated type, it is treated as any other 2127 // value of that type for promotion purposes. 2128 // 2129 // ... so do not fall through into the bit-field checks below in C++. 2130 if (getLangOpts().CPlusPlus) 2131 return false; 2132 } 2133 2134 // C++0x [conv.prom]p2: 2135 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2136 // to an rvalue a prvalue of the first of the following types that can 2137 // represent all the values of its underlying type: int, unsigned int, 2138 // long int, unsigned long int, long long int, or unsigned long long int. 2139 // If none of the types in that list can represent all the values of its 2140 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2141 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2142 // type. 2143 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2144 ToType->isIntegerType()) { 2145 // Determine whether the type we're converting from is signed or 2146 // unsigned. 2147 bool FromIsSigned = FromType->isSignedIntegerType(); 2148 uint64_t FromSize = Context.getTypeSize(FromType); 2149 2150 // The types we'll try to promote to, in the appropriate 2151 // order. Try each of these types. 2152 QualType PromoteTypes[6] = { 2153 Context.IntTy, Context.UnsignedIntTy, 2154 Context.LongTy, Context.UnsignedLongTy , 2155 Context.LongLongTy, Context.UnsignedLongLongTy 2156 }; 2157 for (int Idx = 0; Idx < 6; ++Idx) { 2158 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2159 if (FromSize < ToSize || 2160 (FromSize == ToSize && 2161 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2162 // We found the type that we can promote to. If this is the 2163 // type we wanted, we have a promotion. Otherwise, no 2164 // promotion. 2165 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2166 } 2167 } 2168 } 2169 2170 // An rvalue for an integral bit-field (9.6) can be converted to an 2171 // rvalue of type int if int can represent all the values of the 2172 // bit-field; otherwise, it can be converted to unsigned int if 2173 // unsigned int can represent all the values of the bit-field. If 2174 // the bit-field is larger yet, no integral promotion applies to 2175 // it. If the bit-field has an enumerated type, it is treated as any 2176 // other value of that type for promotion purposes (C++ 4.5p3). 2177 // FIXME: We should delay checking of bit-fields until we actually perform the 2178 // conversion. 2179 // 2180 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2181 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2182 // bit-fields and those whose underlying type is larger than int) for GCC 2183 // compatibility. 2184 if (From) { 2185 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2186 llvm::APSInt BitWidth; 2187 if (FromType->isIntegralType(Context) && 2188 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2189 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2190 ToSize = Context.getTypeSize(ToType); 2191 2192 // Are we promoting to an int from a bitfield that fits in an int? 2193 if (BitWidth < ToSize || 2194 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2195 return To->getKind() == BuiltinType::Int; 2196 } 2197 2198 // Are we promoting to an unsigned int from an unsigned bitfield 2199 // that fits into an unsigned int? 2200 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2201 return To->getKind() == BuiltinType::UInt; 2202 } 2203 2204 return false; 2205 } 2206 } 2207 } 2208 2209 // An rvalue of type bool can be converted to an rvalue of type int, 2210 // with false becoming zero and true becoming one (C++ 4.5p4). 2211 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2212 return true; 2213 } 2214 2215 return false; 2216 } 2217 2218 /// IsFloatingPointPromotion - Determines whether the conversion from 2219 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2220 /// returns true and sets PromotedType to the promoted type. 2221 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2222 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2223 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2224 /// An rvalue of type float can be converted to an rvalue of type 2225 /// double. (C++ 4.6p1). 2226 if (FromBuiltin->getKind() == BuiltinType::Float && 2227 ToBuiltin->getKind() == BuiltinType::Double) 2228 return true; 2229 2230 // C99 6.3.1.5p1: 2231 // When a float is promoted to double or long double, or a 2232 // double is promoted to long double [...]. 2233 if (!getLangOpts().CPlusPlus && 2234 (FromBuiltin->getKind() == BuiltinType::Float || 2235 FromBuiltin->getKind() == BuiltinType::Double) && 2236 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2237 ToBuiltin->getKind() == BuiltinType::Float128)) 2238 return true; 2239 2240 // Half can be promoted to float. 2241 if (!getLangOpts().NativeHalfType && 2242 FromBuiltin->getKind() == BuiltinType::Half && 2243 ToBuiltin->getKind() == BuiltinType::Float) 2244 return true; 2245 } 2246 2247 return false; 2248 } 2249 2250 /// Determine if a conversion is a complex promotion. 2251 /// 2252 /// A complex promotion is defined as a complex -> complex conversion 2253 /// where the conversion between the underlying real types is a 2254 /// floating-point or integral promotion. 2255 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2256 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2257 if (!FromComplex) 2258 return false; 2259 2260 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2261 if (!ToComplex) 2262 return false; 2263 2264 return IsFloatingPointPromotion(FromComplex->getElementType(), 2265 ToComplex->getElementType()) || 2266 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2267 ToComplex->getElementType()); 2268 } 2269 2270 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2271 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2272 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2273 /// if non-empty, will be a pointer to ToType that may or may not have 2274 /// the right set of qualifiers on its pointee. 2275 /// 2276 static QualType 2277 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2278 QualType ToPointee, QualType ToType, 2279 ASTContext &Context, 2280 bool StripObjCLifetime = false) { 2281 assert((FromPtr->getTypeClass() == Type::Pointer || 2282 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2283 "Invalid similarly-qualified pointer type"); 2284 2285 /// Conversions to 'id' subsume cv-qualifier conversions. 2286 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2287 return ToType.getUnqualifiedType(); 2288 2289 QualType CanonFromPointee 2290 = Context.getCanonicalType(FromPtr->getPointeeType()); 2291 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2292 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2293 2294 if (StripObjCLifetime) 2295 Quals.removeObjCLifetime(); 2296 2297 // Exact qualifier match -> return the pointer type we're converting to. 2298 if (CanonToPointee.getLocalQualifiers() == Quals) { 2299 // ToType is exactly what we need. Return it. 2300 if (!ToType.isNull()) 2301 return ToType.getUnqualifiedType(); 2302 2303 // Build a pointer to ToPointee. It has the right qualifiers 2304 // already. 2305 if (isa<ObjCObjectPointerType>(ToType)) 2306 return Context.getObjCObjectPointerType(ToPointee); 2307 return Context.getPointerType(ToPointee); 2308 } 2309 2310 // Just build a canonical type that has the right qualifiers. 2311 QualType QualifiedCanonToPointee 2312 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2313 2314 if (isa<ObjCObjectPointerType>(ToType)) 2315 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2316 return Context.getPointerType(QualifiedCanonToPointee); 2317 } 2318 2319 static bool isNullPointerConstantForConversion(Expr *Expr, 2320 bool InOverloadResolution, 2321 ASTContext &Context) { 2322 // Handle value-dependent integral null pointer constants correctly. 2323 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2324 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2325 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2326 return !InOverloadResolution; 2327 2328 return Expr->isNullPointerConstant(Context, 2329 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2330 : Expr::NPC_ValueDependentIsNull); 2331 } 2332 2333 /// IsPointerConversion - Determines whether the conversion of the 2334 /// expression From, which has the (possibly adjusted) type FromType, 2335 /// can be converted to the type ToType via a pointer conversion (C++ 2336 /// 4.10). If so, returns true and places the converted type (that 2337 /// might differ from ToType in its cv-qualifiers at some level) into 2338 /// ConvertedType. 2339 /// 2340 /// This routine also supports conversions to and from block pointers 2341 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2342 /// pointers to interfaces. FIXME: Once we've determined the 2343 /// appropriate overloading rules for Objective-C, we may want to 2344 /// split the Objective-C checks into a different routine; however, 2345 /// GCC seems to consider all of these conversions to be pointer 2346 /// conversions, so for now they live here. IncompatibleObjC will be 2347 /// set if the conversion is an allowed Objective-C conversion that 2348 /// should result in a warning. 2349 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2350 bool InOverloadResolution, 2351 QualType& ConvertedType, 2352 bool &IncompatibleObjC) { 2353 IncompatibleObjC = false; 2354 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2355 IncompatibleObjC)) 2356 return true; 2357 2358 // Conversion from a null pointer constant to any Objective-C pointer type. 2359 if (ToType->isObjCObjectPointerType() && 2360 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2361 ConvertedType = ToType; 2362 return true; 2363 } 2364 2365 // Blocks: Block pointers can be converted to void*. 2366 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2367 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2368 ConvertedType = ToType; 2369 return true; 2370 } 2371 // Blocks: A null pointer constant can be converted to a block 2372 // pointer type. 2373 if (ToType->isBlockPointerType() && 2374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2375 ConvertedType = ToType; 2376 return true; 2377 } 2378 2379 // If the left-hand-side is nullptr_t, the right side can be a null 2380 // pointer constant. 2381 if (ToType->isNullPtrType() && 2382 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2383 ConvertedType = ToType; 2384 return true; 2385 } 2386 2387 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2388 if (!ToTypePtr) 2389 return false; 2390 2391 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2392 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2393 ConvertedType = ToType; 2394 return true; 2395 } 2396 2397 // Beyond this point, both types need to be pointers 2398 // , including objective-c pointers. 2399 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2400 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2401 !getLangOpts().ObjCAutoRefCount) { 2402 ConvertedType = BuildSimilarlyQualifiedPointerType( 2403 FromType->getAs<ObjCObjectPointerType>(), 2404 ToPointeeType, 2405 ToType, Context); 2406 return true; 2407 } 2408 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2409 if (!FromTypePtr) 2410 return false; 2411 2412 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2413 2414 // If the unqualified pointee types are the same, this can't be a 2415 // pointer conversion, so don't do all of the work below. 2416 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2417 return false; 2418 2419 // An rvalue of type "pointer to cv T," where T is an object type, 2420 // can be converted to an rvalue of type "pointer to cv void" (C++ 2421 // 4.10p2). 2422 if (FromPointeeType->isIncompleteOrObjectType() && 2423 ToPointeeType->isVoidType()) { 2424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2425 ToPointeeType, 2426 ToType, Context, 2427 /*StripObjCLifetime=*/true); 2428 return true; 2429 } 2430 2431 // MSVC allows implicit function to void* type conversion. 2432 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2433 ToPointeeType->isVoidType()) { 2434 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2435 ToPointeeType, 2436 ToType, Context); 2437 return true; 2438 } 2439 2440 // When we're overloading in C, we allow a special kind of pointer 2441 // conversion for compatible-but-not-identical pointee types. 2442 if (!getLangOpts().CPlusPlus && 2443 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2444 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2445 ToPointeeType, 2446 ToType, Context); 2447 return true; 2448 } 2449 2450 // C++ [conv.ptr]p3: 2451 // 2452 // An rvalue of type "pointer to cv D," where D is a class type, 2453 // can be converted to an rvalue of type "pointer to cv B," where 2454 // B is a base class (clause 10) of D. If B is an inaccessible 2455 // (clause 11) or ambiguous (10.2) base class of D, a program that 2456 // necessitates this conversion is ill-formed. The result of the 2457 // conversion is a pointer to the base class sub-object of the 2458 // derived class object. The null pointer value is converted to 2459 // the null pointer value of the destination type. 2460 // 2461 // Note that we do not check for ambiguity or inaccessibility 2462 // here. That is handled by CheckPointerConversion. 2463 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2464 ToPointeeType->isRecordType() && 2465 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2466 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2467 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2468 ToPointeeType, 2469 ToType, Context); 2470 return true; 2471 } 2472 2473 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2474 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2475 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2476 ToPointeeType, 2477 ToType, Context); 2478 return true; 2479 } 2480 2481 return false; 2482 } 2483 2484 /// Adopt the given qualifiers for the given type. 2485 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2486 Qualifiers TQs = T.getQualifiers(); 2487 2488 // Check whether qualifiers already match. 2489 if (TQs == Qs) 2490 return T; 2491 2492 if (Qs.compatiblyIncludes(TQs)) 2493 return Context.getQualifiedType(T, Qs); 2494 2495 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2496 } 2497 2498 /// isObjCPointerConversion - Determines whether this is an 2499 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2500 /// with the same arguments and return values. 2501 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2502 QualType& ConvertedType, 2503 bool &IncompatibleObjC) { 2504 if (!getLangOpts().ObjC) 2505 return false; 2506 2507 // The set of qualifiers on the type we're converting from. 2508 Qualifiers FromQualifiers = FromType.getQualifiers(); 2509 2510 // First, we handle all conversions on ObjC object pointer types. 2511 const ObjCObjectPointerType* ToObjCPtr = 2512 ToType->getAs<ObjCObjectPointerType>(); 2513 const ObjCObjectPointerType *FromObjCPtr = 2514 FromType->getAs<ObjCObjectPointerType>(); 2515 2516 if (ToObjCPtr && FromObjCPtr) { 2517 // If the pointee types are the same (ignoring qualifications), 2518 // then this is not a pointer conversion. 2519 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2520 FromObjCPtr->getPointeeType())) 2521 return false; 2522 2523 // Conversion between Objective-C pointers. 2524 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2525 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2526 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2527 if (getLangOpts().CPlusPlus && LHS && RHS && 2528 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2529 FromObjCPtr->getPointeeType())) 2530 return false; 2531 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2532 ToObjCPtr->getPointeeType(), 2533 ToType, Context); 2534 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2535 return true; 2536 } 2537 2538 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2539 // Okay: this is some kind of implicit downcast of Objective-C 2540 // interfaces, which is permitted. However, we're going to 2541 // complain about it. 2542 IncompatibleObjC = true; 2543 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2544 ToObjCPtr->getPointeeType(), 2545 ToType, Context); 2546 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2547 return true; 2548 } 2549 } 2550 // Beyond this point, both types need to be C pointers or block pointers. 2551 QualType ToPointeeType; 2552 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2553 ToPointeeType = ToCPtr->getPointeeType(); 2554 else if (const BlockPointerType *ToBlockPtr = 2555 ToType->getAs<BlockPointerType>()) { 2556 // Objective C++: We're able to convert from a pointer to any object 2557 // to a block pointer type. 2558 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2559 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2560 return true; 2561 } 2562 ToPointeeType = ToBlockPtr->getPointeeType(); 2563 } 2564 else if (FromType->getAs<BlockPointerType>() && 2565 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2566 // Objective C++: We're able to convert from a block pointer type to a 2567 // pointer to any object. 2568 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2569 return true; 2570 } 2571 else 2572 return false; 2573 2574 QualType FromPointeeType; 2575 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2576 FromPointeeType = FromCPtr->getPointeeType(); 2577 else if (const BlockPointerType *FromBlockPtr = 2578 FromType->getAs<BlockPointerType>()) 2579 FromPointeeType = FromBlockPtr->getPointeeType(); 2580 else 2581 return false; 2582 2583 // If we have pointers to pointers, recursively check whether this 2584 // is an Objective-C conversion. 2585 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2586 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2587 IncompatibleObjC)) { 2588 // We always complain about this conversion. 2589 IncompatibleObjC = true; 2590 ConvertedType = Context.getPointerType(ConvertedType); 2591 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2592 return true; 2593 } 2594 // Allow conversion of pointee being objective-c pointer to another one; 2595 // as in I* to id. 2596 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2597 ToPointeeType->getAs<ObjCObjectPointerType>() && 2598 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2599 IncompatibleObjC)) { 2600 2601 ConvertedType = Context.getPointerType(ConvertedType); 2602 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2603 return true; 2604 } 2605 2606 // If we have pointers to functions or blocks, check whether the only 2607 // differences in the argument and result types are in Objective-C 2608 // pointer conversions. If so, we permit the conversion (but 2609 // complain about it). 2610 const FunctionProtoType *FromFunctionType 2611 = FromPointeeType->getAs<FunctionProtoType>(); 2612 const FunctionProtoType *ToFunctionType 2613 = ToPointeeType->getAs<FunctionProtoType>(); 2614 if (FromFunctionType && ToFunctionType) { 2615 // If the function types are exactly the same, this isn't an 2616 // Objective-C pointer conversion. 2617 if (Context.getCanonicalType(FromPointeeType) 2618 == Context.getCanonicalType(ToPointeeType)) 2619 return false; 2620 2621 // Perform the quick checks that will tell us whether these 2622 // function types are obviously different. 2623 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2624 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2625 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2626 return false; 2627 2628 bool HasObjCConversion = false; 2629 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2630 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2631 // Okay, the types match exactly. Nothing to do. 2632 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2633 ToFunctionType->getReturnType(), 2634 ConvertedType, IncompatibleObjC)) { 2635 // Okay, we have an Objective-C pointer conversion. 2636 HasObjCConversion = true; 2637 } else { 2638 // Function types are too different. Abort. 2639 return false; 2640 } 2641 2642 // Check argument types. 2643 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2644 ArgIdx != NumArgs; ++ArgIdx) { 2645 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2646 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2647 if (Context.getCanonicalType(FromArgType) 2648 == Context.getCanonicalType(ToArgType)) { 2649 // Okay, the types match exactly. Nothing to do. 2650 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2651 ConvertedType, IncompatibleObjC)) { 2652 // Okay, we have an Objective-C pointer conversion. 2653 HasObjCConversion = true; 2654 } else { 2655 // Argument types are too different. Abort. 2656 return false; 2657 } 2658 } 2659 2660 if (HasObjCConversion) { 2661 // We had an Objective-C conversion. Allow this pointer 2662 // conversion, but complain about it. 2663 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2664 IncompatibleObjC = true; 2665 return true; 2666 } 2667 } 2668 2669 return false; 2670 } 2671 2672 /// Determine whether this is an Objective-C writeback conversion, 2673 /// used for parameter passing when performing automatic reference counting. 2674 /// 2675 /// \param FromType The type we're converting form. 2676 /// 2677 /// \param ToType The type we're converting to. 2678 /// 2679 /// \param ConvertedType The type that will be produced after applying 2680 /// this conversion. 2681 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2682 QualType &ConvertedType) { 2683 if (!getLangOpts().ObjCAutoRefCount || 2684 Context.hasSameUnqualifiedType(FromType, ToType)) 2685 return false; 2686 2687 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2688 QualType ToPointee; 2689 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2690 ToPointee = ToPointer->getPointeeType(); 2691 else 2692 return false; 2693 2694 Qualifiers ToQuals = ToPointee.getQualifiers(); 2695 if (!ToPointee->isObjCLifetimeType() || 2696 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2697 !ToQuals.withoutObjCLifetime().empty()) 2698 return false; 2699 2700 // Argument must be a pointer to __strong to __weak. 2701 QualType FromPointee; 2702 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2703 FromPointee = FromPointer->getPointeeType(); 2704 else 2705 return false; 2706 2707 Qualifiers FromQuals = FromPointee.getQualifiers(); 2708 if (!FromPointee->isObjCLifetimeType() || 2709 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2710 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2711 return false; 2712 2713 // Make sure that we have compatible qualifiers. 2714 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2715 if (!ToQuals.compatiblyIncludes(FromQuals)) 2716 return false; 2717 2718 // Remove qualifiers from the pointee type we're converting from; they 2719 // aren't used in the compatibility check belong, and we'll be adding back 2720 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2721 FromPointee = FromPointee.getUnqualifiedType(); 2722 2723 // The unqualified form of the pointee types must be compatible. 2724 ToPointee = ToPointee.getUnqualifiedType(); 2725 bool IncompatibleObjC; 2726 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2727 FromPointee = ToPointee; 2728 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2729 IncompatibleObjC)) 2730 return false; 2731 2732 /// Construct the type we're converting to, which is a pointer to 2733 /// __autoreleasing pointee. 2734 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2735 ConvertedType = Context.getPointerType(FromPointee); 2736 return true; 2737 } 2738 2739 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2740 QualType& ConvertedType) { 2741 QualType ToPointeeType; 2742 if (const BlockPointerType *ToBlockPtr = 2743 ToType->getAs<BlockPointerType>()) 2744 ToPointeeType = ToBlockPtr->getPointeeType(); 2745 else 2746 return false; 2747 2748 QualType FromPointeeType; 2749 if (const BlockPointerType *FromBlockPtr = 2750 FromType->getAs<BlockPointerType>()) 2751 FromPointeeType = FromBlockPtr->getPointeeType(); 2752 else 2753 return false; 2754 // We have pointer to blocks, check whether the only 2755 // differences in the argument and result types are in Objective-C 2756 // pointer conversions. If so, we permit the conversion. 2757 2758 const FunctionProtoType *FromFunctionType 2759 = FromPointeeType->getAs<FunctionProtoType>(); 2760 const FunctionProtoType *ToFunctionType 2761 = ToPointeeType->getAs<FunctionProtoType>(); 2762 2763 if (!FromFunctionType || !ToFunctionType) 2764 return false; 2765 2766 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2767 return true; 2768 2769 // Perform the quick checks that will tell us whether these 2770 // function types are obviously different. 2771 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2772 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2773 return false; 2774 2775 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2776 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2777 if (FromEInfo != ToEInfo) 2778 return false; 2779 2780 bool IncompatibleObjC = false; 2781 if (Context.hasSameType(FromFunctionType->getReturnType(), 2782 ToFunctionType->getReturnType())) { 2783 // Okay, the types match exactly. Nothing to do. 2784 } else { 2785 QualType RHS = FromFunctionType->getReturnType(); 2786 QualType LHS = ToFunctionType->getReturnType(); 2787 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2788 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2789 LHS = LHS.getUnqualifiedType(); 2790 2791 if (Context.hasSameType(RHS,LHS)) { 2792 // OK exact match. 2793 } else if (isObjCPointerConversion(RHS, LHS, 2794 ConvertedType, IncompatibleObjC)) { 2795 if (IncompatibleObjC) 2796 return false; 2797 // Okay, we have an Objective-C pointer conversion. 2798 } 2799 else 2800 return false; 2801 } 2802 2803 // Check argument types. 2804 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2805 ArgIdx != NumArgs; ++ArgIdx) { 2806 IncompatibleObjC = false; 2807 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2808 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2809 if (Context.hasSameType(FromArgType, ToArgType)) { 2810 // Okay, the types match exactly. Nothing to do. 2811 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2812 ConvertedType, IncompatibleObjC)) { 2813 if (IncompatibleObjC) 2814 return false; 2815 // Okay, we have an Objective-C pointer conversion. 2816 } else 2817 // Argument types are too different. Abort. 2818 return false; 2819 } 2820 2821 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2822 bool CanUseToFPT, CanUseFromFPT; 2823 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2824 CanUseToFPT, CanUseFromFPT, 2825 NewParamInfos)) 2826 return false; 2827 2828 ConvertedType = ToType; 2829 return true; 2830 } 2831 2832 enum { 2833 ft_default, 2834 ft_different_class, 2835 ft_parameter_arity, 2836 ft_parameter_mismatch, 2837 ft_return_type, 2838 ft_qualifer_mismatch, 2839 ft_noexcept 2840 }; 2841 2842 /// Attempts to get the FunctionProtoType from a Type. Handles 2843 /// MemberFunctionPointers properly. 2844 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2845 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2846 return FPT; 2847 2848 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2849 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2850 2851 return nullptr; 2852 } 2853 2854 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2855 /// function types. Catches different number of parameter, mismatch in 2856 /// parameter types, and different return types. 2857 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2858 QualType FromType, QualType ToType) { 2859 // If either type is not valid, include no extra info. 2860 if (FromType.isNull() || ToType.isNull()) { 2861 PDiag << ft_default; 2862 return; 2863 } 2864 2865 // Get the function type from the pointers. 2866 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2867 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2868 *ToMember = ToType->castAs<MemberPointerType>(); 2869 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2870 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2871 << QualType(FromMember->getClass(), 0); 2872 return; 2873 } 2874 FromType = FromMember->getPointeeType(); 2875 ToType = ToMember->getPointeeType(); 2876 } 2877 2878 if (FromType->isPointerType()) 2879 FromType = FromType->getPointeeType(); 2880 if (ToType->isPointerType()) 2881 ToType = ToType->getPointeeType(); 2882 2883 // Remove references. 2884 FromType = FromType.getNonReferenceType(); 2885 ToType = ToType.getNonReferenceType(); 2886 2887 // Don't print extra info for non-specialized template functions. 2888 if (FromType->isInstantiationDependentType() && 2889 !FromType->getAs<TemplateSpecializationType>()) { 2890 PDiag << ft_default; 2891 return; 2892 } 2893 2894 // No extra info for same types. 2895 if (Context.hasSameType(FromType, ToType)) { 2896 PDiag << ft_default; 2897 return; 2898 } 2899 2900 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2901 *ToFunction = tryGetFunctionProtoType(ToType); 2902 2903 // Both types need to be function types. 2904 if (!FromFunction || !ToFunction) { 2905 PDiag << ft_default; 2906 return; 2907 } 2908 2909 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2910 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2911 << FromFunction->getNumParams(); 2912 return; 2913 } 2914 2915 // Handle different parameter types. 2916 unsigned ArgPos; 2917 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2918 PDiag << ft_parameter_mismatch << ArgPos + 1 2919 << ToFunction->getParamType(ArgPos) 2920 << FromFunction->getParamType(ArgPos); 2921 return; 2922 } 2923 2924 // Handle different return type. 2925 if (!Context.hasSameType(FromFunction->getReturnType(), 2926 ToFunction->getReturnType())) { 2927 PDiag << ft_return_type << ToFunction->getReturnType() 2928 << FromFunction->getReturnType(); 2929 return; 2930 } 2931 2932 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2933 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2934 << FromFunction->getMethodQuals(); 2935 return; 2936 } 2937 2938 // Handle exception specification differences on canonical type (in C++17 2939 // onwards). 2940 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2941 ->isNothrow() != 2942 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2943 ->isNothrow()) { 2944 PDiag << ft_noexcept; 2945 return; 2946 } 2947 2948 // Unable to find a difference, so add no extra info. 2949 PDiag << ft_default; 2950 } 2951 2952 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2953 /// for equality of their argument types. Caller has already checked that 2954 /// they have same number of arguments. If the parameters are different, 2955 /// ArgPos will have the parameter index of the first different parameter. 2956 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2957 const FunctionProtoType *NewType, 2958 unsigned *ArgPos) { 2959 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2960 N = NewType->param_type_begin(), 2961 E = OldType->param_type_end(); 2962 O && (O != E); ++O, ++N) { 2963 // Ignore address spaces in pointee type. This is to disallow overloading 2964 // on __ptr32/__ptr64 address spaces. 2965 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2966 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2967 2968 if (!Context.hasSameType(Old, New)) { 2969 if (ArgPos) 2970 *ArgPos = O - OldType->param_type_begin(); 2971 return false; 2972 } 2973 } 2974 return true; 2975 } 2976 2977 /// CheckPointerConversion - Check the pointer conversion from the 2978 /// expression From to the type ToType. This routine checks for 2979 /// ambiguous or inaccessible derived-to-base pointer 2980 /// conversions for which IsPointerConversion has already returned 2981 /// true. It returns true and produces a diagnostic if there was an 2982 /// error, or returns false otherwise. 2983 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2984 CastKind &Kind, 2985 CXXCastPath& BasePath, 2986 bool IgnoreBaseAccess, 2987 bool Diagnose) { 2988 QualType FromType = From->getType(); 2989 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2990 2991 Kind = CK_BitCast; 2992 2993 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2994 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2995 Expr::NPCK_ZeroExpression) { 2996 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2997 DiagRuntimeBehavior(From->getExprLoc(), From, 2998 PDiag(diag::warn_impcast_bool_to_null_pointer) 2999 << ToType << From->getSourceRange()); 3000 else if (!isUnevaluatedContext()) 3001 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3002 << ToType << From->getSourceRange(); 3003 } 3004 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3005 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3006 QualType FromPointeeType = FromPtrType->getPointeeType(), 3007 ToPointeeType = ToPtrType->getPointeeType(); 3008 3009 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3010 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3011 // We must have a derived-to-base conversion. Check an 3012 // ambiguous or inaccessible conversion. 3013 unsigned InaccessibleID = 0; 3014 unsigned AmbiguousID = 0; 3015 if (Diagnose) { 3016 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3017 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3018 } 3019 if (CheckDerivedToBaseConversion( 3020 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3021 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3022 &BasePath, IgnoreBaseAccess)) 3023 return true; 3024 3025 // The conversion was successful. 3026 Kind = CK_DerivedToBase; 3027 } 3028 3029 if (Diagnose && !IsCStyleOrFunctionalCast && 3030 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3031 assert(getLangOpts().MSVCCompat && 3032 "this should only be possible with MSVCCompat!"); 3033 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3034 << From->getSourceRange(); 3035 } 3036 } 3037 } else if (const ObjCObjectPointerType *ToPtrType = 3038 ToType->getAs<ObjCObjectPointerType>()) { 3039 if (const ObjCObjectPointerType *FromPtrType = 3040 FromType->getAs<ObjCObjectPointerType>()) { 3041 // Objective-C++ conversions are always okay. 3042 // FIXME: We should have a different class of conversions for the 3043 // Objective-C++ implicit conversions. 3044 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3045 return false; 3046 } else if (FromType->isBlockPointerType()) { 3047 Kind = CK_BlockPointerToObjCPointerCast; 3048 } else { 3049 Kind = CK_CPointerToObjCPointerCast; 3050 } 3051 } else if (ToType->isBlockPointerType()) { 3052 if (!FromType->isBlockPointerType()) 3053 Kind = CK_AnyPointerToBlockPointerCast; 3054 } 3055 3056 // We shouldn't fall into this case unless it's valid for other 3057 // reasons. 3058 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3059 Kind = CK_NullToPointer; 3060 3061 return false; 3062 } 3063 3064 /// IsMemberPointerConversion - Determines whether the conversion of the 3065 /// expression From, which has the (possibly adjusted) type FromType, can be 3066 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3067 /// If so, returns true and places the converted type (that might differ from 3068 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3069 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3070 QualType ToType, 3071 bool InOverloadResolution, 3072 QualType &ConvertedType) { 3073 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3074 if (!ToTypePtr) 3075 return false; 3076 3077 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3078 if (From->isNullPointerConstant(Context, 3079 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3080 : Expr::NPC_ValueDependentIsNull)) { 3081 ConvertedType = ToType; 3082 return true; 3083 } 3084 3085 // Otherwise, both types have to be member pointers. 3086 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3087 if (!FromTypePtr) 3088 return false; 3089 3090 // A pointer to member of B can be converted to a pointer to member of D, 3091 // where D is derived from B (C++ 4.11p2). 3092 QualType FromClass(FromTypePtr->getClass(), 0); 3093 QualType ToClass(ToTypePtr->getClass(), 0); 3094 3095 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3096 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3097 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3098 ToClass.getTypePtr()); 3099 return true; 3100 } 3101 3102 return false; 3103 } 3104 3105 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3106 /// expression From to the type ToType. This routine checks for ambiguous or 3107 /// virtual or inaccessible base-to-derived member pointer conversions 3108 /// for which IsMemberPointerConversion has already returned true. It returns 3109 /// true and produces a diagnostic if there was an error, or returns false 3110 /// otherwise. 3111 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3112 CastKind &Kind, 3113 CXXCastPath &BasePath, 3114 bool IgnoreBaseAccess) { 3115 QualType FromType = From->getType(); 3116 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3117 if (!FromPtrType) { 3118 // This must be a null pointer to member pointer conversion 3119 assert(From->isNullPointerConstant(Context, 3120 Expr::NPC_ValueDependentIsNull) && 3121 "Expr must be null pointer constant!"); 3122 Kind = CK_NullToMemberPointer; 3123 return false; 3124 } 3125 3126 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3127 assert(ToPtrType && "No member pointer cast has a target type " 3128 "that is not a member pointer."); 3129 3130 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3131 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3132 3133 // FIXME: What about dependent types? 3134 assert(FromClass->isRecordType() && "Pointer into non-class."); 3135 assert(ToClass->isRecordType() && "Pointer into non-class."); 3136 3137 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3138 /*DetectVirtual=*/true); 3139 bool DerivationOkay = 3140 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3141 assert(DerivationOkay && 3142 "Should not have been called if derivation isn't OK."); 3143 (void)DerivationOkay; 3144 3145 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3146 getUnqualifiedType())) { 3147 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3148 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3149 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3150 return true; 3151 } 3152 3153 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3154 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3155 << FromClass << ToClass << QualType(VBase, 0) 3156 << From->getSourceRange(); 3157 return true; 3158 } 3159 3160 if (!IgnoreBaseAccess) 3161 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3162 Paths.front(), 3163 diag::err_downcast_from_inaccessible_base); 3164 3165 // Must be a base to derived member conversion. 3166 BuildBasePathArray(Paths, BasePath); 3167 Kind = CK_BaseToDerivedMemberPointer; 3168 return false; 3169 } 3170 3171 /// Determine whether the lifetime conversion between the two given 3172 /// qualifiers sets is nontrivial. 3173 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3174 Qualifiers ToQuals) { 3175 // Converting anything to const __unsafe_unretained is trivial. 3176 if (ToQuals.hasConst() && 3177 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3178 return false; 3179 3180 return true; 3181 } 3182 3183 /// Perform a single iteration of the loop for checking if a qualification 3184 /// conversion is valid. 3185 /// 3186 /// Specifically, check whether any change between the qualifiers of \p 3187 /// FromType and \p ToType is permissible, given knowledge about whether every 3188 /// outer layer is const-qualified. 3189 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3190 bool CStyle, bool IsTopLevel, 3191 bool &PreviousToQualsIncludeConst, 3192 bool &ObjCLifetimeConversion) { 3193 Qualifiers FromQuals = FromType.getQualifiers(); 3194 Qualifiers ToQuals = ToType.getQualifiers(); 3195 3196 // Ignore __unaligned qualifier if this type is void. 3197 if (ToType.getUnqualifiedType()->isVoidType()) 3198 FromQuals.removeUnaligned(); 3199 3200 // Objective-C ARC: 3201 // Check Objective-C lifetime conversions. 3202 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3203 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3204 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3205 ObjCLifetimeConversion = true; 3206 FromQuals.removeObjCLifetime(); 3207 ToQuals.removeObjCLifetime(); 3208 } else { 3209 // Qualification conversions cannot cast between different 3210 // Objective-C lifetime qualifiers. 3211 return false; 3212 } 3213 } 3214 3215 // Allow addition/removal of GC attributes but not changing GC attributes. 3216 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3217 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3218 FromQuals.removeObjCGCAttr(); 3219 ToQuals.removeObjCGCAttr(); 3220 } 3221 3222 // -- for every j > 0, if const is in cv 1,j then const is in cv 3223 // 2,j, and similarly for volatile. 3224 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3225 return false; 3226 3227 // If address spaces mismatch: 3228 // - in top level it is only valid to convert to addr space that is a 3229 // superset in all cases apart from C-style casts where we allow 3230 // conversions between overlapping address spaces. 3231 // - in non-top levels it is not a valid conversion. 3232 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3233 (!IsTopLevel || 3234 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3235 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3236 return false; 3237 3238 // -- if the cv 1,j and cv 2,j are different, then const is in 3239 // every cv for 0 < k < j. 3240 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3241 !PreviousToQualsIncludeConst) 3242 return false; 3243 3244 // Keep track of whether all prior cv-qualifiers in the "to" type 3245 // include const. 3246 PreviousToQualsIncludeConst = 3247 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3248 return true; 3249 } 3250 3251 /// IsQualificationConversion - Determines whether the conversion from 3252 /// an rvalue of type FromType to ToType is a qualification conversion 3253 /// (C++ 4.4). 3254 /// 3255 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3256 /// when the qualification conversion involves a change in the Objective-C 3257 /// object lifetime. 3258 bool 3259 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3260 bool CStyle, bool &ObjCLifetimeConversion) { 3261 FromType = Context.getCanonicalType(FromType); 3262 ToType = Context.getCanonicalType(ToType); 3263 ObjCLifetimeConversion = false; 3264 3265 // If FromType and ToType are the same type, this is not a 3266 // qualification conversion. 3267 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3268 return false; 3269 3270 // (C++ 4.4p4): 3271 // A conversion can add cv-qualifiers at levels other than the first 3272 // in multi-level pointers, subject to the following rules: [...] 3273 bool PreviousToQualsIncludeConst = true; 3274 bool UnwrappedAnyPointer = false; 3275 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3276 if (!isQualificationConversionStep( 3277 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3278 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3279 return false; 3280 UnwrappedAnyPointer = true; 3281 } 3282 3283 // We are left with FromType and ToType being the pointee types 3284 // after unwrapping the original FromType and ToType the same number 3285 // of times. If we unwrapped any pointers, and if FromType and 3286 // ToType have the same unqualified type (since we checked 3287 // qualifiers above), then this is a qualification conversion. 3288 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3289 } 3290 3291 /// - Determine whether this is a conversion from a scalar type to an 3292 /// atomic type. 3293 /// 3294 /// If successful, updates \c SCS's second and third steps in the conversion 3295 /// sequence to finish the conversion. 3296 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3297 bool InOverloadResolution, 3298 StandardConversionSequence &SCS, 3299 bool CStyle) { 3300 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3301 if (!ToAtomic) 3302 return false; 3303 3304 StandardConversionSequence InnerSCS; 3305 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3306 InOverloadResolution, InnerSCS, 3307 CStyle, /*AllowObjCWritebackConversion=*/false)) 3308 return false; 3309 3310 SCS.Second = InnerSCS.Second; 3311 SCS.setToType(1, InnerSCS.getToType(1)); 3312 SCS.Third = InnerSCS.Third; 3313 SCS.QualificationIncludesObjCLifetime 3314 = InnerSCS.QualificationIncludesObjCLifetime; 3315 SCS.setToType(2, InnerSCS.getToType(2)); 3316 return true; 3317 } 3318 3319 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3320 CXXConstructorDecl *Constructor, 3321 QualType Type) { 3322 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3323 if (CtorType->getNumParams() > 0) { 3324 QualType FirstArg = CtorType->getParamType(0); 3325 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3326 return true; 3327 } 3328 return false; 3329 } 3330 3331 static OverloadingResult 3332 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3333 CXXRecordDecl *To, 3334 UserDefinedConversionSequence &User, 3335 OverloadCandidateSet &CandidateSet, 3336 bool AllowExplicit) { 3337 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3338 for (auto *D : S.LookupConstructors(To)) { 3339 auto Info = getConstructorInfo(D); 3340 if (!Info) 3341 continue; 3342 3343 bool Usable = !Info.Constructor->isInvalidDecl() && 3344 S.isInitListConstructor(Info.Constructor); 3345 if (Usable) { 3346 // If the first argument is (a reference to) the target type, 3347 // suppress conversions. 3348 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3349 S.Context, Info.Constructor, ToType); 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 if (SuppressUserConversions && ListInitializing) { 3474 SuppressUserConversions = false; 3475 if (NumArgs == 1) { 3476 // If the first argument is (a reference to) the target type, 3477 // suppress conversions. 3478 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3479 S.Context, Info.Constructor, ToType); 3480 } 3481 } 3482 if (Info.ConstructorTmpl) 3483 S.AddTemplateOverloadCandidate( 3484 Info.ConstructorTmpl, Info.FoundDecl, 3485 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3486 CandidateSet, SuppressUserConversions, 3487 /*PartialOverloading*/ false, 3488 AllowExplicit == AllowedExplicit::All); 3489 else 3490 // Allow one user-defined conversion when user specifies a 3491 // From->ToType conversion via an static cast (c-style, etc). 3492 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3493 llvm::makeArrayRef(Args, NumArgs), 3494 CandidateSet, SuppressUserConversions, 3495 /*PartialOverloading*/ false, 3496 AllowExplicit == AllowedExplicit::All); 3497 } 3498 } 3499 } 3500 } 3501 3502 // Enumerate conversion functions, if we're allowed to. 3503 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3504 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3505 // No conversion functions from incomplete types. 3506 } else if (const RecordType *FromRecordType = 3507 From->getType()->getAs<RecordType>()) { 3508 if (CXXRecordDecl *FromRecordDecl 3509 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3510 // Add all of the conversion functions as candidates. 3511 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3512 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3513 DeclAccessPair FoundDecl = I.getPair(); 3514 NamedDecl *D = FoundDecl.getDecl(); 3515 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3516 if (isa<UsingShadowDecl>(D)) 3517 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3518 3519 CXXConversionDecl *Conv; 3520 FunctionTemplateDecl *ConvTemplate; 3521 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3522 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3523 else 3524 Conv = cast<CXXConversionDecl>(D); 3525 3526 if (ConvTemplate) 3527 S.AddTemplateConversionCandidate( 3528 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3529 CandidateSet, AllowObjCConversionOnExplicit, 3530 AllowExplicit != AllowedExplicit::None); 3531 else 3532 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3533 CandidateSet, AllowObjCConversionOnExplicit, 3534 AllowExplicit != AllowedExplicit::None); 3535 } 3536 } 3537 } 3538 3539 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3540 3541 OverloadCandidateSet::iterator Best; 3542 switch (auto Result = 3543 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3544 case OR_Success: 3545 case OR_Deleted: 3546 // Record the standard conversion we used and the conversion function. 3547 if (CXXConstructorDecl *Constructor 3548 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3549 // C++ [over.ics.user]p1: 3550 // If the user-defined conversion is specified by a 3551 // constructor (12.3.1), the initial standard conversion 3552 // sequence converts the source type to the type required by 3553 // the argument of the constructor. 3554 // 3555 QualType ThisType = Constructor->getThisType(); 3556 if (isa<InitListExpr>(From)) { 3557 // Initializer lists don't have conversions as such. 3558 User.Before.setAsIdentityConversion(); 3559 } else { 3560 if (Best->Conversions[0].isEllipsis()) 3561 User.EllipsisConversion = true; 3562 else { 3563 User.Before = Best->Conversions[0].Standard; 3564 User.EllipsisConversion = false; 3565 } 3566 } 3567 User.HadMultipleCandidates = HadMultipleCandidates; 3568 User.ConversionFunction = Constructor; 3569 User.FoundConversionFunction = Best->FoundDecl; 3570 User.After.setAsIdentityConversion(); 3571 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3572 User.After.setAllToTypes(ToType); 3573 return Result; 3574 } 3575 if (CXXConversionDecl *Conversion 3576 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3577 // C++ [over.ics.user]p1: 3578 // 3579 // [...] If the user-defined conversion is specified by a 3580 // conversion function (12.3.2), the initial standard 3581 // conversion sequence converts the source type to the 3582 // implicit object parameter of the conversion function. 3583 User.Before = Best->Conversions[0].Standard; 3584 User.HadMultipleCandidates = HadMultipleCandidates; 3585 User.ConversionFunction = Conversion; 3586 User.FoundConversionFunction = Best->FoundDecl; 3587 User.EllipsisConversion = false; 3588 3589 // C++ [over.ics.user]p2: 3590 // The second standard conversion sequence converts the 3591 // result of the user-defined conversion to the target type 3592 // for the sequence. Since an implicit conversion sequence 3593 // is an initialization, the special rules for 3594 // initialization by user-defined conversion apply when 3595 // selecting the best user-defined conversion for a 3596 // user-defined conversion sequence (see 13.3.3 and 3597 // 13.3.3.1). 3598 User.After = Best->FinalConversion; 3599 return Result; 3600 } 3601 llvm_unreachable("Not a constructor or conversion function?"); 3602 3603 case OR_No_Viable_Function: 3604 return OR_No_Viable_Function; 3605 3606 case OR_Ambiguous: 3607 return OR_Ambiguous; 3608 } 3609 3610 llvm_unreachable("Invalid OverloadResult!"); 3611 } 3612 3613 bool 3614 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3615 ImplicitConversionSequence ICS; 3616 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3617 OverloadCandidateSet::CSK_Normal); 3618 OverloadingResult OvResult = 3619 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3620 CandidateSet, AllowedExplicit::None, false); 3621 3622 if (!(OvResult == OR_Ambiguous || 3623 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3624 return false; 3625 3626 auto Cands = CandidateSet.CompleteCandidates( 3627 *this, 3628 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3629 From); 3630 if (OvResult == OR_Ambiguous) 3631 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3632 << From->getType() << ToType << From->getSourceRange(); 3633 else { // OR_No_Viable_Function && !CandidateSet.empty() 3634 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3635 diag::err_typecheck_nonviable_condition_incomplete, 3636 From->getType(), From->getSourceRange())) 3637 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3638 << false << From->getType() << From->getSourceRange() << ToType; 3639 } 3640 3641 CandidateSet.NoteCandidates( 3642 *this, From, Cands); 3643 return true; 3644 } 3645 3646 /// Compare the user-defined conversion functions or constructors 3647 /// of two user-defined conversion sequences to determine whether any ordering 3648 /// is possible. 3649 static ImplicitConversionSequence::CompareKind 3650 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3651 FunctionDecl *Function2) { 3652 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3653 return ImplicitConversionSequence::Indistinguishable; 3654 3655 // Objective-C++: 3656 // If both conversion functions are implicitly-declared conversions from 3657 // a lambda closure type to a function pointer and a block pointer, 3658 // respectively, always prefer the conversion to a function pointer, 3659 // because the function pointer is more lightweight and is more likely 3660 // to keep code working. 3661 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3662 if (!Conv1) 3663 return ImplicitConversionSequence::Indistinguishable; 3664 3665 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3666 if (!Conv2) 3667 return ImplicitConversionSequence::Indistinguishable; 3668 3669 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3670 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3671 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3672 if (Block1 != Block2) 3673 return Block1 ? ImplicitConversionSequence::Worse 3674 : ImplicitConversionSequence::Better; 3675 } 3676 3677 return ImplicitConversionSequence::Indistinguishable; 3678 } 3679 3680 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3681 const ImplicitConversionSequence &ICS) { 3682 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3683 (ICS.isUserDefined() && 3684 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3685 } 3686 3687 /// CompareImplicitConversionSequences - Compare two implicit 3688 /// conversion sequences to determine whether one is better than the 3689 /// other or if they are indistinguishable (C++ 13.3.3.2). 3690 static ImplicitConversionSequence::CompareKind 3691 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3692 const ImplicitConversionSequence& ICS1, 3693 const ImplicitConversionSequence& ICS2) 3694 { 3695 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3696 // conversion sequences (as defined in 13.3.3.1) 3697 // -- a standard conversion sequence (13.3.3.1.1) is a better 3698 // conversion sequence than a user-defined conversion sequence or 3699 // an ellipsis conversion sequence, and 3700 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3701 // conversion sequence than an ellipsis conversion sequence 3702 // (13.3.3.1.3). 3703 // 3704 // C++0x [over.best.ics]p10: 3705 // For the purpose of ranking implicit conversion sequences as 3706 // described in 13.3.3.2, the ambiguous conversion sequence is 3707 // treated as a user-defined sequence that is indistinguishable 3708 // from any other user-defined conversion sequence. 3709 3710 // String literal to 'char *' conversion has been deprecated in C++03. It has 3711 // been removed from C++11. We still accept this conversion, if it happens at 3712 // the best viable function. Otherwise, this conversion is considered worse 3713 // than ellipsis conversion. Consider this as an extension; this is not in the 3714 // standard. For example: 3715 // 3716 // int &f(...); // #1 3717 // void f(char*); // #2 3718 // void g() { int &r = f("foo"); } 3719 // 3720 // In C++03, we pick #2 as the best viable function. 3721 // In C++11, we pick #1 as the best viable function, because ellipsis 3722 // conversion is better than string-literal to char* conversion (since there 3723 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3724 // convert arguments, #2 would be the best viable function in C++11. 3725 // If the best viable function has this conversion, a warning will be issued 3726 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3727 3728 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3729 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3730 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3731 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3732 ? ImplicitConversionSequence::Worse 3733 : ImplicitConversionSequence::Better; 3734 3735 if (ICS1.getKindRank() < ICS2.getKindRank()) 3736 return ImplicitConversionSequence::Better; 3737 if (ICS2.getKindRank() < ICS1.getKindRank()) 3738 return ImplicitConversionSequence::Worse; 3739 3740 // The following checks require both conversion sequences to be of 3741 // the same kind. 3742 if (ICS1.getKind() != ICS2.getKind()) 3743 return ImplicitConversionSequence::Indistinguishable; 3744 3745 ImplicitConversionSequence::CompareKind Result = 3746 ImplicitConversionSequence::Indistinguishable; 3747 3748 // Two implicit conversion sequences of the same form are 3749 // indistinguishable conversion sequences unless one of the 3750 // following rules apply: (C++ 13.3.3.2p3): 3751 3752 // List-initialization sequence L1 is a better conversion sequence than 3753 // list-initialization sequence L2 if: 3754 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3755 // if not that, 3756 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3757 // and N1 is smaller than N2., 3758 // even if one of the other rules in this paragraph would otherwise apply. 3759 if (!ICS1.isBad()) { 3760 if (ICS1.isStdInitializerListElement() && 3761 !ICS2.isStdInitializerListElement()) 3762 return ImplicitConversionSequence::Better; 3763 if (!ICS1.isStdInitializerListElement() && 3764 ICS2.isStdInitializerListElement()) 3765 return ImplicitConversionSequence::Worse; 3766 } 3767 3768 if (ICS1.isStandard()) 3769 // Standard conversion sequence S1 is a better conversion sequence than 3770 // standard conversion sequence S2 if [...] 3771 Result = CompareStandardConversionSequences(S, Loc, 3772 ICS1.Standard, ICS2.Standard); 3773 else if (ICS1.isUserDefined()) { 3774 // User-defined conversion sequence U1 is a better conversion 3775 // sequence than another user-defined conversion sequence U2 if 3776 // they contain the same user-defined conversion function or 3777 // constructor and if the second standard conversion sequence of 3778 // U1 is better than the second standard conversion sequence of 3779 // U2 (C++ 13.3.3.2p3). 3780 if (ICS1.UserDefined.ConversionFunction == 3781 ICS2.UserDefined.ConversionFunction) 3782 Result = CompareStandardConversionSequences(S, Loc, 3783 ICS1.UserDefined.After, 3784 ICS2.UserDefined.After); 3785 else 3786 Result = compareConversionFunctions(S, 3787 ICS1.UserDefined.ConversionFunction, 3788 ICS2.UserDefined.ConversionFunction); 3789 } 3790 3791 return Result; 3792 } 3793 3794 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3795 // determine if one is a proper subset of the other. 3796 static ImplicitConversionSequence::CompareKind 3797 compareStandardConversionSubsets(ASTContext &Context, 3798 const StandardConversionSequence& SCS1, 3799 const StandardConversionSequence& SCS2) { 3800 ImplicitConversionSequence::CompareKind Result 3801 = ImplicitConversionSequence::Indistinguishable; 3802 3803 // the identity conversion sequence is considered to be a subsequence of 3804 // any non-identity conversion sequence 3805 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3806 return ImplicitConversionSequence::Better; 3807 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3808 return ImplicitConversionSequence::Worse; 3809 3810 if (SCS1.Second != SCS2.Second) { 3811 if (SCS1.Second == ICK_Identity) 3812 Result = ImplicitConversionSequence::Better; 3813 else if (SCS2.Second == ICK_Identity) 3814 Result = ImplicitConversionSequence::Worse; 3815 else 3816 return ImplicitConversionSequence::Indistinguishable; 3817 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3818 return ImplicitConversionSequence::Indistinguishable; 3819 3820 if (SCS1.Third == SCS2.Third) { 3821 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3822 : ImplicitConversionSequence::Indistinguishable; 3823 } 3824 3825 if (SCS1.Third == ICK_Identity) 3826 return Result == ImplicitConversionSequence::Worse 3827 ? ImplicitConversionSequence::Indistinguishable 3828 : ImplicitConversionSequence::Better; 3829 3830 if (SCS2.Third == ICK_Identity) 3831 return Result == ImplicitConversionSequence::Better 3832 ? ImplicitConversionSequence::Indistinguishable 3833 : ImplicitConversionSequence::Worse; 3834 3835 return ImplicitConversionSequence::Indistinguishable; 3836 } 3837 3838 /// Determine whether one of the given reference bindings is better 3839 /// than the other based on what kind of bindings they are. 3840 static bool 3841 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3842 const StandardConversionSequence &SCS2) { 3843 // C++0x [over.ics.rank]p3b4: 3844 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3845 // implicit object parameter of a non-static member function declared 3846 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3847 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3848 // lvalue reference to a function lvalue and S2 binds an rvalue 3849 // reference*. 3850 // 3851 // FIXME: Rvalue references. We're going rogue with the above edits, 3852 // because the semantics in the current C++0x working paper (N3225 at the 3853 // time of this writing) break the standard definition of std::forward 3854 // and std::reference_wrapper when dealing with references to functions. 3855 // Proposed wording changes submitted to CWG for consideration. 3856 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3857 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3858 return false; 3859 3860 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3861 SCS2.IsLvalueReference) || 3862 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3863 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3864 } 3865 3866 enum class FixedEnumPromotion { 3867 None, 3868 ToUnderlyingType, 3869 ToPromotedUnderlyingType 3870 }; 3871 3872 /// Returns kind of fixed enum promotion the \a SCS uses. 3873 static FixedEnumPromotion 3874 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3875 3876 if (SCS.Second != ICK_Integral_Promotion) 3877 return FixedEnumPromotion::None; 3878 3879 QualType FromType = SCS.getFromType(); 3880 if (!FromType->isEnumeralType()) 3881 return FixedEnumPromotion::None; 3882 3883 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3884 if (!Enum->isFixed()) 3885 return FixedEnumPromotion::None; 3886 3887 QualType UnderlyingType = Enum->getIntegerType(); 3888 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3889 return FixedEnumPromotion::ToUnderlyingType; 3890 3891 return FixedEnumPromotion::ToPromotedUnderlyingType; 3892 } 3893 3894 /// CompareStandardConversionSequences - Compare two standard 3895 /// conversion sequences to determine whether one is better than the 3896 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3897 static ImplicitConversionSequence::CompareKind 3898 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3899 const StandardConversionSequence& SCS1, 3900 const StandardConversionSequence& SCS2) 3901 { 3902 // Standard conversion sequence S1 is a better conversion sequence 3903 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3904 3905 // -- S1 is a proper subsequence of S2 (comparing the conversion 3906 // sequences in the canonical form defined by 13.3.3.1.1, 3907 // excluding any Lvalue Transformation; the identity conversion 3908 // sequence is considered to be a subsequence of any 3909 // non-identity conversion sequence) or, if not that, 3910 if (ImplicitConversionSequence::CompareKind CK 3911 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3912 return CK; 3913 3914 // -- the rank of S1 is better than the rank of S2 (by the rules 3915 // defined below), or, if not that, 3916 ImplicitConversionRank Rank1 = SCS1.getRank(); 3917 ImplicitConversionRank Rank2 = SCS2.getRank(); 3918 if (Rank1 < Rank2) 3919 return ImplicitConversionSequence::Better; 3920 else if (Rank2 < Rank1) 3921 return ImplicitConversionSequence::Worse; 3922 3923 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3924 // are indistinguishable unless one of the following rules 3925 // applies: 3926 3927 // A conversion that is not a conversion of a pointer, or 3928 // pointer to member, to bool is better than another conversion 3929 // that is such a conversion. 3930 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3931 return SCS2.isPointerConversionToBool() 3932 ? ImplicitConversionSequence::Better 3933 : ImplicitConversionSequence::Worse; 3934 3935 // C++14 [over.ics.rank]p4b2: 3936 // This is retroactively applied to C++11 by CWG 1601. 3937 // 3938 // A conversion that promotes an enumeration whose underlying type is fixed 3939 // to its underlying type is better than one that promotes to the promoted 3940 // underlying type, if the two are different. 3941 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3942 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3943 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3944 FEP1 != FEP2) 3945 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3946 ? ImplicitConversionSequence::Better 3947 : ImplicitConversionSequence::Worse; 3948 3949 // C++ [over.ics.rank]p4b2: 3950 // 3951 // If class B is derived directly or indirectly from class A, 3952 // conversion of B* to A* is better than conversion of B* to 3953 // void*, and conversion of A* to void* is better than conversion 3954 // of B* to void*. 3955 bool SCS1ConvertsToVoid 3956 = SCS1.isPointerConversionToVoidPointer(S.Context); 3957 bool SCS2ConvertsToVoid 3958 = SCS2.isPointerConversionToVoidPointer(S.Context); 3959 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3960 // Exactly one of the conversion sequences is a conversion to 3961 // a void pointer; it's the worse conversion. 3962 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3963 : ImplicitConversionSequence::Worse; 3964 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3965 // Neither conversion sequence converts to a void pointer; compare 3966 // their derived-to-base conversions. 3967 if (ImplicitConversionSequence::CompareKind DerivedCK 3968 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3969 return DerivedCK; 3970 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3971 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3972 // Both conversion sequences are conversions to void 3973 // pointers. Compare the source types to determine if there's an 3974 // inheritance relationship in their sources. 3975 QualType FromType1 = SCS1.getFromType(); 3976 QualType FromType2 = SCS2.getFromType(); 3977 3978 // Adjust the types we're converting from via the array-to-pointer 3979 // conversion, if we need to. 3980 if (SCS1.First == ICK_Array_To_Pointer) 3981 FromType1 = S.Context.getArrayDecayedType(FromType1); 3982 if (SCS2.First == ICK_Array_To_Pointer) 3983 FromType2 = S.Context.getArrayDecayedType(FromType2); 3984 3985 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3986 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3987 3988 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3989 return ImplicitConversionSequence::Better; 3990 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3991 return ImplicitConversionSequence::Worse; 3992 3993 // Objective-C++: If one interface is more specific than the 3994 // other, it is the better one. 3995 const ObjCObjectPointerType* FromObjCPtr1 3996 = FromType1->getAs<ObjCObjectPointerType>(); 3997 const ObjCObjectPointerType* FromObjCPtr2 3998 = FromType2->getAs<ObjCObjectPointerType>(); 3999 if (FromObjCPtr1 && FromObjCPtr2) { 4000 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4001 FromObjCPtr2); 4002 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4003 FromObjCPtr1); 4004 if (AssignLeft != AssignRight) { 4005 return AssignLeft? ImplicitConversionSequence::Better 4006 : ImplicitConversionSequence::Worse; 4007 } 4008 } 4009 } 4010 4011 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4012 // Check for a better reference binding based on the kind of bindings. 4013 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4014 return ImplicitConversionSequence::Better; 4015 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4016 return ImplicitConversionSequence::Worse; 4017 } 4018 4019 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4020 // bullet 3). 4021 if (ImplicitConversionSequence::CompareKind QualCK 4022 = CompareQualificationConversions(S, SCS1, SCS2)) 4023 return QualCK; 4024 4025 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4026 // C++ [over.ics.rank]p3b4: 4027 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4028 // which the references refer are the same type except for 4029 // top-level cv-qualifiers, and the type to which the reference 4030 // initialized by S2 refers is more cv-qualified than the type 4031 // to which the reference initialized by S1 refers. 4032 QualType T1 = SCS1.getToType(2); 4033 QualType T2 = SCS2.getToType(2); 4034 T1 = S.Context.getCanonicalType(T1); 4035 T2 = S.Context.getCanonicalType(T2); 4036 Qualifiers T1Quals, T2Quals; 4037 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4038 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4039 if (UnqualT1 == UnqualT2) { 4040 // Objective-C++ ARC: If the references refer to objects with different 4041 // lifetimes, prefer bindings that don't change lifetime. 4042 if (SCS1.ObjCLifetimeConversionBinding != 4043 SCS2.ObjCLifetimeConversionBinding) { 4044 return SCS1.ObjCLifetimeConversionBinding 4045 ? ImplicitConversionSequence::Worse 4046 : ImplicitConversionSequence::Better; 4047 } 4048 4049 // If the type is an array type, promote the element qualifiers to the 4050 // type for comparison. 4051 if (isa<ArrayType>(T1) && T1Quals) 4052 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4053 if (isa<ArrayType>(T2) && T2Quals) 4054 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4055 if (T2.isMoreQualifiedThan(T1)) 4056 return ImplicitConversionSequence::Better; 4057 if (T1.isMoreQualifiedThan(T2)) 4058 return ImplicitConversionSequence::Worse; 4059 } 4060 } 4061 4062 // In Microsoft mode, prefer an integral conversion to a 4063 // floating-to-integral conversion if the integral conversion 4064 // is between types of the same size. 4065 // For example: 4066 // void f(float); 4067 // void f(int); 4068 // int main { 4069 // long a; 4070 // f(a); 4071 // } 4072 // Here, MSVC will call f(int) instead of generating a compile error 4073 // as clang will do in standard mode. 4074 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4075 SCS2.Second == ICK_Floating_Integral && 4076 S.Context.getTypeSize(SCS1.getFromType()) == 4077 S.Context.getTypeSize(SCS1.getToType(2))) 4078 return ImplicitConversionSequence::Better; 4079 4080 // Prefer a compatible vector conversion over a lax vector conversion 4081 // For example: 4082 // 4083 // typedef float __v4sf __attribute__((__vector_size__(16))); 4084 // void f(vector float); 4085 // void f(vector signed int); 4086 // int main() { 4087 // __v4sf a; 4088 // f(a); 4089 // } 4090 // Here, we'd like to choose f(vector float) and not 4091 // report an ambiguous call error 4092 if (SCS1.Second == ICK_Vector_Conversion && 4093 SCS2.Second == ICK_Vector_Conversion) { 4094 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4095 SCS1.getFromType(), SCS1.getToType(2)); 4096 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4097 SCS2.getFromType(), SCS2.getToType(2)); 4098 4099 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4100 return SCS1IsCompatibleVectorConversion 4101 ? ImplicitConversionSequence::Better 4102 : ImplicitConversionSequence::Worse; 4103 } 4104 4105 return ImplicitConversionSequence::Indistinguishable; 4106 } 4107 4108 /// CompareQualificationConversions - Compares two standard conversion 4109 /// sequences to determine whether they can be ranked based on their 4110 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4111 static ImplicitConversionSequence::CompareKind 4112 CompareQualificationConversions(Sema &S, 4113 const StandardConversionSequence& SCS1, 4114 const StandardConversionSequence& SCS2) { 4115 // C++ 13.3.3.2p3: 4116 // -- S1 and S2 differ only in their qualification conversion and 4117 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4118 // cv-qualification signature of type T1 is a proper subset of 4119 // the cv-qualification signature of type T2, and S1 is not the 4120 // deprecated string literal array-to-pointer conversion (4.2). 4121 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4122 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4123 return ImplicitConversionSequence::Indistinguishable; 4124 4125 // FIXME: the example in the standard doesn't use a qualification 4126 // conversion (!) 4127 QualType T1 = SCS1.getToType(2); 4128 QualType T2 = SCS2.getToType(2); 4129 T1 = S.Context.getCanonicalType(T1); 4130 T2 = S.Context.getCanonicalType(T2); 4131 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4132 Qualifiers T1Quals, T2Quals; 4133 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4134 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4135 4136 // If the types are the same, we won't learn anything by unwrapping 4137 // them. 4138 if (UnqualT1 == UnqualT2) 4139 return ImplicitConversionSequence::Indistinguishable; 4140 4141 ImplicitConversionSequence::CompareKind Result 4142 = ImplicitConversionSequence::Indistinguishable; 4143 4144 // Objective-C++ ARC: 4145 // Prefer qualification conversions not involving a change in lifetime 4146 // to qualification conversions that do not change lifetime. 4147 if (SCS1.QualificationIncludesObjCLifetime != 4148 SCS2.QualificationIncludesObjCLifetime) { 4149 Result = SCS1.QualificationIncludesObjCLifetime 4150 ? ImplicitConversionSequence::Worse 4151 : ImplicitConversionSequence::Better; 4152 } 4153 4154 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4155 // Within each iteration of the loop, we check the qualifiers to 4156 // determine if this still looks like a qualification 4157 // conversion. Then, if all is well, we unwrap one more level of 4158 // pointers or pointers-to-members and do it all again 4159 // until there are no more pointers or pointers-to-members left 4160 // to unwrap. This essentially mimics what 4161 // IsQualificationConversion does, but here we're checking for a 4162 // strict subset of qualifiers. 4163 if (T1.getQualifiers().withoutObjCLifetime() == 4164 T2.getQualifiers().withoutObjCLifetime()) 4165 // The qualifiers are the same, so this doesn't tell us anything 4166 // about how the sequences rank. 4167 // ObjC ownership quals are omitted above as they interfere with 4168 // the ARC overload rule. 4169 ; 4170 else if (T2.isMoreQualifiedThan(T1)) { 4171 // T1 has fewer qualifiers, so it could be the better sequence. 4172 if (Result == ImplicitConversionSequence::Worse) 4173 // Neither has qualifiers that are a subset of the other's 4174 // qualifiers. 4175 return ImplicitConversionSequence::Indistinguishable; 4176 4177 Result = ImplicitConversionSequence::Better; 4178 } else if (T1.isMoreQualifiedThan(T2)) { 4179 // T2 has fewer qualifiers, so it could be the better sequence. 4180 if (Result == ImplicitConversionSequence::Better) 4181 // Neither has qualifiers that are a subset of the other's 4182 // qualifiers. 4183 return ImplicitConversionSequence::Indistinguishable; 4184 4185 Result = ImplicitConversionSequence::Worse; 4186 } else { 4187 // Qualifiers are disjoint. 4188 return ImplicitConversionSequence::Indistinguishable; 4189 } 4190 4191 // If the types after this point are equivalent, we're done. 4192 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4193 break; 4194 } 4195 4196 // Check that the winning standard conversion sequence isn't using 4197 // the deprecated string literal array to pointer conversion. 4198 switch (Result) { 4199 case ImplicitConversionSequence::Better: 4200 if (SCS1.DeprecatedStringLiteralToCharPtr) 4201 Result = ImplicitConversionSequence::Indistinguishable; 4202 break; 4203 4204 case ImplicitConversionSequence::Indistinguishable: 4205 break; 4206 4207 case ImplicitConversionSequence::Worse: 4208 if (SCS2.DeprecatedStringLiteralToCharPtr) 4209 Result = ImplicitConversionSequence::Indistinguishable; 4210 break; 4211 } 4212 4213 return Result; 4214 } 4215 4216 /// CompareDerivedToBaseConversions - Compares two standard conversion 4217 /// sequences to determine whether they can be ranked based on their 4218 /// various kinds of derived-to-base conversions (C++ 4219 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4220 /// conversions between Objective-C interface types. 4221 static ImplicitConversionSequence::CompareKind 4222 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4223 const StandardConversionSequence& SCS1, 4224 const StandardConversionSequence& SCS2) { 4225 QualType FromType1 = SCS1.getFromType(); 4226 QualType ToType1 = SCS1.getToType(1); 4227 QualType FromType2 = SCS2.getFromType(); 4228 QualType ToType2 = SCS2.getToType(1); 4229 4230 // Adjust the types we're converting from via the array-to-pointer 4231 // conversion, if we need to. 4232 if (SCS1.First == ICK_Array_To_Pointer) 4233 FromType1 = S.Context.getArrayDecayedType(FromType1); 4234 if (SCS2.First == ICK_Array_To_Pointer) 4235 FromType2 = S.Context.getArrayDecayedType(FromType2); 4236 4237 // Canonicalize all of the types. 4238 FromType1 = S.Context.getCanonicalType(FromType1); 4239 ToType1 = S.Context.getCanonicalType(ToType1); 4240 FromType2 = S.Context.getCanonicalType(FromType2); 4241 ToType2 = S.Context.getCanonicalType(ToType2); 4242 4243 // C++ [over.ics.rank]p4b3: 4244 // 4245 // If class B is derived directly or indirectly from class A and 4246 // class C is derived directly or indirectly from B, 4247 // 4248 // Compare based on pointer conversions. 4249 if (SCS1.Second == ICK_Pointer_Conversion && 4250 SCS2.Second == ICK_Pointer_Conversion && 4251 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4252 FromType1->isPointerType() && FromType2->isPointerType() && 4253 ToType1->isPointerType() && ToType2->isPointerType()) { 4254 QualType FromPointee1 = 4255 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4256 QualType ToPointee1 = 4257 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4258 QualType FromPointee2 = 4259 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4260 QualType ToPointee2 = 4261 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4262 4263 // -- conversion of C* to B* is better than conversion of C* to A*, 4264 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4265 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4266 return ImplicitConversionSequence::Better; 4267 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4268 return ImplicitConversionSequence::Worse; 4269 } 4270 4271 // -- conversion of B* to A* is better than conversion of C* to A*, 4272 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4273 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4274 return ImplicitConversionSequence::Better; 4275 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4276 return ImplicitConversionSequence::Worse; 4277 } 4278 } else if (SCS1.Second == ICK_Pointer_Conversion && 4279 SCS2.Second == ICK_Pointer_Conversion) { 4280 const ObjCObjectPointerType *FromPtr1 4281 = FromType1->getAs<ObjCObjectPointerType>(); 4282 const ObjCObjectPointerType *FromPtr2 4283 = FromType2->getAs<ObjCObjectPointerType>(); 4284 const ObjCObjectPointerType *ToPtr1 4285 = ToType1->getAs<ObjCObjectPointerType>(); 4286 const ObjCObjectPointerType *ToPtr2 4287 = ToType2->getAs<ObjCObjectPointerType>(); 4288 4289 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4290 // Apply the same conversion ranking rules for Objective-C pointer types 4291 // that we do for C++ pointers to class types. However, we employ the 4292 // Objective-C pseudo-subtyping relationship used for assignment of 4293 // Objective-C pointer types. 4294 bool FromAssignLeft 4295 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4296 bool FromAssignRight 4297 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4298 bool ToAssignLeft 4299 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4300 bool ToAssignRight 4301 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4302 4303 // A conversion to an a non-id object pointer type or qualified 'id' 4304 // type is better than a conversion to 'id'. 4305 if (ToPtr1->isObjCIdType() && 4306 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4307 return ImplicitConversionSequence::Worse; 4308 if (ToPtr2->isObjCIdType() && 4309 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4310 return ImplicitConversionSequence::Better; 4311 4312 // A conversion to a non-id object pointer type is better than a 4313 // conversion to a qualified 'id' type 4314 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4315 return ImplicitConversionSequence::Worse; 4316 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4317 return ImplicitConversionSequence::Better; 4318 4319 // A conversion to an a non-Class object pointer type or qualified 'Class' 4320 // type is better than a conversion to 'Class'. 4321 if (ToPtr1->isObjCClassType() && 4322 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4323 return ImplicitConversionSequence::Worse; 4324 if (ToPtr2->isObjCClassType() && 4325 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4326 return ImplicitConversionSequence::Better; 4327 4328 // A conversion to a non-Class object pointer type is better than a 4329 // conversion to a qualified 'Class' type. 4330 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4331 return ImplicitConversionSequence::Worse; 4332 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4333 return ImplicitConversionSequence::Better; 4334 4335 // -- "conversion of C* to B* is better than conversion of C* to A*," 4336 if (S.Context.hasSameType(FromType1, FromType2) && 4337 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4338 (ToAssignLeft != ToAssignRight)) { 4339 if (FromPtr1->isSpecialized()) { 4340 // "conversion of B<A> * to B * is better than conversion of B * to 4341 // C *. 4342 bool IsFirstSame = 4343 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4344 bool IsSecondSame = 4345 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4346 if (IsFirstSame) { 4347 if (!IsSecondSame) 4348 return ImplicitConversionSequence::Better; 4349 } else if (IsSecondSame) 4350 return ImplicitConversionSequence::Worse; 4351 } 4352 return ToAssignLeft? ImplicitConversionSequence::Worse 4353 : ImplicitConversionSequence::Better; 4354 } 4355 4356 // -- "conversion of B* to A* is better than conversion of C* to A*," 4357 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4358 (FromAssignLeft != FromAssignRight)) 4359 return FromAssignLeft? ImplicitConversionSequence::Better 4360 : ImplicitConversionSequence::Worse; 4361 } 4362 } 4363 4364 // Ranking of member-pointer types. 4365 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4366 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4367 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4368 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4369 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4370 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4371 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4372 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4373 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4374 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4375 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4376 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4377 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4378 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4379 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4380 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4381 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4382 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4383 return ImplicitConversionSequence::Worse; 4384 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4385 return ImplicitConversionSequence::Better; 4386 } 4387 // conversion of B::* to C::* is better than conversion of A::* to C::* 4388 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4389 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4390 return ImplicitConversionSequence::Better; 4391 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4392 return ImplicitConversionSequence::Worse; 4393 } 4394 } 4395 4396 if (SCS1.Second == ICK_Derived_To_Base) { 4397 // -- conversion of C to B is better than conversion of C to A, 4398 // -- binding of an expression of type C to a reference of type 4399 // B& is better than binding an expression of type C to a 4400 // reference of type A&, 4401 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4402 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4403 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4404 return ImplicitConversionSequence::Better; 4405 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4406 return ImplicitConversionSequence::Worse; 4407 } 4408 4409 // -- conversion of B to A is better than conversion of C to A. 4410 // -- binding of an expression of type B to a reference of type 4411 // A& is better than binding an expression of type C to a 4412 // reference of type A&, 4413 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4414 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4415 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4416 return ImplicitConversionSequence::Better; 4417 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4418 return ImplicitConversionSequence::Worse; 4419 } 4420 } 4421 4422 return ImplicitConversionSequence::Indistinguishable; 4423 } 4424 4425 /// Determine whether the given type is valid, e.g., it is not an invalid 4426 /// C++ class. 4427 static bool isTypeValid(QualType T) { 4428 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4429 return !Record->isInvalidDecl(); 4430 4431 return true; 4432 } 4433 4434 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4435 if (!T.getQualifiers().hasUnaligned()) 4436 return T; 4437 4438 Qualifiers Q; 4439 T = Ctx.getUnqualifiedArrayType(T, Q); 4440 Q.removeUnaligned(); 4441 return Ctx.getQualifiedType(T, Q); 4442 } 4443 4444 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4445 /// determine whether they are reference-compatible, 4446 /// reference-related, or incompatible, for use in C++ initialization by 4447 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4448 /// type, and the first type (T1) is the pointee type of the reference 4449 /// type being initialized. 4450 Sema::ReferenceCompareResult 4451 Sema::CompareReferenceRelationship(SourceLocation Loc, 4452 QualType OrigT1, QualType OrigT2, 4453 ReferenceConversions *ConvOut) { 4454 assert(!OrigT1->isReferenceType() && 4455 "T1 must be the pointee type of the reference type"); 4456 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4457 4458 QualType T1 = Context.getCanonicalType(OrigT1); 4459 QualType T2 = Context.getCanonicalType(OrigT2); 4460 Qualifiers T1Quals, T2Quals; 4461 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4462 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4463 4464 ReferenceConversions ConvTmp; 4465 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4466 Conv = ReferenceConversions(); 4467 4468 // C++2a [dcl.init.ref]p4: 4469 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4470 // reference-related to "cv2 T2" if T1 is similar to T2, or 4471 // T1 is a base class of T2. 4472 // "cv1 T1" is reference-compatible with "cv2 T2" if 4473 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4474 // "pointer to cv1 T1" via a standard conversion sequence. 4475 4476 // Check for standard conversions we can apply to pointers: derived-to-base 4477 // conversions, ObjC pointer conversions, and function pointer conversions. 4478 // (Qualification conversions are checked last.) 4479 QualType ConvertedT2; 4480 if (UnqualT1 == UnqualT2) { 4481 // Nothing to do. 4482 } else if (isCompleteType(Loc, OrigT2) && 4483 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4484 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4485 Conv |= ReferenceConversions::DerivedToBase; 4486 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4487 UnqualT2->isObjCObjectOrInterfaceType() && 4488 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4489 Conv |= ReferenceConversions::ObjC; 4490 else if (UnqualT2->isFunctionType() && 4491 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4492 Conv |= ReferenceConversions::Function; 4493 // No need to check qualifiers; function types don't have them. 4494 return Ref_Compatible; 4495 } 4496 bool ConvertedReferent = Conv != 0; 4497 4498 // We can have a qualification conversion. Compute whether the types are 4499 // similar at the same time. 4500 bool PreviousToQualsIncludeConst = true; 4501 bool TopLevel = true; 4502 do { 4503 if (T1 == T2) 4504 break; 4505 4506 // We will need a qualification conversion. 4507 Conv |= ReferenceConversions::Qualification; 4508 4509 // Track whether we performed a qualification conversion anywhere other 4510 // than the top level. This matters for ranking reference bindings in 4511 // overload resolution. 4512 if (!TopLevel) 4513 Conv |= ReferenceConversions::NestedQualification; 4514 4515 // MS compiler ignores __unaligned qualifier for references; do the same. 4516 T1 = withoutUnaligned(Context, T1); 4517 T2 = withoutUnaligned(Context, T2); 4518 4519 // If we find a qualifier mismatch, the types are not reference-compatible, 4520 // but are still be reference-related if they're similar. 4521 bool ObjCLifetimeConversion = false; 4522 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4523 PreviousToQualsIncludeConst, 4524 ObjCLifetimeConversion)) 4525 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4526 ? Ref_Related 4527 : Ref_Incompatible; 4528 4529 // FIXME: Should we track this for any level other than the first? 4530 if (ObjCLifetimeConversion) 4531 Conv |= ReferenceConversions::ObjCLifetime; 4532 4533 TopLevel = false; 4534 } while (Context.UnwrapSimilarTypes(T1, T2)); 4535 4536 // At this point, if the types are reference-related, we must either have the 4537 // same inner type (ignoring qualifiers), or must have already worked out how 4538 // to convert the referent. 4539 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4540 ? Ref_Compatible 4541 : Ref_Incompatible; 4542 } 4543 4544 /// Look for a user-defined conversion to a value reference-compatible 4545 /// with DeclType. Return true if something definite is found. 4546 static bool 4547 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4548 QualType DeclType, SourceLocation DeclLoc, 4549 Expr *Init, QualType T2, bool AllowRvalues, 4550 bool AllowExplicit) { 4551 assert(T2->isRecordType() && "Can only find conversions of record types."); 4552 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4553 4554 OverloadCandidateSet CandidateSet( 4555 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4556 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4557 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4558 NamedDecl *D = *I; 4559 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4560 if (isa<UsingShadowDecl>(D)) 4561 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4562 4563 FunctionTemplateDecl *ConvTemplate 4564 = dyn_cast<FunctionTemplateDecl>(D); 4565 CXXConversionDecl *Conv; 4566 if (ConvTemplate) 4567 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4568 else 4569 Conv = cast<CXXConversionDecl>(D); 4570 4571 if (AllowRvalues) { 4572 // If we are initializing an rvalue reference, don't permit conversion 4573 // functions that return lvalues. 4574 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4575 const ReferenceType *RefType 4576 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4577 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4578 continue; 4579 } 4580 4581 if (!ConvTemplate && 4582 S.CompareReferenceRelationship( 4583 DeclLoc, 4584 Conv->getConversionType() 4585 .getNonReferenceType() 4586 .getUnqualifiedType(), 4587 DeclType.getNonReferenceType().getUnqualifiedType()) == 4588 Sema::Ref_Incompatible) 4589 continue; 4590 } else { 4591 // If the conversion function doesn't return a reference type, 4592 // it can't be considered for this conversion. An rvalue reference 4593 // is only acceptable if its referencee is a function type. 4594 4595 const ReferenceType *RefType = 4596 Conv->getConversionType()->getAs<ReferenceType>(); 4597 if (!RefType || 4598 (!RefType->isLValueReferenceType() && 4599 !RefType->getPointeeType()->isFunctionType())) 4600 continue; 4601 } 4602 4603 if (ConvTemplate) 4604 S.AddTemplateConversionCandidate( 4605 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4606 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4607 else 4608 S.AddConversionCandidate( 4609 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4610 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4611 } 4612 4613 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4614 4615 OverloadCandidateSet::iterator Best; 4616 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4617 case OR_Success: 4618 // C++ [over.ics.ref]p1: 4619 // 4620 // [...] If the parameter binds directly to the result of 4621 // applying a conversion function to the argument 4622 // expression, the implicit conversion sequence is a 4623 // user-defined conversion sequence (13.3.3.1.2), with the 4624 // second standard conversion sequence either an identity 4625 // conversion or, if the conversion function returns an 4626 // entity of a type that is a derived class of the parameter 4627 // type, a derived-to-base Conversion. 4628 if (!Best->FinalConversion.DirectBinding) 4629 return false; 4630 4631 ICS.setUserDefined(); 4632 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4633 ICS.UserDefined.After = Best->FinalConversion; 4634 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4635 ICS.UserDefined.ConversionFunction = Best->Function; 4636 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4637 ICS.UserDefined.EllipsisConversion = false; 4638 assert(ICS.UserDefined.After.ReferenceBinding && 4639 ICS.UserDefined.After.DirectBinding && 4640 "Expected a direct reference binding!"); 4641 return true; 4642 4643 case OR_Ambiguous: 4644 ICS.setAmbiguous(); 4645 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4646 Cand != CandidateSet.end(); ++Cand) 4647 if (Cand->Best) 4648 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4649 return true; 4650 4651 case OR_No_Viable_Function: 4652 case OR_Deleted: 4653 // There was no suitable conversion, or we found a deleted 4654 // conversion; continue with other checks. 4655 return false; 4656 } 4657 4658 llvm_unreachable("Invalid OverloadResult!"); 4659 } 4660 4661 /// Compute an implicit conversion sequence for reference 4662 /// initialization. 4663 static ImplicitConversionSequence 4664 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4665 SourceLocation DeclLoc, 4666 bool SuppressUserConversions, 4667 bool AllowExplicit) { 4668 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4669 4670 // Most paths end in a failed conversion. 4671 ImplicitConversionSequence ICS; 4672 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4673 4674 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4675 QualType T2 = Init->getType(); 4676 4677 // If the initializer is the address of an overloaded function, try 4678 // to resolve the overloaded function. If all goes well, T2 is the 4679 // type of the resulting function. 4680 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4681 DeclAccessPair Found; 4682 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4683 false, Found)) 4684 T2 = Fn->getType(); 4685 } 4686 4687 // Compute some basic properties of the types and the initializer. 4688 bool isRValRef = DeclType->isRValueReferenceType(); 4689 Expr::Classification InitCategory = Init->Classify(S.Context); 4690 4691 Sema::ReferenceConversions RefConv; 4692 Sema::ReferenceCompareResult RefRelationship = 4693 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4694 4695 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4696 ICS.setStandard(); 4697 ICS.Standard.First = ICK_Identity; 4698 // FIXME: A reference binding can be a function conversion too. We should 4699 // consider that when ordering reference-to-function bindings. 4700 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4701 ? ICK_Derived_To_Base 4702 : (RefConv & Sema::ReferenceConversions::ObjC) 4703 ? ICK_Compatible_Conversion 4704 : ICK_Identity; 4705 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4706 // a reference binding that performs a non-top-level qualification 4707 // conversion as a qualification conversion, not as an identity conversion. 4708 ICS.Standard.Third = (RefConv & 4709 Sema::ReferenceConversions::NestedQualification) 4710 ? ICK_Qualification 4711 : ICK_Identity; 4712 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4713 ICS.Standard.setToType(0, T2); 4714 ICS.Standard.setToType(1, T1); 4715 ICS.Standard.setToType(2, T1); 4716 ICS.Standard.ReferenceBinding = true; 4717 ICS.Standard.DirectBinding = BindsDirectly; 4718 ICS.Standard.IsLvalueReference = !isRValRef; 4719 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4720 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4721 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4722 ICS.Standard.ObjCLifetimeConversionBinding = 4723 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4724 ICS.Standard.CopyConstructor = nullptr; 4725 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4726 }; 4727 4728 // C++0x [dcl.init.ref]p5: 4729 // A reference to type "cv1 T1" is initialized by an expression 4730 // of type "cv2 T2" as follows: 4731 4732 // -- If reference is an lvalue reference and the initializer expression 4733 if (!isRValRef) { 4734 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4735 // reference-compatible with "cv2 T2," or 4736 // 4737 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4738 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4739 // C++ [over.ics.ref]p1: 4740 // When a parameter of reference type binds directly (8.5.3) 4741 // to an argument expression, the implicit conversion sequence 4742 // is the identity conversion, unless the argument expression 4743 // has a type that is a derived class of the parameter type, 4744 // in which case the implicit conversion sequence is a 4745 // derived-to-base Conversion (13.3.3.1). 4746 SetAsReferenceBinding(/*BindsDirectly=*/true); 4747 4748 // Nothing more to do: the inaccessibility/ambiguity check for 4749 // derived-to-base conversions is suppressed when we're 4750 // computing the implicit conversion sequence (C++ 4751 // [over.best.ics]p2). 4752 return ICS; 4753 } 4754 4755 // -- has a class type (i.e., T2 is a class type), where T1 is 4756 // not reference-related to T2, and can be implicitly 4757 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4758 // is reference-compatible with "cv3 T3" 92) (this 4759 // conversion is selected by enumerating the applicable 4760 // conversion functions (13.3.1.6) and choosing the best 4761 // one through overload resolution (13.3)), 4762 if (!SuppressUserConversions && T2->isRecordType() && 4763 S.isCompleteType(DeclLoc, T2) && 4764 RefRelationship == Sema::Ref_Incompatible) { 4765 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4766 Init, T2, /*AllowRvalues=*/false, 4767 AllowExplicit)) 4768 return ICS; 4769 } 4770 } 4771 4772 // -- Otherwise, the reference shall be an lvalue reference to a 4773 // non-volatile const type (i.e., cv1 shall be const), or the reference 4774 // shall be an rvalue reference. 4775 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4776 return ICS; 4777 4778 // -- If the initializer expression 4779 // 4780 // -- is an xvalue, class prvalue, array prvalue or function 4781 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4782 if (RefRelationship == Sema::Ref_Compatible && 4783 (InitCategory.isXValue() || 4784 (InitCategory.isPRValue() && 4785 (T2->isRecordType() || T2->isArrayType())) || 4786 (InitCategory.isLValue() && T2->isFunctionType()))) { 4787 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4788 // binding unless we're binding to a class prvalue. 4789 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4790 // allow the use of rvalue references in C++98/03 for the benefit of 4791 // standard library implementors; therefore, we need the xvalue check here. 4792 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4793 !(InitCategory.isPRValue() || T2->isRecordType())); 4794 return ICS; 4795 } 4796 4797 // -- has a class type (i.e., T2 is a class type), where T1 is not 4798 // reference-related to T2, and can be implicitly converted to 4799 // an xvalue, class prvalue, or function lvalue of type 4800 // "cv3 T3", where "cv1 T1" is reference-compatible with 4801 // "cv3 T3", 4802 // 4803 // then the reference is bound to the value of the initializer 4804 // expression in the first case and to the result of the conversion 4805 // in the second case (or, in either case, to an appropriate base 4806 // class subobject). 4807 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4808 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4809 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4810 Init, T2, /*AllowRvalues=*/true, 4811 AllowExplicit)) { 4812 // In the second case, if the reference is an rvalue reference 4813 // and the second standard conversion sequence of the 4814 // user-defined conversion sequence includes an lvalue-to-rvalue 4815 // conversion, the program is ill-formed. 4816 if (ICS.isUserDefined() && isRValRef && 4817 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4818 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4819 4820 return ICS; 4821 } 4822 4823 // A temporary of function type cannot be created; don't even try. 4824 if (T1->isFunctionType()) 4825 return ICS; 4826 4827 // -- Otherwise, a temporary of type "cv1 T1" is created and 4828 // initialized from the initializer expression using the 4829 // rules for a non-reference copy initialization (8.5). The 4830 // reference is then bound to the temporary. If T1 is 4831 // reference-related to T2, cv1 must be the same 4832 // cv-qualification as, or greater cv-qualification than, 4833 // cv2; otherwise, the program is ill-formed. 4834 if (RefRelationship == Sema::Ref_Related) { 4835 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4836 // we would be reference-compatible or reference-compatible with 4837 // added qualification. But that wasn't the case, so the reference 4838 // initialization fails. 4839 // 4840 // Note that we only want to check address spaces and cvr-qualifiers here. 4841 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4842 Qualifiers T1Quals = T1.getQualifiers(); 4843 Qualifiers T2Quals = T2.getQualifiers(); 4844 T1Quals.removeObjCGCAttr(); 4845 T1Quals.removeObjCLifetime(); 4846 T2Quals.removeObjCGCAttr(); 4847 T2Quals.removeObjCLifetime(); 4848 // MS compiler ignores __unaligned qualifier for references; do the same. 4849 T1Quals.removeUnaligned(); 4850 T2Quals.removeUnaligned(); 4851 if (!T1Quals.compatiblyIncludes(T2Quals)) 4852 return ICS; 4853 } 4854 4855 // If at least one of the types is a class type, the types are not 4856 // related, and we aren't allowed any user conversions, the 4857 // reference binding fails. This case is important for breaking 4858 // recursion, since TryImplicitConversion below will attempt to 4859 // create a temporary through the use of a copy constructor. 4860 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4861 (T1->isRecordType() || T2->isRecordType())) 4862 return ICS; 4863 4864 // If T1 is reference-related to T2 and the reference is an rvalue 4865 // reference, the initializer expression shall not be an lvalue. 4866 if (RefRelationship >= Sema::Ref_Related && 4867 isRValRef && Init->Classify(S.Context).isLValue()) 4868 return ICS; 4869 4870 // C++ [over.ics.ref]p2: 4871 // When a parameter of reference type is not bound directly to 4872 // an argument expression, the conversion sequence is the one 4873 // required to convert the argument expression to the 4874 // underlying type of the reference according to 4875 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4876 // to copy-initializing a temporary of the underlying type with 4877 // the argument expression. Any difference in top-level 4878 // cv-qualification is subsumed by the initialization itself 4879 // and does not constitute a conversion. 4880 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4881 AllowedExplicit::None, 4882 /*InOverloadResolution=*/false, 4883 /*CStyle=*/false, 4884 /*AllowObjCWritebackConversion=*/false, 4885 /*AllowObjCConversionOnExplicit=*/false); 4886 4887 // Of course, that's still a reference binding. 4888 if (ICS.isStandard()) { 4889 ICS.Standard.ReferenceBinding = true; 4890 ICS.Standard.IsLvalueReference = !isRValRef; 4891 ICS.Standard.BindsToFunctionLvalue = false; 4892 ICS.Standard.BindsToRvalue = true; 4893 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4894 ICS.Standard.ObjCLifetimeConversionBinding = false; 4895 } else if (ICS.isUserDefined()) { 4896 const ReferenceType *LValRefType = 4897 ICS.UserDefined.ConversionFunction->getReturnType() 4898 ->getAs<LValueReferenceType>(); 4899 4900 // C++ [over.ics.ref]p3: 4901 // Except for an implicit object parameter, for which see 13.3.1, a 4902 // standard conversion sequence cannot be formed if it requires [...] 4903 // binding an rvalue reference to an lvalue other than a function 4904 // lvalue. 4905 // Note that the function case is not possible here. 4906 if (DeclType->isRValueReferenceType() && LValRefType) { 4907 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4908 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4909 // reference to an rvalue! 4910 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4911 return ICS; 4912 } 4913 4914 ICS.UserDefined.After.ReferenceBinding = true; 4915 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4916 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4917 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4918 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4919 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4920 } 4921 4922 return ICS; 4923 } 4924 4925 static ImplicitConversionSequence 4926 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4927 bool SuppressUserConversions, 4928 bool InOverloadResolution, 4929 bool AllowObjCWritebackConversion, 4930 bool AllowExplicit = false); 4931 4932 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4933 /// initializer list From. 4934 static ImplicitConversionSequence 4935 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4936 bool SuppressUserConversions, 4937 bool InOverloadResolution, 4938 bool AllowObjCWritebackConversion) { 4939 // C++11 [over.ics.list]p1: 4940 // When an argument is an initializer list, it is not an expression and 4941 // special rules apply for converting it to a parameter type. 4942 4943 ImplicitConversionSequence Result; 4944 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4945 4946 // We need a complete type for what follows. Incomplete types can never be 4947 // initialized from init lists. 4948 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4949 return Result; 4950 4951 // Per DR1467: 4952 // If the parameter type is a class X and the initializer list has a single 4953 // element of type cv U, where U is X or a class derived from X, the 4954 // implicit conversion sequence is the one required to convert the element 4955 // to the parameter type. 4956 // 4957 // Otherwise, if the parameter type is a character array [... ] 4958 // and the initializer list has a single element that is an 4959 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4960 // implicit conversion sequence is the identity conversion. 4961 if (From->getNumInits() == 1) { 4962 if (ToType->isRecordType()) { 4963 QualType InitType = From->getInit(0)->getType(); 4964 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4965 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4966 return TryCopyInitialization(S, From->getInit(0), ToType, 4967 SuppressUserConversions, 4968 InOverloadResolution, 4969 AllowObjCWritebackConversion); 4970 } 4971 // FIXME: Check the other conditions here: array of character type, 4972 // initializer is a string literal. 4973 if (ToType->isArrayType()) { 4974 InitializedEntity Entity = 4975 InitializedEntity::InitializeParameter(S.Context, ToType, 4976 /*Consumed=*/false); 4977 if (S.CanPerformCopyInitialization(Entity, From)) { 4978 Result.setStandard(); 4979 Result.Standard.setAsIdentityConversion(); 4980 Result.Standard.setFromType(ToType); 4981 Result.Standard.setAllToTypes(ToType); 4982 return Result; 4983 } 4984 } 4985 } 4986 4987 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4988 // C++11 [over.ics.list]p2: 4989 // If the parameter type is std::initializer_list<X> or "array of X" and 4990 // all the elements can be implicitly converted to X, the implicit 4991 // conversion sequence is the worst conversion necessary to convert an 4992 // element of the list to X. 4993 // 4994 // C++14 [over.ics.list]p3: 4995 // Otherwise, if the parameter type is "array of N X", if the initializer 4996 // list has exactly N elements or if it has fewer than N elements and X is 4997 // default-constructible, and if all the elements of the initializer list 4998 // can be implicitly converted to X, the implicit conversion sequence is 4999 // the worst conversion necessary to convert an element of the list to X. 5000 // 5001 // FIXME: We're missing a lot of these checks. 5002 bool toStdInitializerList = false; 5003 QualType X; 5004 if (ToType->isArrayType()) 5005 X = S.Context.getAsArrayType(ToType)->getElementType(); 5006 else 5007 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5008 if (!X.isNull()) { 5009 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5010 Expr *Init = From->getInit(i); 5011 ImplicitConversionSequence ICS = 5012 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5013 InOverloadResolution, 5014 AllowObjCWritebackConversion); 5015 // If a single element isn't convertible, fail. 5016 if (ICS.isBad()) { 5017 Result = ICS; 5018 break; 5019 } 5020 // Otherwise, look for the worst conversion. 5021 if (Result.isBad() || CompareImplicitConversionSequences( 5022 S, From->getBeginLoc(), ICS, Result) == 5023 ImplicitConversionSequence::Worse) 5024 Result = ICS; 5025 } 5026 5027 // For an empty list, we won't have computed any conversion sequence. 5028 // Introduce the identity conversion sequence. 5029 if (From->getNumInits() == 0) { 5030 Result.setStandard(); 5031 Result.Standard.setAsIdentityConversion(); 5032 Result.Standard.setFromType(ToType); 5033 Result.Standard.setAllToTypes(ToType); 5034 } 5035 5036 Result.setStdInitializerListElement(toStdInitializerList); 5037 return Result; 5038 } 5039 5040 // C++14 [over.ics.list]p4: 5041 // C++11 [over.ics.list]p3: 5042 // Otherwise, if the parameter is a non-aggregate class X and overload 5043 // resolution chooses a single best constructor [...] the implicit 5044 // conversion sequence is a user-defined conversion sequence. If multiple 5045 // constructors are viable but none is better than the others, the 5046 // implicit conversion sequence is a user-defined conversion sequence. 5047 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5048 // This function can deal with initializer lists. 5049 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5050 AllowedExplicit::None, 5051 InOverloadResolution, /*CStyle=*/false, 5052 AllowObjCWritebackConversion, 5053 /*AllowObjCConversionOnExplicit=*/false); 5054 } 5055 5056 // C++14 [over.ics.list]p5: 5057 // C++11 [over.ics.list]p4: 5058 // Otherwise, if the parameter has an aggregate type which can be 5059 // initialized from the initializer list [...] the implicit conversion 5060 // sequence is a user-defined conversion sequence. 5061 if (ToType->isAggregateType()) { 5062 // Type is an aggregate, argument is an init list. At this point it comes 5063 // down to checking whether the initialization works. 5064 // FIXME: Find out whether this parameter is consumed or not. 5065 InitializedEntity Entity = 5066 InitializedEntity::InitializeParameter(S.Context, ToType, 5067 /*Consumed=*/false); 5068 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5069 From)) { 5070 Result.setUserDefined(); 5071 Result.UserDefined.Before.setAsIdentityConversion(); 5072 // Initializer lists don't have a type. 5073 Result.UserDefined.Before.setFromType(QualType()); 5074 Result.UserDefined.Before.setAllToTypes(QualType()); 5075 5076 Result.UserDefined.After.setAsIdentityConversion(); 5077 Result.UserDefined.After.setFromType(ToType); 5078 Result.UserDefined.After.setAllToTypes(ToType); 5079 Result.UserDefined.ConversionFunction = nullptr; 5080 } 5081 return Result; 5082 } 5083 5084 // C++14 [over.ics.list]p6: 5085 // C++11 [over.ics.list]p5: 5086 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5087 if (ToType->isReferenceType()) { 5088 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5089 // mention initializer lists in any way. So we go by what list- 5090 // initialization would do and try to extrapolate from that. 5091 5092 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5093 5094 // If the initializer list has a single element that is reference-related 5095 // to the parameter type, we initialize the reference from that. 5096 if (From->getNumInits() == 1) { 5097 Expr *Init = From->getInit(0); 5098 5099 QualType T2 = Init->getType(); 5100 5101 // If the initializer is the address of an overloaded function, try 5102 // to resolve the overloaded function. If all goes well, T2 is the 5103 // type of the resulting function. 5104 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5105 DeclAccessPair Found; 5106 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5107 Init, ToType, false, Found)) 5108 T2 = Fn->getType(); 5109 } 5110 5111 // Compute some basic properties of the types and the initializer. 5112 Sema::ReferenceCompareResult RefRelationship = 5113 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5114 5115 if (RefRelationship >= Sema::Ref_Related) { 5116 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5117 SuppressUserConversions, 5118 /*AllowExplicit=*/false); 5119 } 5120 } 5121 5122 // Otherwise, we bind the reference to a temporary created from the 5123 // initializer list. 5124 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5125 InOverloadResolution, 5126 AllowObjCWritebackConversion); 5127 if (Result.isFailure()) 5128 return Result; 5129 assert(!Result.isEllipsis() && 5130 "Sub-initialization cannot result in ellipsis conversion."); 5131 5132 // Can we even bind to a temporary? 5133 if (ToType->isRValueReferenceType() || 5134 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5135 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5136 Result.UserDefined.After; 5137 SCS.ReferenceBinding = true; 5138 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5139 SCS.BindsToRvalue = true; 5140 SCS.BindsToFunctionLvalue = false; 5141 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5142 SCS.ObjCLifetimeConversionBinding = false; 5143 } else 5144 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5145 From, ToType); 5146 return Result; 5147 } 5148 5149 // C++14 [over.ics.list]p7: 5150 // C++11 [over.ics.list]p6: 5151 // Otherwise, if the parameter type is not a class: 5152 if (!ToType->isRecordType()) { 5153 // - if the initializer list has one element that is not itself an 5154 // initializer list, the implicit conversion sequence is the one 5155 // required to convert the element to the parameter type. 5156 unsigned NumInits = From->getNumInits(); 5157 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5158 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5159 SuppressUserConversions, 5160 InOverloadResolution, 5161 AllowObjCWritebackConversion); 5162 // - if the initializer list has no elements, the implicit conversion 5163 // sequence is the identity conversion. 5164 else if (NumInits == 0) { 5165 Result.setStandard(); 5166 Result.Standard.setAsIdentityConversion(); 5167 Result.Standard.setFromType(ToType); 5168 Result.Standard.setAllToTypes(ToType); 5169 } 5170 return Result; 5171 } 5172 5173 // C++14 [over.ics.list]p8: 5174 // C++11 [over.ics.list]p7: 5175 // In all cases other than those enumerated above, no conversion is possible 5176 return Result; 5177 } 5178 5179 /// TryCopyInitialization - Try to copy-initialize a value of type 5180 /// ToType from the expression From. Return the implicit conversion 5181 /// sequence required to pass this argument, which may be a bad 5182 /// conversion sequence (meaning that the argument cannot be passed to 5183 /// a parameter of this type). If @p SuppressUserConversions, then we 5184 /// do not permit any user-defined conversion sequences. 5185 static ImplicitConversionSequence 5186 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5187 bool SuppressUserConversions, 5188 bool InOverloadResolution, 5189 bool AllowObjCWritebackConversion, 5190 bool AllowExplicit) { 5191 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5192 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5193 InOverloadResolution,AllowObjCWritebackConversion); 5194 5195 if (ToType->isReferenceType()) 5196 return TryReferenceInit(S, From, ToType, 5197 /*FIXME:*/ From->getBeginLoc(), 5198 SuppressUserConversions, AllowExplicit); 5199 5200 return TryImplicitConversion(S, From, ToType, 5201 SuppressUserConversions, 5202 AllowedExplicit::None, 5203 InOverloadResolution, 5204 /*CStyle=*/false, 5205 AllowObjCWritebackConversion, 5206 /*AllowObjCConversionOnExplicit=*/false); 5207 } 5208 5209 static bool TryCopyInitialization(const CanQualType FromQTy, 5210 const CanQualType ToQTy, 5211 Sema &S, 5212 SourceLocation Loc, 5213 ExprValueKind FromVK) { 5214 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5215 ImplicitConversionSequence ICS = 5216 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5217 5218 return !ICS.isBad(); 5219 } 5220 5221 /// TryObjectArgumentInitialization - Try to initialize the object 5222 /// parameter of the given member function (@c Method) from the 5223 /// expression @p From. 5224 static ImplicitConversionSequence 5225 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5226 Expr::Classification FromClassification, 5227 CXXMethodDecl *Method, 5228 CXXRecordDecl *ActingContext) { 5229 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5230 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5231 // const volatile object. 5232 Qualifiers Quals = Method->getMethodQualifiers(); 5233 if (isa<CXXDestructorDecl>(Method)) { 5234 Quals.addConst(); 5235 Quals.addVolatile(); 5236 } 5237 5238 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5239 5240 // Set up the conversion sequence as a "bad" conversion, to allow us 5241 // to exit early. 5242 ImplicitConversionSequence ICS; 5243 5244 // We need to have an object of class type. 5245 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5246 FromType = PT->getPointeeType(); 5247 5248 // When we had a pointer, it's implicitly dereferenced, so we 5249 // better have an lvalue. 5250 assert(FromClassification.isLValue()); 5251 } 5252 5253 assert(FromType->isRecordType()); 5254 5255 // C++0x [over.match.funcs]p4: 5256 // For non-static member functions, the type of the implicit object 5257 // parameter is 5258 // 5259 // - "lvalue reference to cv X" for functions declared without a 5260 // ref-qualifier or with the & ref-qualifier 5261 // - "rvalue reference to cv X" for functions declared with the && 5262 // ref-qualifier 5263 // 5264 // where X is the class of which the function is a member and cv is the 5265 // cv-qualification on the member function declaration. 5266 // 5267 // However, when finding an implicit conversion sequence for the argument, we 5268 // are not allowed to perform user-defined conversions 5269 // (C++ [over.match.funcs]p5). We perform a simplified version of 5270 // reference binding here, that allows class rvalues to bind to 5271 // non-constant references. 5272 5273 // First check the qualifiers. 5274 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5275 if (ImplicitParamType.getCVRQualifiers() 5276 != FromTypeCanon.getLocalCVRQualifiers() && 5277 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5278 ICS.setBad(BadConversionSequence::bad_qualifiers, 5279 FromType, ImplicitParamType); 5280 return ICS; 5281 } 5282 5283 if (FromTypeCanon.hasAddressSpace()) { 5284 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5285 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5286 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5287 ICS.setBad(BadConversionSequence::bad_qualifiers, 5288 FromType, ImplicitParamType); 5289 return ICS; 5290 } 5291 } 5292 5293 // Check that we have either the same type or a derived type. It 5294 // affects the conversion rank. 5295 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5296 ImplicitConversionKind SecondKind; 5297 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5298 SecondKind = ICK_Identity; 5299 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5300 SecondKind = ICK_Derived_To_Base; 5301 else { 5302 ICS.setBad(BadConversionSequence::unrelated_class, 5303 FromType, ImplicitParamType); 5304 return ICS; 5305 } 5306 5307 // Check the ref-qualifier. 5308 switch (Method->getRefQualifier()) { 5309 case RQ_None: 5310 // Do nothing; we don't care about lvalueness or rvalueness. 5311 break; 5312 5313 case RQ_LValue: 5314 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5315 // non-const lvalue reference cannot bind to an rvalue 5316 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5317 ImplicitParamType); 5318 return ICS; 5319 } 5320 break; 5321 5322 case RQ_RValue: 5323 if (!FromClassification.isRValue()) { 5324 // rvalue reference cannot bind to an lvalue 5325 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5326 ImplicitParamType); 5327 return ICS; 5328 } 5329 break; 5330 } 5331 5332 // Success. Mark this as a reference binding. 5333 ICS.setStandard(); 5334 ICS.Standard.setAsIdentityConversion(); 5335 ICS.Standard.Second = SecondKind; 5336 ICS.Standard.setFromType(FromType); 5337 ICS.Standard.setAllToTypes(ImplicitParamType); 5338 ICS.Standard.ReferenceBinding = true; 5339 ICS.Standard.DirectBinding = true; 5340 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5341 ICS.Standard.BindsToFunctionLvalue = false; 5342 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5343 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5344 = (Method->getRefQualifier() == RQ_None); 5345 return ICS; 5346 } 5347 5348 /// PerformObjectArgumentInitialization - Perform initialization of 5349 /// the implicit object parameter for the given Method with the given 5350 /// expression. 5351 ExprResult 5352 Sema::PerformObjectArgumentInitialization(Expr *From, 5353 NestedNameSpecifier *Qualifier, 5354 NamedDecl *FoundDecl, 5355 CXXMethodDecl *Method) { 5356 QualType FromRecordType, DestType; 5357 QualType ImplicitParamRecordType = 5358 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5359 5360 Expr::Classification FromClassification; 5361 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5362 FromRecordType = PT->getPointeeType(); 5363 DestType = Method->getThisType(); 5364 FromClassification = Expr::Classification::makeSimpleLValue(); 5365 } else { 5366 FromRecordType = From->getType(); 5367 DestType = ImplicitParamRecordType; 5368 FromClassification = From->Classify(Context); 5369 5370 // When performing member access on an rvalue, materialize a temporary. 5371 if (From->isRValue()) { 5372 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5373 Method->getRefQualifier() != 5374 RefQualifierKind::RQ_RValue); 5375 } 5376 } 5377 5378 // Note that we always use the true parent context when performing 5379 // the actual argument initialization. 5380 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5381 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5382 Method->getParent()); 5383 if (ICS.isBad()) { 5384 switch (ICS.Bad.Kind) { 5385 case BadConversionSequence::bad_qualifiers: { 5386 Qualifiers FromQs = FromRecordType.getQualifiers(); 5387 Qualifiers ToQs = DestType.getQualifiers(); 5388 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5389 if (CVR) { 5390 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5391 << Method->getDeclName() << FromRecordType << (CVR - 1) 5392 << From->getSourceRange(); 5393 Diag(Method->getLocation(), diag::note_previous_decl) 5394 << Method->getDeclName(); 5395 return ExprError(); 5396 } 5397 break; 5398 } 5399 5400 case BadConversionSequence::lvalue_ref_to_rvalue: 5401 case BadConversionSequence::rvalue_ref_to_lvalue: { 5402 bool IsRValueQualified = 5403 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5404 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5405 << Method->getDeclName() << FromClassification.isRValue() 5406 << IsRValueQualified; 5407 Diag(Method->getLocation(), diag::note_previous_decl) 5408 << Method->getDeclName(); 5409 return ExprError(); 5410 } 5411 5412 case BadConversionSequence::no_conversion: 5413 case BadConversionSequence::unrelated_class: 5414 break; 5415 } 5416 5417 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5418 << ImplicitParamRecordType << FromRecordType 5419 << From->getSourceRange(); 5420 } 5421 5422 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5423 ExprResult FromRes = 5424 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5425 if (FromRes.isInvalid()) 5426 return ExprError(); 5427 From = FromRes.get(); 5428 } 5429 5430 if (!Context.hasSameType(From->getType(), DestType)) { 5431 CastKind CK; 5432 QualType PteeTy = DestType->getPointeeType(); 5433 LangAS DestAS = 5434 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5435 if (FromRecordType.getAddressSpace() != DestAS) 5436 CK = CK_AddressSpaceConversion; 5437 else 5438 CK = CK_NoOp; 5439 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5440 } 5441 return From; 5442 } 5443 5444 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5445 /// expression From to bool (C++0x [conv]p3). 5446 static ImplicitConversionSequence 5447 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5448 // C++ [dcl.init]/17.8: 5449 // - Otherwise, if the initialization is direct-initialization, the source 5450 // type is std::nullptr_t, and the destination type is bool, the initial 5451 // value of the object being initialized is false. 5452 if (From->getType()->isNullPtrType()) 5453 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5454 S.Context.BoolTy, 5455 From->isGLValue()); 5456 5457 // All other direct-initialization of bool is equivalent to an implicit 5458 // conversion to bool in which explicit conversions are permitted. 5459 return TryImplicitConversion(S, From, S.Context.BoolTy, 5460 /*SuppressUserConversions=*/false, 5461 AllowedExplicit::Conversions, 5462 /*InOverloadResolution=*/false, 5463 /*CStyle=*/false, 5464 /*AllowObjCWritebackConversion=*/false, 5465 /*AllowObjCConversionOnExplicit=*/false); 5466 } 5467 5468 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5469 /// of the expression From to bool (C++0x [conv]p3). 5470 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5471 if (checkPlaceholderForOverload(*this, From)) 5472 return ExprError(); 5473 5474 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5475 if (!ICS.isBad()) 5476 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5477 5478 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5479 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5480 << From->getType() << From->getSourceRange(); 5481 return ExprError(); 5482 } 5483 5484 /// Check that the specified conversion is permitted in a converted constant 5485 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5486 /// is acceptable. 5487 static bool CheckConvertedConstantConversions(Sema &S, 5488 StandardConversionSequence &SCS) { 5489 // Since we know that the target type is an integral or unscoped enumeration 5490 // type, most conversion kinds are impossible. All possible First and Third 5491 // conversions are fine. 5492 switch (SCS.Second) { 5493 case ICK_Identity: 5494 case ICK_Function_Conversion: 5495 case ICK_Integral_Promotion: 5496 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5497 case ICK_Zero_Queue_Conversion: 5498 return true; 5499 5500 case ICK_Boolean_Conversion: 5501 // Conversion from an integral or unscoped enumeration type to bool is 5502 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5503 // conversion, so we allow it in a converted constant expression. 5504 // 5505 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5506 // a lot of popular code. We should at least add a warning for this 5507 // (non-conforming) extension. 5508 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5509 SCS.getToType(2)->isBooleanType(); 5510 5511 case ICK_Pointer_Conversion: 5512 case ICK_Pointer_Member: 5513 // C++1z: null pointer conversions and null member pointer conversions are 5514 // only permitted if the source type is std::nullptr_t. 5515 return SCS.getFromType()->isNullPtrType(); 5516 5517 case ICK_Floating_Promotion: 5518 case ICK_Complex_Promotion: 5519 case ICK_Floating_Conversion: 5520 case ICK_Complex_Conversion: 5521 case ICK_Floating_Integral: 5522 case ICK_Compatible_Conversion: 5523 case ICK_Derived_To_Base: 5524 case ICK_Vector_Conversion: 5525 case ICK_Vector_Splat: 5526 case ICK_Complex_Real: 5527 case ICK_Block_Pointer_Conversion: 5528 case ICK_TransparentUnionConversion: 5529 case ICK_Writeback_Conversion: 5530 case ICK_Zero_Event_Conversion: 5531 case ICK_C_Only_Conversion: 5532 case ICK_Incompatible_Pointer_Conversion: 5533 return false; 5534 5535 case ICK_Lvalue_To_Rvalue: 5536 case ICK_Array_To_Pointer: 5537 case ICK_Function_To_Pointer: 5538 llvm_unreachable("found a first conversion kind in Second"); 5539 5540 case ICK_Qualification: 5541 llvm_unreachable("found a third conversion kind in Second"); 5542 5543 case ICK_Num_Conversion_Kinds: 5544 break; 5545 } 5546 5547 llvm_unreachable("unknown conversion kind"); 5548 } 5549 5550 /// CheckConvertedConstantExpression - Check that the expression From is a 5551 /// converted constant expression of type T, perform the conversion and produce 5552 /// the converted expression, per C++11 [expr.const]p3. 5553 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5554 QualType T, APValue &Value, 5555 Sema::CCEKind CCE, 5556 bool RequireInt) { 5557 assert(S.getLangOpts().CPlusPlus11 && 5558 "converted constant expression outside C++11"); 5559 5560 if (checkPlaceholderForOverload(S, From)) 5561 return ExprError(); 5562 5563 // C++1z [expr.const]p3: 5564 // A converted constant expression of type T is an expression, 5565 // implicitly converted to type T, where the converted 5566 // expression is a constant expression and the implicit conversion 5567 // sequence contains only [... list of conversions ...]. 5568 // C++1z [stmt.if]p2: 5569 // If the if statement is of the form if constexpr, the value of the 5570 // condition shall be a contextually converted constant expression of type 5571 // bool. 5572 ImplicitConversionSequence ICS = 5573 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5574 ? TryContextuallyConvertToBool(S, From) 5575 : TryCopyInitialization(S, From, T, 5576 /*SuppressUserConversions=*/false, 5577 /*InOverloadResolution=*/false, 5578 /*AllowObjCWritebackConversion=*/false, 5579 /*AllowExplicit=*/false); 5580 StandardConversionSequence *SCS = nullptr; 5581 switch (ICS.getKind()) { 5582 case ImplicitConversionSequence::StandardConversion: 5583 SCS = &ICS.Standard; 5584 break; 5585 case ImplicitConversionSequence::UserDefinedConversion: 5586 // We are converting to a non-class type, so the Before sequence 5587 // must be trivial. 5588 SCS = &ICS.UserDefined.After; 5589 break; 5590 case ImplicitConversionSequence::AmbiguousConversion: 5591 case ImplicitConversionSequence::BadConversion: 5592 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5593 return S.Diag(From->getBeginLoc(), 5594 diag::err_typecheck_converted_constant_expression) 5595 << From->getType() << From->getSourceRange() << T; 5596 return ExprError(); 5597 5598 case ImplicitConversionSequence::EllipsisConversion: 5599 llvm_unreachable("ellipsis conversion in converted constant expression"); 5600 } 5601 5602 // Check that we would only use permitted conversions. 5603 if (!CheckConvertedConstantConversions(S, *SCS)) { 5604 return S.Diag(From->getBeginLoc(), 5605 diag::err_typecheck_converted_constant_expression_disallowed) 5606 << From->getType() << From->getSourceRange() << T; 5607 } 5608 // [...] and where the reference binding (if any) binds directly. 5609 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5610 return S.Diag(From->getBeginLoc(), 5611 diag::err_typecheck_converted_constant_expression_indirect) 5612 << From->getType() << From->getSourceRange() << T; 5613 } 5614 5615 ExprResult Result = 5616 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5617 if (Result.isInvalid()) 5618 return Result; 5619 5620 // C++2a [intro.execution]p5: 5621 // A full-expression is [...] a constant-expression [...] 5622 Result = 5623 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5624 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5625 if (Result.isInvalid()) 5626 return Result; 5627 5628 // Check for a narrowing implicit conversion. 5629 APValue PreNarrowingValue; 5630 QualType PreNarrowingType; 5631 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5632 PreNarrowingType)) { 5633 case NK_Dependent_Narrowing: 5634 // Implicit conversion to a narrower type, but the expression is 5635 // value-dependent so we can't tell whether it's actually narrowing. 5636 case NK_Variable_Narrowing: 5637 // Implicit conversion to a narrower type, and the value is not a constant 5638 // expression. We'll diagnose this in a moment. 5639 case NK_Not_Narrowing: 5640 break; 5641 5642 case NK_Constant_Narrowing: 5643 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5644 << CCE << /*Constant*/ 1 5645 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5646 break; 5647 5648 case NK_Type_Narrowing: 5649 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5650 << CCE << /*Constant*/ 0 << From->getType() << T; 5651 break; 5652 } 5653 5654 if (Result.get()->isValueDependent()) { 5655 Value = APValue(); 5656 return Result; 5657 } 5658 5659 // Check the expression is a constant expression. 5660 SmallVector<PartialDiagnosticAt, 8> Notes; 5661 Expr::EvalResult Eval; 5662 Eval.Diag = &Notes; 5663 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5664 ? Expr::EvaluateForMangling 5665 : Expr::EvaluateForCodeGen; 5666 5667 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5668 (RequireInt && !Eval.Val.isInt())) { 5669 // The expression can't be folded, so we can't keep it at this position in 5670 // the AST. 5671 Result = ExprError(); 5672 } else { 5673 Value = Eval.Val; 5674 5675 if (Notes.empty()) { 5676 // It's a constant expression. 5677 return ConstantExpr::Create(S.Context, Result.get(), Value); 5678 } 5679 } 5680 5681 // It's not a constant expression. Produce an appropriate diagnostic. 5682 if (Notes.size() == 1 && 5683 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5684 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5685 else { 5686 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5687 << CCE << From->getSourceRange(); 5688 for (unsigned I = 0; I < Notes.size(); ++I) 5689 S.Diag(Notes[I].first, Notes[I].second); 5690 } 5691 return ExprError(); 5692 } 5693 5694 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5695 APValue &Value, CCEKind CCE) { 5696 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5697 } 5698 5699 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5700 llvm::APSInt &Value, 5701 CCEKind CCE) { 5702 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5703 5704 APValue V; 5705 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5706 if (!R.isInvalid() && !R.get()->isValueDependent()) 5707 Value = V.getInt(); 5708 return R; 5709 } 5710 5711 5712 /// dropPointerConversions - If the given standard conversion sequence 5713 /// involves any pointer conversions, remove them. This may change 5714 /// the result type of the conversion sequence. 5715 static void dropPointerConversion(StandardConversionSequence &SCS) { 5716 if (SCS.Second == ICK_Pointer_Conversion) { 5717 SCS.Second = ICK_Identity; 5718 SCS.Third = ICK_Identity; 5719 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5720 } 5721 } 5722 5723 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5724 /// convert the expression From to an Objective-C pointer type. 5725 static ImplicitConversionSequence 5726 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5727 // Do an implicit conversion to 'id'. 5728 QualType Ty = S.Context.getObjCIdType(); 5729 ImplicitConversionSequence ICS 5730 = TryImplicitConversion(S, From, Ty, 5731 // FIXME: Are these flags correct? 5732 /*SuppressUserConversions=*/false, 5733 AllowedExplicit::Conversions, 5734 /*InOverloadResolution=*/false, 5735 /*CStyle=*/false, 5736 /*AllowObjCWritebackConversion=*/false, 5737 /*AllowObjCConversionOnExplicit=*/true); 5738 5739 // Strip off any final conversions to 'id'. 5740 switch (ICS.getKind()) { 5741 case ImplicitConversionSequence::BadConversion: 5742 case ImplicitConversionSequence::AmbiguousConversion: 5743 case ImplicitConversionSequence::EllipsisConversion: 5744 break; 5745 5746 case ImplicitConversionSequence::UserDefinedConversion: 5747 dropPointerConversion(ICS.UserDefined.After); 5748 break; 5749 5750 case ImplicitConversionSequence::StandardConversion: 5751 dropPointerConversion(ICS.Standard); 5752 break; 5753 } 5754 5755 return ICS; 5756 } 5757 5758 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5759 /// conversion of the expression From to an Objective-C pointer type. 5760 /// Returns a valid but null ExprResult if no conversion sequence exists. 5761 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5762 if (checkPlaceholderForOverload(*this, From)) 5763 return ExprError(); 5764 5765 QualType Ty = Context.getObjCIdType(); 5766 ImplicitConversionSequence ICS = 5767 TryContextuallyConvertToObjCPointer(*this, From); 5768 if (!ICS.isBad()) 5769 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5770 return ExprResult(); 5771 } 5772 5773 /// Determine whether the provided type is an integral type, or an enumeration 5774 /// type of a permitted flavor. 5775 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5776 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5777 : T->isIntegralOrUnscopedEnumerationType(); 5778 } 5779 5780 static ExprResult 5781 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5782 Sema::ContextualImplicitConverter &Converter, 5783 QualType T, UnresolvedSetImpl &ViableConversions) { 5784 5785 if (Converter.Suppress) 5786 return ExprError(); 5787 5788 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5789 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5790 CXXConversionDecl *Conv = 5791 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5792 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5793 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5794 } 5795 return From; 5796 } 5797 5798 static bool 5799 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5800 Sema::ContextualImplicitConverter &Converter, 5801 QualType T, bool HadMultipleCandidates, 5802 UnresolvedSetImpl &ExplicitConversions) { 5803 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5804 DeclAccessPair Found = ExplicitConversions[0]; 5805 CXXConversionDecl *Conversion = 5806 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5807 5808 // The user probably meant to invoke the given explicit 5809 // conversion; use it. 5810 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5811 std::string TypeStr; 5812 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5813 5814 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5815 << FixItHint::CreateInsertion(From->getBeginLoc(), 5816 "static_cast<" + TypeStr + ">(") 5817 << FixItHint::CreateInsertion( 5818 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5819 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5820 5821 // If we aren't in a SFINAE context, build a call to the 5822 // explicit conversion function. 5823 if (SemaRef.isSFINAEContext()) 5824 return true; 5825 5826 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5827 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5828 HadMultipleCandidates); 5829 if (Result.isInvalid()) 5830 return true; 5831 // Record usage of conversion in an implicit cast. 5832 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5833 CK_UserDefinedConversion, Result.get(), 5834 nullptr, Result.get()->getValueKind()); 5835 } 5836 return false; 5837 } 5838 5839 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5840 Sema::ContextualImplicitConverter &Converter, 5841 QualType T, bool HadMultipleCandidates, 5842 DeclAccessPair &Found) { 5843 CXXConversionDecl *Conversion = 5844 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5845 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5846 5847 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5848 if (!Converter.SuppressConversion) { 5849 if (SemaRef.isSFINAEContext()) 5850 return true; 5851 5852 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5853 << From->getSourceRange(); 5854 } 5855 5856 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5857 HadMultipleCandidates); 5858 if (Result.isInvalid()) 5859 return true; 5860 // Record usage of conversion in an implicit cast. 5861 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5862 CK_UserDefinedConversion, Result.get(), 5863 nullptr, Result.get()->getValueKind()); 5864 return false; 5865 } 5866 5867 static ExprResult finishContextualImplicitConversion( 5868 Sema &SemaRef, SourceLocation Loc, Expr *From, 5869 Sema::ContextualImplicitConverter &Converter) { 5870 if (!Converter.match(From->getType()) && !Converter.Suppress) 5871 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5872 << From->getSourceRange(); 5873 5874 return SemaRef.DefaultLvalueConversion(From); 5875 } 5876 5877 static void 5878 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5879 UnresolvedSetImpl &ViableConversions, 5880 OverloadCandidateSet &CandidateSet) { 5881 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5882 DeclAccessPair FoundDecl = ViableConversions[I]; 5883 NamedDecl *D = FoundDecl.getDecl(); 5884 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5885 if (isa<UsingShadowDecl>(D)) 5886 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5887 5888 CXXConversionDecl *Conv; 5889 FunctionTemplateDecl *ConvTemplate; 5890 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5891 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5892 else 5893 Conv = cast<CXXConversionDecl>(D); 5894 5895 if (ConvTemplate) 5896 SemaRef.AddTemplateConversionCandidate( 5897 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5898 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5899 else 5900 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5901 ToType, CandidateSet, 5902 /*AllowObjCConversionOnExplicit=*/false, 5903 /*AllowExplicit*/ true); 5904 } 5905 } 5906 5907 /// Attempt to convert the given expression to a type which is accepted 5908 /// by the given converter. 5909 /// 5910 /// This routine will attempt to convert an expression of class type to a 5911 /// type accepted by the specified converter. In C++11 and before, the class 5912 /// must have a single non-explicit conversion function converting to a matching 5913 /// type. In C++1y, there can be multiple such conversion functions, but only 5914 /// one target type. 5915 /// 5916 /// \param Loc The source location of the construct that requires the 5917 /// conversion. 5918 /// 5919 /// \param From The expression we're converting from. 5920 /// 5921 /// \param Converter Used to control and diagnose the conversion process. 5922 /// 5923 /// \returns The expression, converted to an integral or enumeration type if 5924 /// successful. 5925 ExprResult Sema::PerformContextualImplicitConversion( 5926 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5927 // We can't perform any more checking for type-dependent expressions. 5928 if (From->isTypeDependent()) 5929 return From; 5930 5931 // Process placeholders immediately. 5932 if (From->hasPlaceholderType()) { 5933 ExprResult result = CheckPlaceholderExpr(From); 5934 if (result.isInvalid()) 5935 return result; 5936 From = result.get(); 5937 } 5938 5939 // If the expression already has a matching type, we're golden. 5940 QualType T = From->getType(); 5941 if (Converter.match(T)) 5942 return DefaultLvalueConversion(From); 5943 5944 // FIXME: Check for missing '()' if T is a function type? 5945 5946 // We can only perform contextual implicit conversions on objects of class 5947 // type. 5948 const RecordType *RecordTy = T->getAs<RecordType>(); 5949 if (!RecordTy || !getLangOpts().CPlusPlus) { 5950 if (!Converter.Suppress) 5951 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5952 return From; 5953 } 5954 5955 // We must have a complete class type. 5956 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5957 ContextualImplicitConverter &Converter; 5958 Expr *From; 5959 5960 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5961 : Converter(Converter), From(From) {} 5962 5963 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5964 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5965 } 5966 } IncompleteDiagnoser(Converter, From); 5967 5968 if (Converter.Suppress ? !isCompleteType(Loc, T) 5969 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5970 return From; 5971 5972 // Look for a conversion to an integral or enumeration type. 5973 UnresolvedSet<4> 5974 ViableConversions; // These are *potentially* viable in C++1y. 5975 UnresolvedSet<4> ExplicitConversions; 5976 const auto &Conversions = 5977 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5978 5979 bool HadMultipleCandidates = 5980 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5981 5982 // To check that there is only one target type, in C++1y: 5983 QualType ToType; 5984 bool HasUniqueTargetType = true; 5985 5986 // Collect explicit or viable (potentially in C++1y) conversions. 5987 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5988 NamedDecl *D = (*I)->getUnderlyingDecl(); 5989 CXXConversionDecl *Conversion; 5990 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5991 if (ConvTemplate) { 5992 if (getLangOpts().CPlusPlus14) 5993 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5994 else 5995 continue; // C++11 does not consider conversion operator templates(?). 5996 } else 5997 Conversion = cast<CXXConversionDecl>(D); 5998 5999 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6000 "Conversion operator templates are considered potentially " 6001 "viable in C++1y"); 6002 6003 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6004 if (Converter.match(CurToType) || ConvTemplate) { 6005 6006 if (Conversion->isExplicit()) { 6007 // FIXME: For C++1y, do we need this restriction? 6008 // cf. diagnoseNoViableConversion() 6009 if (!ConvTemplate) 6010 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6011 } else { 6012 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6013 if (ToType.isNull()) 6014 ToType = CurToType.getUnqualifiedType(); 6015 else if (HasUniqueTargetType && 6016 (CurToType.getUnqualifiedType() != ToType)) 6017 HasUniqueTargetType = false; 6018 } 6019 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6020 } 6021 } 6022 } 6023 6024 if (getLangOpts().CPlusPlus14) { 6025 // C++1y [conv]p6: 6026 // ... An expression e of class type E appearing in such a context 6027 // is said to be contextually implicitly converted to a specified 6028 // type T and is well-formed if and only if e can be implicitly 6029 // converted to a type T that is determined as follows: E is searched 6030 // for conversion functions whose return type is cv T or reference to 6031 // cv T such that T is allowed by the context. There shall be 6032 // exactly one such T. 6033 6034 // If no unique T is found: 6035 if (ToType.isNull()) { 6036 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6037 HadMultipleCandidates, 6038 ExplicitConversions)) 6039 return ExprError(); 6040 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6041 } 6042 6043 // If more than one unique Ts are found: 6044 if (!HasUniqueTargetType) 6045 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6046 ViableConversions); 6047 6048 // If one unique T is found: 6049 // First, build a candidate set from the previously recorded 6050 // potentially viable conversions. 6051 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6052 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6053 CandidateSet); 6054 6055 // Then, perform overload resolution over the candidate set. 6056 OverloadCandidateSet::iterator Best; 6057 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6058 case OR_Success: { 6059 // Apply this conversion. 6060 DeclAccessPair Found = 6061 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6062 if (recordConversion(*this, Loc, From, Converter, T, 6063 HadMultipleCandidates, Found)) 6064 return ExprError(); 6065 break; 6066 } 6067 case OR_Ambiguous: 6068 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6069 ViableConversions); 6070 case OR_No_Viable_Function: 6071 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6072 HadMultipleCandidates, 6073 ExplicitConversions)) 6074 return ExprError(); 6075 LLVM_FALLTHROUGH; 6076 case OR_Deleted: 6077 // We'll complain below about a non-integral condition type. 6078 break; 6079 } 6080 } else { 6081 switch (ViableConversions.size()) { 6082 case 0: { 6083 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6084 HadMultipleCandidates, 6085 ExplicitConversions)) 6086 return ExprError(); 6087 6088 // We'll complain below about a non-integral condition type. 6089 break; 6090 } 6091 case 1: { 6092 // Apply this conversion. 6093 DeclAccessPair Found = ViableConversions[0]; 6094 if (recordConversion(*this, Loc, From, Converter, T, 6095 HadMultipleCandidates, Found)) 6096 return ExprError(); 6097 break; 6098 } 6099 default: 6100 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6101 ViableConversions); 6102 } 6103 } 6104 6105 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6106 } 6107 6108 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6109 /// an acceptable non-member overloaded operator for a call whose 6110 /// arguments have types T1 (and, if non-empty, T2). This routine 6111 /// implements the check in C++ [over.match.oper]p3b2 concerning 6112 /// enumeration types. 6113 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6114 FunctionDecl *Fn, 6115 ArrayRef<Expr *> Args) { 6116 QualType T1 = Args[0]->getType(); 6117 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6118 6119 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6120 return true; 6121 6122 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6123 return true; 6124 6125 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6126 if (Proto->getNumParams() < 1) 6127 return false; 6128 6129 if (T1->isEnumeralType()) { 6130 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6131 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6132 return true; 6133 } 6134 6135 if (Proto->getNumParams() < 2) 6136 return false; 6137 6138 if (!T2.isNull() && T2->isEnumeralType()) { 6139 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6140 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6141 return true; 6142 } 6143 6144 return false; 6145 } 6146 6147 /// AddOverloadCandidate - Adds the given function to the set of 6148 /// candidate functions, using the given function call arguments. If 6149 /// @p SuppressUserConversions, then don't allow user-defined 6150 /// conversions via constructors or conversion operators. 6151 /// 6152 /// \param PartialOverloading true if we are performing "partial" overloading 6153 /// based on an incomplete set of function arguments. This feature is used by 6154 /// code completion. 6155 void Sema::AddOverloadCandidate( 6156 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6157 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6158 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6159 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6160 OverloadCandidateParamOrder PO) { 6161 const FunctionProtoType *Proto 6162 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6163 assert(Proto && "Functions without a prototype cannot be overloaded"); 6164 assert(!Function->getDescribedFunctionTemplate() && 6165 "Use AddTemplateOverloadCandidate for function templates"); 6166 6167 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6168 if (!isa<CXXConstructorDecl>(Method)) { 6169 // If we get here, it's because we're calling a member function 6170 // that is named without a member access expression (e.g., 6171 // "this->f") that was either written explicitly or created 6172 // implicitly. This can happen with a qualified call to a member 6173 // function, e.g., X::f(). We use an empty type for the implied 6174 // object argument (C++ [over.call.func]p3), and the acting context 6175 // is irrelevant. 6176 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6177 Expr::Classification::makeSimpleLValue(), Args, 6178 CandidateSet, SuppressUserConversions, 6179 PartialOverloading, EarlyConversions, PO); 6180 return; 6181 } 6182 // We treat a constructor like a non-member function, since its object 6183 // argument doesn't participate in overload resolution. 6184 } 6185 6186 if (!CandidateSet.isNewCandidate(Function, PO)) 6187 return; 6188 6189 // C++11 [class.copy]p11: [DR1402] 6190 // A defaulted move constructor that is defined as deleted is ignored by 6191 // overload resolution. 6192 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6193 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6194 Constructor->isMoveConstructor()) 6195 return; 6196 6197 // Overload resolution is always an unevaluated context. 6198 EnterExpressionEvaluationContext Unevaluated( 6199 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6200 6201 // C++ [over.match.oper]p3: 6202 // if no operand has a class type, only those non-member functions in the 6203 // lookup set that have a first parameter of type T1 or "reference to 6204 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6205 // is a right operand) a second parameter of type T2 or "reference to 6206 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6207 // candidate functions. 6208 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6209 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6210 return; 6211 6212 // Add this candidate 6213 OverloadCandidate &Candidate = 6214 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6215 Candidate.FoundDecl = FoundDecl; 6216 Candidate.Function = Function; 6217 Candidate.Viable = true; 6218 Candidate.RewriteKind = 6219 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6220 Candidate.IsSurrogate = false; 6221 Candidate.IsADLCandidate = IsADLCandidate; 6222 Candidate.IgnoreObjectArgument = false; 6223 Candidate.ExplicitCallArguments = Args.size(); 6224 6225 // Explicit functions are not actually candidates at all if we're not 6226 // allowing them in this context, but keep them around so we can point 6227 // to them in diagnostics. 6228 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6229 Candidate.Viable = false; 6230 Candidate.FailureKind = ovl_fail_explicit; 6231 return; 6232 } 6233 6234 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6235 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6236 Candidate.Viable = false; 6237 Candidate.FailureKind = ovl_non_default_multiversion_function; 6238 return; 6239 } 6240 6241 if (Constructor) { 6242 // C++ [class.copy]p3: 6243 // A member function template is never instantiated to perform the copy 6244 // of a class object to an object of its class type. 6245 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6246 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6247 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6248 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6249 ClassType))) { 6250 Candidate.Viable = false; 6251 Candidate.FailureKind = ovl_fail_illegal_constructor; 6252 return; 6253 } 6254 6255 // C++ [over.match.funcs]p8: (proposed DR resolution) 6256 // A constructor inherited from class type C that has a first parameter 6257 // of type "reference to P" (including such a constructor instantiated 6258 // from a template) is excluded from the set of candidate functions when 6259 // constructing an object of type cv D if the argument list has exactly 6260 // one argument and D is reference-related to P and P is reference-related 6261 // to C. 6262 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6263 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6264 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6265 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6266 QualType C = Context.getRecordType(Constructor->getParent()); 6267 QualType D = Context.getRecordType(Shadow->getParent()); 6268 SourceLocation Loc = Args.front()->getExprLoc(); 6269 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6270 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6271 Candidate.Viable = false; 6272 Candidate.FailureKind = ovl_fail_inhctor_slice; 6273 return; 6274 } 6275 } 6276 6277 // Check that the constructor is capable of constructing an object in the 6278 // destination address space. 6279 if (!Qualifiers::isAddressSpaceSupersetOf( 6280 Constructor->getMethodQualifiers().getAddressSpace(), 6281 CandidateSet.getDestAS())) { 6282 Candidate.Viable = false; 6283 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6284 } 6285 } 6286 6287 unsigned NumParams = Proto->getNumParams(); 6288 6289 // (C++ 13.3.2p2): A candidate function having fewer than m 6290 // parameters is viable only if it has an ellipsis in its parameter 6291 // list (8.3.5). 6292 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6293 !Proto->isVariadic()) { 6294 Candidate.Viable = false; 6295 Candidate.FailureKind = ovl_fail_too_many_arguments; 6296 return; 6297 } 6298 6299 // (C++ 13.3.2p2): A candidate function having more than m parameters 6300 // is viable only if the (m+1)st parameter has a default argument 6301 // (8.3.6). For the purposes of overload resolution, the 6302 // parameter list is truncated on the right, so that there are 6303 // exactly m parameters. 6304 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6305 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6306 // Not enough arguments. 6307 Candidate.Viable = false; 6308 Candidate.FailureKind = ovl_fail_too_few_arguments; 6309 return; 6310 } 6311 6312 // (CUDA B.1): Check for invalid calls between targets. 6313 if (getLangOpts().CUDA) 6314 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6315 // Skip the check for callers that are implicit members, because in this 6316 // case we may not yet know what the member's target is; the target is 6317 // inferred for the member automatically, based on the bases and fields of 6318 // the class. 6319 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6320 Candidate.Viable = false; 6321 Candidate.FailureKind = ovl_fail_bad_target; 6322 return; 6323 } 6324 6325 if (Function->getTrailingRequiresClause()) { 6326 ConstraintSatisfaction Satisfaction; 6327 if (CheckFunctionConstraints(Function, Satisfaction) || 6328 !Satisfaction.IsSatisfied) { 6329 Candidate.Viable = false; 6330 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6331 return; 6332 } 6333 } 6334 6335 // Determine the implicit conversion sequences for each of the 6336 // arguments. 6337 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6338 unsigned ConvIdx = 6339 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6340 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6341 // We already formed a conversion sequence for this parameter during 6342 // template argument deduction. 6343 } else if (ArgIdx < NumParams) { 6344 // (C++ 13.3.2p3): for F to be a viable function, there shall 6345 // exist for each argument an implicit conversion sequence 6346 // (13.3.3.1) that converts that argument to the corresponding 6347 // parameter of F. 6348 QualType ParamType = Proto->getParamType(ArgIdx); 6349 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6350 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6351 /*InOverloadResolution=*/true, 6352 /*AllowObjCWritebackConversion=*/ 6353 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6354 if (Candidate.Conversions[ConvIdx].isBad()) { 6355 Candidate.Viable = false; 6356 Candidate.FailureKind = ovl_fail_bad_conversion; 6357 return; 6358 } 6359 } else { 6360 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6361 // argument for which there is no corresponding parameter is 6362 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6363 Candidate.Conversions[ConvIdx].setEllipsis(); 6364 } 6365 } 6366 6367 if (EnableIfAttr *FailedAttr = 6368 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6369 Candidate.Viable = false; 6370 Candidate.FailureKind = ovl_fail_enable_if; 6371 Candidate.DeductionFailure.Data = FailedAttr; 6372 return; 6373 } 6374 6375 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6376 Candidate.Viable = false; 6377 Candidate.FailureKind = ovl_fail_ext_disabled; 6378 return; 6379 } 6380 } 6381 6382 ObjCMethodDecl * 6383 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6384 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6385 if (Methods.size() <= 1) 6386 return nullptr; 6387 6388 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6389 bool Match = true; 6390 ObjCMethodDecl *Method = Methods[b]; 6391 unsigned NumNamedArgs = Sel.getNumArgs(); 6392 // Method might have more arguments than selector indicates. This is due 6393 // to addition of c-style arguments in method. 6394 if (Method->param_size() > NumNamedArgs) 6395 NumNamedArgs = Method->param_size(); 6396 if (Args.size() < NumNamedArgs) 6397 continue; 6398 6399 for (unsigned i = 0; i < NumNamedArgs; i++) { 6400 // We can't do any type-checking on a type-dependent argument. 6401 if (Args[i]->isTypeDependent()) { 6402 Match = false; 6403 break; 6404 } 6405 6406 ParmVarDecl *param = Method->parameters()[i]; 6407 Expr *argExpr = Args[i]; 6408 assert(argExpr && "SelectBestMethod(): missing expression"); 6409 6410 // Strip the unbridged-cast placeholder expression off unless it's 6411 // a consumed argument. 6412 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6413 !param->hasAttr<CFConsumedAttr>()) 6414 argExpr = stripARCUnbridgedCast(argExpr); 6415 6416 // If the parameter is __unknown_anytype, move on to the next method. 6417 if (param->getType() == Context.UnknownAnyTy) { 6418 Match = false; 6419 break; 6420 } 6421 6422 ImplicitConversionSequence ConversionState 6423 = TryCopyInitialization(*this, argExpr, param->getType(), 6424 /*SuppressUserConversions*/false, 6425 /*InOverloadResolution=*/true, 6426 /*AllowObjCWritebackConversion=*/ 6427 getLangOpts().ObjCAutoRefCount, 6428 /*AllowExplicit*/false); 6429 // This function looks for a reasonably-exact match, so we consider 6430 // incompatible pointer conversions to be a failure here. 6431 if (ConversionState.isBad() || 6432 (ConversionState.isStandard() && 6433 ConversionState.Standard.Second == 6434 ICK_Incompatible_Pointer_Conversion)) { 6435 Match = false; 6436 break; 6437 } 6438 } 6439 // Promote additional arguments to variadic methods. 6440 if (Match && Method->isVariadic()) { 6441 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6442 if (Args[i]->isTypeDependent()) { 6443 Match = false; 6444 break; 6445 } 6446 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6447 nullptr); 6448 if (Arg.isInvalid()) { 6449 Match = false; 6450 break; 6451 } 6452 } 6453 } else { 6454 // Check for extra arguments to non-variadic methods. 6455 if (Args.size() != NumNamedArgs) 6456 Match = false; 6457 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6458 // Special case when selectors have no argument. In this case, select 6459 // one with the most general result type of 'id'. 6460 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6461 QualType ReturnT = Methods[b]->getReturnType(); 6462 if (ReturnT->isObjCIdType()) 6463 return Methods[b]; 6464 } 6465 } 6466 } 6467 6468 if (Match) 6469 return Method; 6470 } 6471 return nullptr; 6472 } 6473 6474 static bool convertArgsForAvailabilityChecks( 6475 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6476 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6477 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6478 if (ThisArg) { 6479 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6480 assert(!isa<CXXConstructorDecl>(Method) && 6481 "Shouldn't have `this` for ctors!"); 6482 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6483 ExprResult R = S.PerformObjectArgumentInitialization( 6484 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6485 if (R.isInvalid()) 6486 return false; 6487 ConvertedThis = R.get(); 6488 } else { 6489 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6490 (void)MD; 6491 assert((MissingImplicitThis || MD->isStatic() || 6492 isa<CXXConstructorDecl>(MD)) && 6493 "Expected `this` for non-ctor instance methods"); 6494 } 6495 ConvertedThis = nullptr; 6496 } 6497 6498 // Ignore any variadic arguments. Converting them is pointless, since the 6499 // user can't refer to them in the function condition. 6500 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6501 6502 // Convert the arguments. 6503 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6504 ExprResult R; 6505 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6506 S.Context, Function->getParamDecl(I)), 6507 SourceLocation(), Args[I]); 6508 6509 if (R.isInvalid()) 6510 return false; 6511 6512 ConvertedArgs.push_back(R.get()); 6513 } 6514 6515 if (Trap.hasErrorOccurred()) 6516 return false; 6517 6518 // Push default arguments if needed. 6519 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6520 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6521 ParmVarDecl *P = Function->getParamDecl(i); 6522 if (!P->hasDefaultArg()) 6523 return false; 6524 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6525 if (R.isInvalid()) 6526 return false; 6527 ConvertedArgs.push_back(R.get()); 6528 } 6529 6530 if (Trap.hasErrorOccurred()) 6531 return false; 6532 } 6533 return true; 6534 } 6535 6536 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6537 SourceLocation CallLoc, 6538 ArrayRef<Expr *> Args, 6539 bool MissingImplicitThis) { 6540 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6541 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6542 return nullptr; 6543 6544 SFINAETrap Trap(*this); 6545 SmallVector<Expr *, 16> ConvertedArgs; 6546 // FIXME: We should look into making enable_if late-parsed. 6547 Expr *DiscardedThis; 6548 if (!convertArgsForAvailabilityChecks( 6549 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6550 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6551 return *EnableIfAttrs.begin(); 6552 6553 for (auto *EIA : EnableIfAttrs) { 6554 APValue Result; 6555 // FIXME: This doesn't consider value-dependent cases, because doing so is 6556 // very difficult. Ideally, we should handle them more gracefully. 6557 if (EIA->getCond()->isValueDependent() || 6558 !EIA->getCond()->EvaluateWithSubstitution( 6559 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6560 return EIA; 6561 6562 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6563 return EIA; 6564 } 6565 return nullptr; 6566 } 6567 6568 template <typename CheckFn> 6569 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6570 bool ArgDependent, SourceLocation Loc, 6571 CheckFn &&IsSuccessful) { 6572 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6573 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6574 if (ArgDependent == DIA->getArgDependent()) 6575 Attrs.push_back(DIA); 6576 } 6577 6578 // Common case: No diagnose_if attributes, so we can quit early. 6579 if (Attrs.empty()) 6580 return false; 6581 6582 auto WarningBegin = std::stable_partition( 6583 Attrs.begin(), Attrs.end(), 6584 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6585 6586 // Note that diagnose_if attributes are late-parsed, so they appear in the 6587 // correct order (unlike enable_if attributes). 6588 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6589 IsSuccessful); 6590 if (ErrAttr != WarningBegin) { 6591 const DiagnoseIfAttr *DIA = *ErrAttr; 6592 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6593 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6594 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6595 return true; 6596 } 6597 6598 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6599 if (IsSuccessful(DIA)) { 6600 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6601 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6602 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6603 } 6604 6605 return false; 6606 } 6607 6608 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6609 const Expr *ThisArg, 6610 ArrayRef<const Expr *> Args, 6611 SourceLocation Loc) { 6612 return diagnoseDiagnoseIfAttrsWith( 6613 *this, Function, /*ArgDependent=*/true, Loc, 6614 [&](const DiagnoseIfAttr *DIA) { 6615 APValue Result; 6616 // It's sane to use the same Args for any redecl of this function, since 6617 // EvaluateWithSubstitution only cares about the position of each 6618 // argument in the arg list, not the ParmVarDecl* it maps to. 6619 if (!DIA->getCond()->EvaluateWithSubstitution( 6620 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6621 return false; 6622 return Result.isInt() && Result.getInt().getBoolValue(); 6623 }); 6624 } 6625 6626 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6627 SourceLocation Loc) { 6628 return diagnoseDiagnoseIfAttrsWith( 6629 *this, ND, /*ArgDependent=*/false, Loc, 6630 [&](const DiagnoseIfAttr *DIA) { 6631 bool Result; 6632 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6633 Result; 6634 }); 6635 } 6636 6637 /// Add all of the function declarations in the given function set to 6638 /// the overload candidate set. 6639 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6640 ArrayRef<Expr *> Args, 6641 OverloadCandidateSet &CandidateSet, 6642 TemplateArgumentListInfo *ExplicitTemplateArgs, 6643 bool SuppressUserConversions, 6644 bool PartialOverloading, 6645 bool FirstArgumentIsBase) { 6646 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6647 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6648 ArrayRef<Expr *> FunctionArgs = Args; 6649 6650 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6651 FunctionDecl *FD = 6652 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6653 6654 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6655 QualType ObjectType; 6656 Expr::Classification ObjectClassification; 6657 if (Args.size() > 0) { 6658 if (Expr *E = Args[0]) { 6659 // Use the explicit base to restrict the lookup: 6660 ObjectType = E->getType(); 6661 // Pointers in the object arguments are implicitly dereferenced, so we 6662 // always classify them as l-values. 6663 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6664 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6665 else 6666 ObjectClassification = E->Classify(Context); 6667 } // .. else there is an implicit base. 6668 FunctionArgs = Args.slice(1); 6669 } 6670 if (FunTmpl) { 6671 AddMethodTemplateCandidate( 6672 FunTmpl, F.getPair(), 6673 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6674 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6675 FunctionArgs, CandidateSet, SuppressUserConversions, 6676 PartialOverloading); 6677 } else { 6678 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6679 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6680 ObjectClassification, FunctionArgs, CandidateSet, 6681 SuppressUserConversions, PartialOverloading); 6682 } 6683 } else { 6684 // This branch handles both standalone functions and static methods. 6685 6686 // Slice the first argument (which is the base) when we access 6687 // static method as non-static. 6688 if (Args.size() > 0 && 6689 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6690 !isa<CXXConstructorDecl>(FD)))) { 6691 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6692 FunctionArgs = Args.slice(1); 6693 } 6694 if (FunTmpl) { 6695 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6696 ExplicitTemplateArgs, FunctionArgs, 6697 CandidateSet, SuppressUserConversions, 6698 PartialOverloading); 6699 } else { 6700 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6701 SuppressUserConversions, PartialOverloading); 6702 } 6703 } 6704 } 6705 } 6706 6707 /// AddMethodCandidate - Adds a named decl (which is some kind of 6708 /// method) as a method candidate to the given overload set. 6709 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6710 Expr::Classification ObjectClassification, 6711 ArrayRef<Expr *> Args, 6712 OverloadCandidateSet &CandidateSet, 6713 bool SuppressUserConversions, 6714 OverloadCandidateParamOrder PO) { 6715 NamedDecl *Decl = FoundDecl.getDecl(); 6716 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6717 6718 if (isa<UsingShadowDecl>(Decl)) 6719 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6720 6721 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6722 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6723 "Expected a member function template"); 6724 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6725 /*ExplicitArgs*/ nullptr, ObjectType, 6726 ObjectClassification, Args, CandidateSet, 6727 SuppressUserConversions, false, PO); 6728 } else { 6729 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6730 ObjectType, ObjectClassification, Args, CandidateSet, 6731 SuppressUserConversions, false, None, PO); 6732 } 6733 } 6734 6735 /// AddMethodCandidate - Adds the given C++ member function to the set 6736 /// of candidate functions, using the given function call arguments 6737 /// and the object argument (@c Object). For example, in a call 6738 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6739 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6740 /// allow user-defined conversions via constructors or conversion 6741 /// operators. 6742 void 6743 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6744 CXXRecordDecl *ActingContext, QualType ObjectType, 6745 Expr::Classification ObjectClassification, 6746 ArrayRef<Expr *> Args, 6747 OverloadCandidateSet &CandidateSet, 6748 bool SuppressUserConversions, 6749 bool PartialOverloading, 6750 ConversionSequenceList EarlyConversions, 6751 OverloadCandidateParamOrder PO) { 6752 const FunctionProtoType *Proto 6753 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6754 assert(Proto && "Methods without a prototype cannot be overloaded"); 6755 assert(!isa<CXXConstructorDecl>(Method) && 6756 "Use AddOverloadCandidate for constructors"); 6757 6758 if (!CandidateSet.isNewCandidate(Method, PO)) 6759 return; 6760 6761 // C++11 [class.copy]p23: [DR1402] 6762 // A defaulted move assignment operator that is defined as deleted is 6763 // ignored by overload resolution. 6764 if (Method->isDefaulted() && Method->isDeleted() && 6765 Method->isMoveAssignmentOperator()) 6766 return; 6767 6768 // Overload resolution is always an unevaluated context. 6769 EnterExpressionEvaluationContext Unevaluated( 6770 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6771 6772 // Add this candidate 6773 OverloadCandidate &Candidate = 6774 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6775 Candidate.FoundDecl = FoundDecl; 6776 Candidate.Function = Method; 6777 Candidate.RewriteKind = 6778 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6779 Candidate.IsSurrogate = false; 6780 Candidate.IgnoreObjectArgument = false; 6781 Candidate.ExplicitCallArguments = Args.size(); 6782 6783 unsigned NumParams = Proto->getNumParams(); 6784 6785 // (C++ 13.3.2p2): A candidate function having fewer than m 6786 // parameters is viable only if it has an ellipsis in its parameter 6787 // list (8.3.5). 6788 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6789 !Proto->isVariadic()) { 6790 Candidate.Viable = false; 6791 Candidate.FailureKind = ovl_fail_too_many_arguments; 6792 return; 6793 } 6794 6795 // (C++ 13.3.2p2): A candidate function having more than m parameters 6796 // is viable only if the (m+1)st parameter has a default argument 6797 // (8.3.6). For the purposes of overload resolution, the 6798 // parameter list is truncated on the right, so that there are 6799 // exactly m parameters. 6800 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6801 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6802 // Not enough arguments. 6803 Candidate.Viable = false; 6804 Candidate.FailureKind = ovl_fail_too_few_arguments; 6805 return; 6806 } 6807 6808 Candidate.Viable = true; 6809 6810 if (Method->isStatic() || ObjectType.isNull()) 6811 // The implicit object argument is ignored. 6812 Candidate.IgnoreObjectArgument = true; 6813 else { 6814 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6815 // Determine the implicit conversion sequence for the object 6816 // parameter. 6817 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6818 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6819 Method, ActingContext); 6820 if (Candidate.Conversions[ConvIdx].isBad()) { 6821 Candidate.Viable = false; 6822 Candidate.FailureKind = ovl_fail_bad_conversion; 6823 return; 6824 } 6825 } 6826 6827 // (CUDA B.1): Check for invalid calls between targets. 6828 if (getLangOpts().CUDA) 6829 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6830 if (!IsAllowedCUDACall(Caller, Method)) { 6831 Candidate.Viable = false; 6832 Candidate.FailureKind = ovl_fail_bad_target; 6833 return; 6834 } 6835 6836 if (Method->getTrailingRequiresClause()) { 6837 ConstraintSatisfaction Satisfaction; 6838 if (CheckFunctionConstraints(Method, Satisfaction) || 6839 !Satisfaction.IsSatisfied) { 6840 Candidate.Viable = false; 6841 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6842 return; 6843 } 6844 } 6845 6846 // Determine the implicit conversion sequences for each of the 6847 // arguments. 6848 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6849 unsigned ConvIdx = 6850 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6851 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6852 // We already formed a conversion sequence for this parameter during 6853 // template argument deduction. 6854 } else if (ArgIdx < NumParams) { 6855 // (C++ 13.3.2p3): for F to be a viable function, there shall 6856 // exist for each argument an implicit conversion sequence 6857 // (13.3.3.1) that converts that argument to the corresponding 6858 // parameter of F. 6859 QualType ParamType = Proto->getParamType(ArgIdx); 6860 Candidate.Conversions[ConvIdx] 6861 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6862 SuppressUserConversions, 6863 /*InOverloadResolution=*/true, 6864 /*AllowObjCWritebackConversion=*/ 6865 getLangOpts().ObjCAutoRefCount); 6866 if (Candidate.Conversions[ConvIdx].isBad()) { 6867 Candidate.Viable = false; 6868 Candidate.FailureKind = ovl_fail_bad_conversion; 6869 return; 6870 } 6871 } else { 6872 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6873 // argument for which there is no corresponding parameter is 6874 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6875 Candidate.Conversions[ConvIdx].setEllipsis(); 6876 } 6877 } 6878 6879 if (EnableIfAttr *FailedAttr = 6880 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6881 Candidate.Viable = false; 6882 Candidate.FailureKind = ovl_fail_enable_if; 6883 Candidate.DeductionFailure.Data = FailedAttr; 6884 return; 6885 } 6886 6887 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6888 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6889 Candidate.Viable = false; 6890 Candidate.FailureKind = ovl_non_default_multiversion_function; 6891 } 6892 } 6893 6894 /// Add a C++ member function template as a candidate to the candidate 6895 /// set, using template argument deduction to produce an appropriate member 6896 /// function template specialization. 6897 void Sema::AddMethodTemplateCandidate( 6898 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6899 CXXRecordDecl *ActingContext, 6900 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6901 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6902 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6903 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6904 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6905 return; 6906 6907 // C++ [over.match.funcs]p7: 6908 // In each case where a candidate is a function template, candidate 6909 // function template specializations are generated using template argument 6910 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6911 // candidate functions in the usual way.113) A given name can refer to one 6912 // or more function templates and also to a set of overloaded non-template 6913 // functions. In such a case, the candidate functions generated from each 6914 // function template are combined with the set of non-template candidate 6915 // functions. 6916 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6917 FunctionDecl *Specialization = nullptr; 6918 ConversionSequenceList Conversions; 6919 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6920 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6921 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6922 return CheckNonDependentConversions( 6923 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6924 SuppressUserConversions, ActingContext, ObjectType, 6925 ObjectClassification, PO); 6926 })) { 6927 OverloadCandidate &Candidate = 6928 CandidateSet.addCandidate(Conversions.size(), Conversions); 6929 Candidate.FoundDecl = FoundDecl; 6930 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6931 Candidate.Viable = false; 6932 Candidate.RewriteKind = 6933 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6934 Candidate.IsSurrogate = false; 6935 Candidate.IgnoreObjectArgument = 6936 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6937 ObjectType.isNull(); 6938 Candidate.ExplicitCallArguments = Args.size(); 6939 if (Result == TDK_NonDependentConversionFailure) 6940 Candidate.FailureKind = ovl_fail_bad_conversion; 6941 else { 6942 Candidate.FailureKind = ovl_fail_bad_deduction; 6943 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6944 Info); 6945 } 6946 return; 6947 } 6948 6949 // Add the function template specialization produced by template argument 6950 // deduction as a candidate. 6951 assert(Specialization && "Missing member function template specialization?"); 6952 assert(isa<CXXMethodDecl>(Specialization) && 6953 "Specialization is not a member function?"); 6954 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6955 ActingContext, ObjectType, ObjectClassification, Args, 6956 CandidateSet, SuppressUserConversions, PartialOverloading, 6957 Conversions, PO); 6958 } 6959 6960 /// Determine whether a given function template has a simple explicit specifier 6961 /// or a non-value-dependent explicit-specification that evaluates to true. 6962 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6963 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6964 } 6965 6966 /// Add a C++ function template specialization as a candidate 6967 /// in the candidate set, using template argument deduction to produce 6968 /// an appropriate function template specialization. 6969 void Sema::AddTemplateOverloadCandidate( 6970 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6971 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6972 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6973 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6974 OverloadCandidateParamOrder PO) { 6975 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6976 return; 6977 6978 // If the function template has a non-dependent explicit specification, 6979 // exclude it now if appropriate; we are not permitted to perform deduction 6980 // and substitution in this case. 6981 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6982 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6983 Candidate.FoundDecl = FoundDecl; 6984 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6985 Candidate.Viable = false; 6986 Candidate.FailureKind = ovl_fail_explicit; 6987 return; 6988 } 6989 6990 // C++ [over.match.funcs]p7: 6991 // In each case where a candidate is a function template, candidate 6992 // function template specializations are generated using template argument 6993 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6994 // candidate functions in the usual way.113) A given name can refer to one 6995 // or more function templates and also to a set of overloaded non-template 6996 // functions. In such a case, the candidate functions generated from each 6997 // function template are combined with the set of non-template candidate 6998 // functions. 6999 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7000 FunctionDecl *Specialization = nullptr; 7001 ConversionSequenceList Conversions; 7002 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7003 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7004 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7005 return CheckNonDependentConversions( 7006 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7007 SuppressUserConversions, nullptr, QualType(), {}, PO); 7008 })) { 7009 OverloadCandidate &Candidate = 7010 CandidateSet.addCandidate(Conversions.size(), Conversions); 7011 Candidate.FoundDecl = FoundDecl; 7012 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7013 Candidate.Viable = false; 7014 Candidate.RewriteKind = 7015 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7016 Candidate.IsSurrogate = false; 7017 Candidate.IsADLCandidate = IsADLCandidate; 7018 // Ignore the object argument if there is one, since we don't have an object 7019 // type. 7020 Candidate.IgnoreObjectArgument = 7021 isa<CXXMethodDecl>(Candidate.Function) && 7022 !isa<CXXConstructorDecl>(Candidate.Function); 7023 Candidate.ExplicitCallArguments = Args.size(); 7024 if (Result == TDK_NonDependentConversionFailure) 7025 Candidate.FailureKind = ovl_fail_bad_conversion; 7026 else { 7027 Candidate.FailureKind = ovl_fail_bad_deduction; 7028 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7029 Info); 7030 } 7031 return; 7032 } 7033 7034 // Add the function template specialization produced by template argument 7035 // deduction as a candidate. 7036 assert(Specialization && "Missing function template specialization?"); 7037 AddOverloadCandidate( 7038 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7039 PartialOverloading, AllowExplicit, 7040 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7041 } 7042 7043 /// Check that implicit conversion sequences can be formed for each argument 7044 /// whose corresponding parameter has a non-dependent type, per DR1391's 7045 /// [temp.deduct.call]p10. 7046 bool Sema::CheckNonDependentConversions( 7047 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7048 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7049 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7050 CXXRecordDecl *ActingContext, QualType ObjectType, 7051 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7052 // FIXME: The cases in which we allow explicit conversions for constructor 7053 // arguments never consider calling a constructor template. It's not clear 7054 // that is correct. 7055 const bool AllowExplicit = false; 7056 7057 auto *FD = FunctionTemplate->getTemplatedDecl(); 7058 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7059 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7060 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7061 7062 Conversions = 7063 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7064 7065 // Overload resolution is always an unevaluated context. 7066 EnterExpressionEvaluationContext Unevaluated( 7067 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7068 7069 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7070 // require that, but this check should never result in a hard error, and 7071 // overload resolution is permitted to sidestep instantiations. 7072 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7073 !ObjectType.isNull()) { 7074 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7075 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7076 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7077 Method, ActingContext); 7078 if (Conversions[ConvIdx].isBad()) 7079 return true; 7080 } 7081 7082 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7083 ++I) { 7084 QualType ParamType = ParamTypes[I]; 7085 if (!ParamType->isDependentType()) { 7086 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7087 ? 0 7088 : (ThisConversions + I); 7089 Conversions[ConvIdx] 7090 = TryCopyInitialization(*this, Args[I], ParamType, 7091 SuppressUserConversions, 7092 /*InOverloadResolution=*/true, 7093 /*AllowObjCWritebackConversion=*/ 7094 getLangOpts().ObjCAutoRefCount, 7095 AllowExplicit); 7096 if (Conversions[ConvIdx].isBad()) 7097 return true; 7098 } 7099 } 7100 7101 return false; 7102 } 7103 7104 /// Determine whether this is an allowable conversion from the result 7105 /// of an explicit conversion operator to the expected type, per C++ 7106 /// [over.match.conv]p1 and [over.match.ref]p1. 7107 /// 7108 /// \param ConvType The return type of the conversion function. 7109 /// 7110 /// \param ToType The type we are converting to. 7111 /// 7112 /// \param AllowObjCPointerConversion Allow a conversion from one 7113 /// Objective-C pointer to another. 7114 /// 7115 /// \returns true if the conversion is allowable, false otherwise. 7116 static bool isAllowableExplicitConversion(Sema &S, 7117 QualType ConvType, QualType ToType, 7118 bool AllowObjCPointerConversion) { 7119 QualType ToNonRefType = ToType.getNonReferenceType(); 7120 7121 // Easy case: the types are the same. 7122 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7123 return true; 7124 7125 // Allow qualification conversions. 7126 bool ObjCLifetimeConversion; 7127 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7128 ObjCLifetimeConversion)) 7129 return true; 7130 7131 // If we're not allowed to consider Objective-C pointer conversions, 7132 // we're done. 7133 if (!AllowObjCPointerConversion) 7134 return false; 7135 7136 // Is this an Objective-C pointer conversion? 7137 bool IncompatibleObjC = false; 7138 QualType ConvertedType; 7139 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7140 IncompatibleObjC); 7141 } 7142 7143 /// AddConversionCandidate - Add a C++ conversion function as a 7144 /// candidate in the candidate set (C++ [over.match.conv], 7145 /// C++ [over.match.copy]). From is the expression we're converting from, 7146 /// and ToType is the type that we're eventually trying to convert to 7147 /// (which may or may not be the same type as the type that the 7148 /// conversion function produces). 7149 void Sema::AddConversionCandidate( 7150 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7151 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7152 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7153 bool AllowExplicit, bool AllowResultConversion) { 7154 assert(!Conversion->getDescribedFunctionTemplate() && 7155 "Conversion function templates use AddTemplateConversionCandidate"); 7156 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7157 if (!CandidateSet.isNewCandidate(Conversion)) 7158 return; 7159 7160 // If the conversion function has an undeduced return type, trigger its 7161 // deduction now. 7162 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7163 if (DeduceReturnType(Conversion, From->getExprLoc())) 7164 return; 7165 ConvType = Conversion->getConversionType().getNonReferenceType(); 7166 } 7167 7168 // If we don't allow any conversion of the result type, ignore conversion 7169 // functions that don't convert to exactly (possibly cv-qualified) T. 7170 if (!AllowResultConversion && 7171 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7172 return; 7173 7174 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7175 // operator is only a candidate if its return type is the target type or 7176 // can be converted to the target type with a qualification conversion. 7177 // 7178 // FIXME: Include such functions in the candidate list and explain why we 7179 // can't select them. 7180 if (Conversion->isExplicit() && 7181 !isAllowableExplicitConversion(*this, ConvType, ToType, 7182 AllowObjCConversionOnExplicit)) 7183 return; 7184 7185 // Overload resolution is always an unevaluated context. 7186 EnterExpressionEvaluationContext Unevaluated( 7187 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7188 7189 // Add this candidate 7190 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7191 Candidate.FoundDecl = FoundDecl; 7192 Candidate.Function = Conversion; 7193 Candidate.IsSurrogate = false; 7194 Candidate.IgnoreObjectArgument = false; 7195 Candidate.FinalConversion.setAsIdentityConversion(); 7196 Candidate.FinalConversion.setFromType(ConvType); 7197 Candidate.FinalConversion.setAllToTypes(ToType); 7198 Candidate.Viable = true; 7199 Candidate.ExplicitCallArguments = 1; 7200 7201 // Explicit functions are not actually candidates at all if we're not 7202 // allowing them in this context, but keep them around so we can point 7203 // to them in diagnostics. 7204 if (!AllowExplicit && Conversion->isExplicit()) { 7205 Candidate.Viable = false; 7206 Candidate.FailureKind = ovl_fail_explicit; 7207 return; 7208 } 7209 7210 // C++ [over.match.funcs]p4: 7211 // For conversion functions, the function is considered to be a member of 7212 // the class of the implicit implied object argument for the purpose of 7213 // defining the type of the implicit object parameter. 7214 // 7215 // Determine the implicit conversion sequence for the implicit 7216 // object parameter. 7217 QualType ImplicitParamType = From->getType(); 7218 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7219 ImplicitParamType = FromPtrType->getPointeeType(); 7220 CXXRecordDecl *ConversionContext 7221 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7222 7223 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7224 *this, CandidateSet.getLocation(), From->getType(), 7225 From->Classify(Context), Conversion, ConversionContext); 7226 7227 if (Candidate.Conversions[0].isBad()) { 7228 Candidate.Viable = false; 7229 Candidate.FailureKind = ovl_fail_bad_conversion; 7230 return; 7231 } 7232 7233 if (Conversion->getTrailingRequiresClause()) { 7234 ConstraintSatisfaction Satisfaction; 7235 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7236 !Satisfaction.IsSatisfied) { 7237 Candidate.Viable = false; 7238 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7239 return; 7240 } 7241 } 7242 7243 // We won't go through a user-defined type conversion function to convert a 7244 // derived to base as such conversions are given Conversion Rank. They only 7245 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7246 QualType FromCanon 7247 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7248 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7249 if (FromCanon == ToCanon || 7250 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7251 Candidate.Viable = false; 7252 Candidate.FailureKind = ovl_fail_trivial_conversion; 7253 return; 7254 } 7255 7256 // To determine what the conversion from the result of calling the 7257 // conversion function to the type we're eventually trying to 7258 // convert to (ToType), we need to synthesize a call to the 7259 // conversion function and attempt copy initialization from it. This 7260 // makes sure that we get the right semantics with respect to 7261 // lvalues/rvalues and the type. Fortunately, we can allocate this 7262 // call on the stack and we don't need its arguments to be 7263 // well-formed. 7264 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7265 VK_LValue, From->getBeginLoc()); 7266 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7267 Context.getPointerType(Conversion->getType()), 7268 CK_FunctionToPointerDecay, 7269 &ConversionRef, VK_RValue); 7270 7271 QualType ConversionType = Conversion->getConversionType(); 7272 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7273 Candidate.Viable = false; 7274 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7275 return; 7276 } 7277 7278 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7279 7280 // Note that it is safe to allocate CallExpr on the stack here because 7281 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7282 // allocator). 7283 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7284 7285 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7286 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7287 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7288 7289 ImplicitConversionSequence ICS = 7290 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7291 /*SuppressUserConversions=*/true, 7292 /*InOverloadResolution=*/false, 7293 /*AllowObjCWritebackConversion=*/false); 7294 7295 switch (ICS.getKind()) { 7296 case ImplicitConversionSequence::StandardConversion: 7297 Candidate.FinalConversion = ICS.Standard; 7298 7299 // C++ [over.ics.user]p3: 7300 // If the user-defined conversion is specified by a specialization of a 7301 // conversion function template, the second standard conversion sequence 7302 // shall have exact match rank. 7303 if (Conversion->getPrimaryTemplate() && 7304 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7305 Candidate.Viable = false; 7306 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7307 return; 7308 } 7309 7310 // C++0x [dcl.init.ref]p5: 7311 // In the second case, if the reference is an rvalue reference and 7312 // the second standard conversion sequence of the user-defined 7313 // conversion sequence includes an lvalue-to-rvalue conversion, the 7314 // program is ill-formed. 7315 if (ToType->isRValueReferenceType() && 7316 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7317 Candidate.Viable = false; 7318 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7319 return; 7320 } 7321 break; 7322 7323 case ImplicitConversionSequence::BadConversion: 7324 Candidate.Viable = false; 7325 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7326 return; 7327 7328 default: 7329 llvm_unreachable( 7330 "Can only end up with a standard conversion sequence or failure"); 7331 } 7332 7333 if (EnableIfAttr *FailedAttr = 7334 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7335 Candidate.Viable = false; 7336 Candidate.FailureKind = ovl_fail_enable_if; 7337 Candidate.DeductionFailure.Data = FailedAttr; 7338 return; 7339 } 7340 7341 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7342 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7343 Candidate.Viable = false; 7344 Candidate.FailureKind = ovl_non_default_multiversion_function; 7345 } 7346 } 7347 7348 /// Adds a conversion function template specialization 7349 /// candidate to the overload set, using template argument deduction 7350 /// to deduce the template arguments of the conversion function 7351 /// template from the type that we are converting to (C++ 7352 /// [temp.deduct.conv]). 7353 void Sema::AddTemplateConversionCandidate( 7354 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7355 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7356 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7357 bool AllowExplicit, bool AllowResultConversion) { 7358 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7359 "Only conversion function templates permitted here"); 7360 7361 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7362 return; 7363 7364 // If the function template has a non-dependent explicit specification, 7365 // exclude it now if appropriate; we are not permitted to perform deduction 7366 // and substitution in this case. 7367 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7368 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7369 Candidate.FoundDecl = FoundDecl; 7370 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7371 Candidate.Viable = false; 7372 Candidate.FailureKind = ovl_fail_explicit; 7373 return; 7374 } 7375 7376 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7377 CXXConversionDecl *Specialization = nullptr; 7378 if (TemplateDeductionResult Result 7379 = DeduceTemplateArguments(FunctionTemplate, ToType, 7380 Specialization, Info)) { 7381 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7382 Candidate.FoundDecl = FoundDecl; 7383 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7384 Candidate.Viable = false; 7385 Candidate.FailureKind = ovl_fail_bad_deduction; 7386 Candidate.IsSurrogate = false; 7387 Candidate.IgnoreObjectArgument = false; 7388 Candidate.ExplicitCallArguments = 1; 7389 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7390 Info); 7391 return; 7392 } 7393 7394 // Add the conversion function template specialization produced by 7395 // template argument deduction as a candidate. 7396 assert(Specialization && "Missing function template specialization?"); 7397 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7398 CandidateSet, AllowObjCConversionOnExplicit, 7399 AllowExplicit, AllowResultConversion); 7400 } 7401 7402 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7403 /// converts the given @c Object to a function pointer via the 7404 /// conversion function @c Conversion, and then attempts to call it 7405 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7406 /// the type of function that we'll eventually be calling. 7407 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7408 DeclAccessPair FoundDecl, 7409 CXXRecordDecl *ActingContext, 7410 const FunctionProtoType *Proto, 7411 Expr *Object, 7412 ArrayRef<Expr *> Args, 7413 OverloadCandidateSet& CandidateSet) { 7414 if (!CandidateSet.isNewCandidate(Conversion)) 7415 return; 7416 7417 // Overload resolution is always an unevaluated context. 7418 EnterExpressionEvaluationContext Unevaluated( 7419 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7420 7421 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7422 Candidate.FoundDecl = FoundDecl; 7423 Candidate.Function = nullptr; 7424 Candidate.Surrogate = Conversion; 7425 Candidate.Viable = true; 7426 Candidate.IsSurrogate = true; 7427 Candidate.IgnoreObjectArgument = false; 7428 Candidate.ExplicitCallArguments = Args.size(); 7429 7430 // Determine the implicit conversion sequence for the implicit 7431 // object parameter. 7432 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7433 *this, CandidateSet.getLocation(), Object->getType(), 7434 Object->Classify(Context), Conversion, ActingContext); 7435 if (ObjectInit.isBad()) { 7436 Candidate.Viable = false; 7437 Candidate.FailureKind = ovl_fail_bad_conversion; 7438 Candidate.Conversions[0] = ObjectInit; 7439 return; 7440 } 7441 7442 // The first conversion is actually a user-defined conversion whose 7443 // first conversion is ObjectInit's standard conversion (which is 7444 // effectively a reference binding). Record it as such. 7445 Candidate.Conversions[0].setUserDefined(); 7446 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7447 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7448 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7449 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7450 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7451 Candidate.Conversions[0].UserDefined.After 7452 = Candidate.Conversions[0].UserDefined.Before; 7453 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7454 7455 // Find the 7456 unsigned NumParams = Proto->getNumParams(); 7457 7458 // (C++ 13.3.2p2): A candidate function having fewer than m 7459 // parameters is viable only if it has an ellipsis in its parameter 7460 // list (8.3.5). 7461 if (Args.size() > NumParams && !Proto->isVariadic()) { 7462 Candidate.Viable = false; 7463 Candidate.FailureKind = ovl_fail_too_many_arguments; 7464 return; 7465 } 7466 7467 // Function types don't have any default arguments, so just check if 7468 // we have enough arguments. 7469 if (Args.size() < NumParams) { 7470 // Not enough arguments. 7471 Candidate.Viable = false; 7472 Candidate.FailureKind = ovl_fail_too_few_arguments; 7473 return; 7474 } 7475 7476 // Determine the implicit conversion sequences for each of the 7477 // arguments. 7478 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7479 if (ArgIdx < NumParams) { 7480 // (C++ 13.3.2p3): for F to be a viable function, there shall 7481 // exist for each argument an implicit conversion sequence 7482 // (13.3.3.1) that converts that argument to the corresponding 7483 // parameter of F. 7484 QualType ParamType = Proto->getParamType(ArgIdx); 7485 Candidate.Conversions[ArgIdx + 1] 7486 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7487 /*SuppressUserConversions=*/false, 7488 /*InOverloadResolution=*/false, 7489 /*AllowObjCWritebackConversion=*/ 7490 getLangOpts().ObjCAutoRefCount); 7491 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7492 Candidate.Viable = false; 7493 Candidate.FailureKind = ovl_fail_bad_conversion; 7494 return; 7495 } 7496 } else { 7497 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7498 // argument for which there is no corresponding parameter is 7499 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7500 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7501 } 7502 } 7503 7504 if (EnableIfAttr *FailedAttr = 7505 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7506 Candidate.Viable = false; 7507 Candidate.FailureKind = ovl_fail_enable_if; 7508 Candidate.DeductionFailure.Data = FailedAttr; 7509 return; 7510 } 7511 } 7512 7513 /// Add all of the non-member operator function declarations in the given 7514 /// function set to the overload candidate set. 7515 void Sema::AddNonMemberOperatorCandidates( 7516 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7517 OverloadCandidateSet &CandidateSet, 7518 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7519 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7520 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7521 ArrayRef<Expr *> FunctionArgs = Args; 7522 7523 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7524 FunctionDecl *FD = 7525 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7526 7527 // Don't consider rewritten functions if we're not rewriting. 7528 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7529 continue; 7530 7531 assert(!isa<CXXMethodDecl>(FD) && 7532 "unqualified operator lookup found a member function"); 7533 7534 if (FunTmpl) { 7535 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7536 FunctionArgs, CandidateSet); 7537 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7538 AddTemplateOverloadCandidate( 7539 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7540 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7541 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7542 } else { 7543 if (ExplicitTemplateArgs) 7544 continue; 7545 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7546 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7547 AddOverloadCandidate(FD, F.getPair(), 7548 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7549 false, false, true, false, ADLCallKind::NotADL, 7550 None, OverloadCandidateParamOrder::Reversed); 7551 } 7552 } 7553 } 7554 7555 /// Add overload candidates for overloaded operators that are 7556 /// member functions. 7557 /// 7558 /// Add the overloaded operator candidates that are member functions 7559 /// for the operator Op that was used in an operator expression such 7560 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7561 /// CandidateSet will store the added overload candidates. (C++ 7562 /// [over.match.oper]). 7563 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7564 SourceLocation OpLoc, 7565 ArrayRef<Expr *> Args, 7566 OverloadCandidateSet &CandidateSet, 7567 OverloadCandidateParamOrder PO) { 7568 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7569 7570 // C++ [over.match.oper]p3: 7571 // For a unary operator @ with an operand of a type whose 7572 // cv-unqualified version is T1, and for a binary operator @ with 7573 // a left operand of a type whose cv-unqualified version is T1 and 7574 // a right operand of a type whose cv-unqualified version is T2, 7575 // three sets of candidate functions, designated member 7576 // candidates, non-member candidates and built-in candidates, are 7577 // constructed as follows: 7578 QualType T1 = Args[0]->getType(); 7579 7580 // -- If T1 is a complete class type or a class currently being 7581 // defined, the set of member candidates is the result of the 7582 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7583 // the set of member candidates is empty. 7584 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7585 // Complete the type if it can be completed. 7586 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7587 return; 7588 // If the type is neither complete nor being defined, bail out now. 7589 if (!T1Rec->getDecl()->getDefinition()) 7590 return; 7591 7592 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7593 LookupQualifiedName(Operators, T1Rec->getDecl()); 7594 Operators.suppressDiagnostics(); 7595 7596 for (LookupResult::iterator Oper = Operators.begin(), 7597 OperEnd = Operators.end(); 7598 Oper != OperEnd; 7599 ++Oper) 7600 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7601 Args[0]->Classify(Context), Args.slice(1), 7602 CandidateSet, /*SuppressUserConversion=*/false, PO); 7603 } 7604 } 7605 7606 /// AddBuiltinCandidate - Add a candidate for a built-in 7607 /// operator. ResultTy and ParamTys are the result and parameter types 7608 /// of the built-in candidate, respectively. Args and NumArgs are the 7609 /// arguments being passed to the candidate. IsAssignmentOperator 7610 /// should be true when this built-in candidate is an assignment 7611 /// operator. NumContextualBoolArguments is the number of arguments 7612 /// (at the beginning of the argument list) that will be contextually 7613 /// converted to bool. 7614 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7615 OverloadCandidateSet& CandidateSet, 7616 bool IsAssignmentOperator, 7617 unsigned NumContextualBoolArguments) { 7618 // Overload resolution is always an unevaluated context. 7619 EnterExpressionEvaluationContext Unevaluated( 7620 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7621 7622 // Add this candidate 7623 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7624 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7625 Candidate.Function = nullptr; 7626 Candidate.IsSurrogate = false; 7627 Candidate.IgnoreObjectArgument = false; 7628 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7629 7630 // Determine the implicit conversion sequences for each of the 7631 // arguments. 7632 Candidate.Viable = true; 7633 Candidate.ExplicitCallArguments = Args.size(); 7634 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7635 // C++ [over.match.oper]p4: 7636 // For the built-in assignment operators, conversions of the 7637 // left operand are restricted as follows: 7638 // -- no temporaries are introduced to hold the left operand, and 7639 // -- no user-defined conversions are applied to the left 7640 // operand to achieve a type match with the left-most 7641 // parameter of a built-in candidate. 7642 // 7643 // We block these conversions by turning off user-defined 7644 // conversions, since that is the only way that initialization of 7645 // a reference to a non-class type can occur from something that 7646 // is not of the same type. 7647 if (ArgIdx < NumContextualBoolArguments) { 7648 assert(ParamTys[ArgIdx] == Context.BoolTy && 7649 "Contextual conversion to bool requires bool type"); 7650 Candidate.Conversions[ArgIdx] 7651 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7652 } else { 7653 Candidate.Conversions[ArgIdx] 7654 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7655 ArgIdx == 0 && IsAssignmentOperator, 7656 /*InOverloadResolution=*/false, 7657 /*AllowObjCWritebackConversion=*/ 7658 getLangOpts().ObjCAutoRefCount); 7659 } 7660 if (Candidate.Conversions[ArgIdx].isBad()) { 7661 Candidate.Viable = false; 7662 Candidate.FailureKind = ovl_fail_bad_conversion; 7663 break; 7664 } 7665 } 7666 } 7667 7668 namespace { 7669 7670 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7671 /// candidate operator functions for built-in operators (C++ 7672 /// [over.built]). The types are separated into pointer types and 7673 /// enumeration types. 7674 class BuiltinCandidateTypeSet { 7675 /// TypeSet - A set of types. 7676 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7677 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7678 7679 /// PointerTypes - The set of pointer types that will be used in the 7680 /// built-in candidates. 7681 TypeSet PointerTypes; 7682 7683 /// MemberPointerTypes - The set of member pointer types that will be 7684 /// used in the built-in candidates. 7685 TypeSet MemberPointerTypes; 7686 7687 /// EnumerationTypes - The set of enumeration types that will be 7688 /// used in the built-in candidates. 7689 TypeSet EnumerationTypes; 7690 7691 /// The set of vector types that will be used in the built-in 7692 /// candidates. 7693 TypeSet VectorTypes; 7694 7695 /// The set of matrix types that will be used in the built-in 7696 /// candidates. 7697 TypeSet MatrixTypes; 7698 7699 /// A flag indicating non-record types are viable candidates 7700 bool HasNonRecordTypes; 7701 7702 /// A flag indicating whether either arithmetic or enumeration types 7703 /// were present in the candidate set. 7704 bool HasArithmeticOrEnumeralTypes; 7705 7706 /// A flag indicating whether the nullptr type was present in the 7707 /// candidate set. 7708 bool HasNullPtrType; 7709 7710 /// Sema - The semantic analysis instance where we are building the 7711 /// candidate type set. 7712 Sema &SemaRef; 7713 7714 /// Context - The AST context in which we will build the type sets. 7715 ASTContext &Context; 7716 7717 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7718 const Qualifiers &VisibleQuals); 7719 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7720 7721 public: 7722 /// iterator - Iterates through the types that are part of the set. 7723 typedef TypeSet::iterator iterator; 7724 7725 BuiltinCandidateTypeSet(Sema &SemaRef) 7726 : HasNonRecordTypes(false), 7727 HasArithmeticOrEnumeralTypes(false), 7728 HasNullPtrType(false), 7729 SemaRef(SemaRef), 7730 Context(SemaRef.Context) { } 7731 7732 void AddTypesConvertedFrom(QualType Ty, 7733 SourceLocation Loc, 7734 bool AllowUserConversions, 7735 bool AllowExplicitConversions, 7736 const Qualifiers &VisibleTypeConversionsQuals); 7737 7738 /// pointer_begin - First pointer type found; 7739 iterator pointer_begin() { return PointerTypes.begin(); } 7740 7741 /// pointer_end - Past the last pointer type found; 7742 iterator pointer_end() { return PointerTypes.end(); } 7743 7744 /// member_pointer_begin - First member pointer type found; 7745 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7746 7747 /// member_pointer_end - Past the last member pointer type found; 7748 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7749 7750 /// enumeration_begin - First enumeration type found; 7751 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7752 7753 /// enumeration_end - Past the last enumeration type found; 7754 iterator enumeration_end() { return EnumerationTypes.end(); } 7755 7756 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7757 7758 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7759 7760 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7761 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7762 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7763 bool hasNullPtrType() const { return HasNullPtrType; } 7764 }; 7765 7766 } // end anonymous namespace 7767 7768 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7769 /// the set of pointer types along with any more-qualified variants of 7770 /// that type. For example, if @p Ty is "int const *", this routine 7771 /// will add "int const *", "int const volatile *", "int const 7772 /// restrict *", and "int const volatile restrict *" to the set of 7773 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7774 /// false otherwise. 7775 /// 7776 /// FIXME: what to do about extended qualifiers? 7777 bool 7778 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7779 const Qualifiers &VisibleQuals) { 7780 7781 // Insert this type. 7782 if (!PointerTypes.insert(Ty)) 7783 return false; 7784 7785 QualType PointeeTy; 7786 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7787 bool buildObjCPtr = false; 7788 if (!PointerTy) { 7789 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7790 PointeeTy = PTy->getPointeeType(); 7791 buildObjCPtr = true; 7792 } else { 7793 PointeeTy = PointerTy->getPointeeType(); 7794 } 7795 7796 // Don't add qualified variants of arrays. For one, they're not allowed 7797 // (the qualifier would sink to the element type), and for another, the 7798 // only overload situation where it matters is subscript or pointer +- int, 7799 // and those shouldn't have qualifier variants anyway. 7800 if (PointeeTy->isArrayType()) 7801 return true; 7802 7803 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7804 bool hasVolatile = VisibleQuals.hasVolatile(); 7805 bool hasRestrict = VisibleQuals.hasRestrict(); 7806 7807 // Iterate through all strict supersets of BaseCVR. 7808 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7809 if ((CVR | BaseCVR) != CVR) continue; 7810 // Skip over volatile if no volatile found anywhere in the types. 7811 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7812 7813 // Skip over restrict if no restrict found anywhere in the types, or if 7814 // the type cannot be restrict-qualified. 7815 if ((CVR & Qualifiers::Restrict) && 7816 (!hasRestrict || 7817 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7818 continue; 7819 7820 // Build qualified pointee type. 7821 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7822 7823 // Build qualified pointer type. 7824 QualType QPointerTy; 7825 if (!buildObjCPtr) 7826 QPointerTy = Context.getPointerType(QPointeeTy); 7827 else 7828 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7829 7830 // Insert qualified pointer type. 7831 PointerTypes.insert(QPointerTy); 7832 } 7833 7834 return true; 7835 } 7836 7837 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7838 /// to the set of pointer types along with any more-qualified variants of 7839 /// that type. For example, if @p Ty is "int const *", this routine 7840 /// will add "int const *", "int const volatile *", "int const 7841 /// restrict *", and "int const volatile restrict *" to the set of 7842 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7843 /// false otherwise. 7844 /// 7845 /// FIXME: what to do about extended qualifiers? 7846 bool 7847 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7848 QualType Ty) { 7849 // Insert this type. 7850 if (!MemberPointerTypes.insert(Ty)) 7851 return false; 7852 7853 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7854 assert(PointerTy && "type was not a member pointer type!"); 7855 7856 QualType PointeeTy = PointerTy->getPointeeType(); 7857 // Don't add qualified variants of arrays. For one, they're not allowed 7858 // (the qualifier would sink to the element type), and for another, the 7859 // only overload situation where it matters is subscript or pointer +- int, 7860 // and those shouldn't have qualifier variants anyway. 7861 if (PointeeTy->isArrayType()) 7862 return true; 7863 const Type *ClassTy = PointerTy->getClass(); 7864 7865 // Iterate through all strict supersets of the pointee type's CVR 7866 // qualifiers. 7867 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7868 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7869 if ((CVR | BaseCVR) != CVR) continue; 7870 7871 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7872 MemberPointerTypes.insert( 7873 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7874 } 7875 7876 return true; 7877 } 7878 7879 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7880 /// Ty can be implicit converted to the given set of @p Types. We're 7881 /// primarily interested in pointer types and enumeration types. We also 7882 /// take member pointer types, for the conditional operator. 7883 /// AllowUserConversions is true if we should look at the conversion 7884 /// functions of a class type, and AllowExplicitConversions if we 7885 /// should also include the explicit conversion functions of a class 7886 /// type. 7887 void 7888 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7889 SourceLocation Loc, 7890 bool AllowUserConversions, 7891 bool AllowExplicitConversions, 7892 const Qualifiers &VisibleQuals) { 7893 // Only deal with canonical types. 7894 Ty = Context.getCanonicalType(Ty); 7895 7896 // Look through reference types; they aren't part of the type of an 7897 // expression for the purposes of conversions. 7898 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7899 Ty = RefTy->getPointeeType(); 7900 7901 // If we're dealing with an array type, decay to the pointer. 7902 if (Ty->isArrayType()) 7903 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7904 7905 // Otherwise, we don't care about qualifiers on the type. 7906 Ty = Ty.getLocalUnqualifiedType(); 7907 7908 // Flag if we ever add a non-record type. 7909 const RecordType *TyRec = Ty->getAs<RecordType>(); 7910 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7911 7912 // Flag if we encounter an arithmetic type. 7913 HasArithmeticOrEnumeralTypes = 7914 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7915 7916 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7917 PointerTypes.insert(Ty); 7918 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7919 // Insert our type, and its more-qualified variants, into the set 7920 // of types. 7921 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7922 return; 7923 } else if (Ty->isMemberPointerType()) { 7924 // Member pointers are far easier, since the pointee can't be converted. 7925 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7926 return; 7927 } else if (Ty->isEnumeralType()) { 7928 HasArithmeticOrEnumeralTypes = true; 7929 EnumerationTypes.insert(Ty); 7930 } else if (Ty->isVectorType()) { 7931 // We treat vector types as arithmetic types in many contexts as an 7932 // extension. 7933 HasArithmeticOrEnumeralTypes = true; 7934 VectorTypes.insert(Ty); 7935 } else if (Ty->isMatrixType()) { 7936 // Similar to vector types, we treat vector types as arithmetic types in 7937 // many contexts as an extension. 7938 HasArithmeticOrEnumeralTypes = true; 7939 MatrixTypes.insert(Ty); 7940 } else if (Ty->isNullPtrType()) { 7941 HasNullPtrType = true; 7942 } else if (AllowUserConversions && TyRec) { 7943 // No conversion functions in incomplete types. 7944 if (!SemaRef.isCompleteType(Loc, Ty)) 7945 return; 7946 7947 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7948 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7949 if (isa<UsingShadowDecl>(D)) 7950 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7951 7952 // Skip conversion function templates; they don't tell us anything 7953 // about which builtin types we can convert to. 7954 if (isa<FunctionTemplateDecl>(D)) 7955 continue; 7956 7957 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7958 if (AllowExplicitConversions || !Conv->isExplicit()) { 7959 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7960 VisibleQuals); 7961 } 7962 } 7963 } 7964 } 7965 /// Helper function for adjusting address spaces for the pointer or reference 7966 /// operands of builtin operators depending on the argument. 7967 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7968 Expr *Arg) { 7969 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7970 } 7971 7972 /// Helper function for AddBuiltinOperatorCandidates() that adds 7973 /// the volatile- and non-volatile-qualified assignment operators for the 7974 /// given type to the candidate set. 7975 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7976 QualType T, 7977 ArrayRef<Expr *> Args, 7978 OverloadCandidateSet &CandidateSet) { 7979 QualType ParamTypes[2]; 7980 7981 // T& operator=(T&, T) 7982 ParamTypes[0] = S.Context.getLValueReferenceType( 7983 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7984 ParamTypes[1] = T; 7985 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7986 /*IsAssignmentOperator=*/true); 7987 7988 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7989 // volatile T& operator=(volatile T&, T) 7990 ParamTypes[0] = S.Context.getLValueReferenceType( 7991 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7992 Args[0])); 7993 ParamTypes[1] = T; 7994 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7995 /*IsAssignmentOperator=*/true); 7996 } 7997 } 7998 7999 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8000 /// if any, found in visible type conversion functions found in ArgExpr's type. 8001 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8002 Qualifiers VRQuals; 8003 const RecordType *TyRec; 8004 if (const MemberPointerType *RHSMPType = 8005 ArgExpr->getType()->getAs<MemberPointerType>()) 8006 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8007 else 8008 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8009 if (!TyRec) { 8010 // Just to be safe, assume the worst case. 8011 VRQuals.addVolatile(); 8012 VRQuals.addRestrict(); 8013 return VRQuals; 8014 } 8015 8016 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8017 if (!ClassDecl->hasDefinition()) 8018 return VRQuals; 8019 8020 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8021 if (isa<UsingShadowDecl>(D)) 8022 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8023 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8024 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8025 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8026 CanTy = ResTypeRef->getPointeeType(); 8027 // Need to go down the pointer/mempointer chain and add qualifiers 8028 // as see them. 8029 bool done = false; 8030 while (!done) { 8031 if (CanTy.isRestrictQualified()) 8032 VRQuals.addRestrict(); 8033 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8034 CanTy = ResTypePtr->getPointeeType(); 8035 else if (const MemberPointerType *ResTypeMPtr = 8036 CanTy->getAs<MemberPointerType>()) 8037 CanTy = ResTypeMPtr->getPointeeType(); 8038 else 8039 done = true; 8040 if (CanTy.isVolatileQualified()) 8041 VRQuals.addVolatile(); 8042 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8043 return VRQuals; 8044 } 8045 } 8046 } 8047 return VRQuals; 8048 } 8049 8050 namespace { 8051 8052 /// Helper class to manage the addition of builtin operator overload 8053 /// candidates. It provides shared state and utility methods used throughout 8054 /// the process, as well as a helper method to add each group of builtin 8055 /// operator overloads from the standard to a candidate set. 8056 class BuiltinOperatorOverloadBuilder { 8057 // Common instance state available to all overload candidate addition methods. 8058 Sema &S; 8059 ArrayRef<Expr *> Args; 8060 Qualifiers VisibleTypeConversionsQuals; 8061 bool HasArithmeticOrEnumeralCandidateType; 8062 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8063 OverloadCandidateSet &CandidateSet; 8064 8065 static constexpr int ArithmeticTypesCap = 24; 8066 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8067 8068 // Define some indices used to iterate over the arithmetic types in 8069 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8070 // types are that preserved by promotion (C++ [over.built]p2). 8071 unsigned FirstIntegralType, 8072 LastIntegralType; 8073 unsigned FirstPromotedIntegralType, 8074 LastPromotedIntegralType; 8075 unsigned FirstPromotedArithmeticType, 8076 LastPromotedArithmeticType; 8077 unsigned NumArithmeticTypes; 8078 8079 void InitArithmeticTypes() { 8080 // Start of promoted types. 8081 FirstPromotedArithmeticType = 0; 8082 ArithmeticTypes.push_back(S.Context.FloatTy); 8083 ArithmeticTypes.push_back(S.Context.DoubleTy); 8084 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8085 if (S.Context.getTargetInfo().hasFloat128Type()) 8086 ArithmeticTypes.push_back(S.Context.Float128Ty); 8087 8088 // Start of integral types. 8089 FirstIntegralType = ArithmeticTypes.size(); 8090 FirstPromotedIntegralType = ArithmeticTypes.size(); 8091 ArithmeticTypes.push_back(S.Context.IntTy); 8092 ArithmeticTypes.push_back(S.Context.LongTy); 8093 ArithmeticTypes.push_back(S.Context.LongLongTy); 8094 if (S.Context.getTargetInfo().hasInt128Type()) 8095 ArithmeticTypes.push_back(S.Context.Int128Ty); 8096 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8097 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8098 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8099 if (S.Context.getTargetInfo().hasInt128Type()) 8100 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8101 LastPromotedIntegralType = ArithmeticTypes.size(); 8102 LastPromotedArithmeticType = ArithmeticTypes.size(); 8103 // End of promoted types. 8104 8105 ArithmeticTypes.push_back(S.Context.BoolTy); 8106 ArithmeticTypes.push_back(S.Context.CharTy); 8107 ArithmeticTypes.push_back(S.Context.WCharTy); 8108 if (S.Context.getLangOpts().Char8) 8109 ArithmeticTypes.push_back(S.Context.Char8Ty); 8110 ArithmeticTypes.push_back(S.Context.Char16Ty); 8111 ArithmeticTypes.push_back(S.Context.Char32Ty); 8112 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8113 ArithmeticTypes.push_back(S.Context.ShortTy); 8114 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8115 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8116 LastIntegralType = ArithmeticTypes.size(); 8117 NumArithmeticTypes = ArithmeticTypes.size(); 8118 // End of integral types. 8119 // FIXME: What about complex? What about half? 8120 8121 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8122 "Enough inline storage for all arithmetic types."); 8123 } 8124 8125 /// Helper method to factor out the common pattern of adding overloads 8126 /// for '++' and '--' builtin operators. 8127 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8128 bool HasVolatile, 8129 bool HasRestrict) { 8130 QualType ParamTypes[2] = { 8131 S.Context.getLValueReferenceType(CandidateTy), 8132 S.Context.IntTy 8133 }; 8134 8135 // Non-volatile version. 8136 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8137 8138 // Use a heuristic to reduce number of builtin candidates in the set: 8139 // add volatile version only if there are conversions to a volatile type. 8140 if (HasVolatile) { 8141 ParamTypes[0] = 8142 S.Context.getLValueReferenceType( 8143 S.Context.getVolatileType(CandidateTy)); 8144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8145 } 8146 8147 // Add restrict version only if there are conversions to a restrict type 8148 // and our candidate type is a non-restrict-qualified pointer. 8149 if (HasRestrict && CandidateTy->isAnyPointerType() && 8150 !CandidateTy.isRestrictQualified()) { 8151 ParamTypes[0] 8152 = S.Context.getLValueReferenceType( 8153 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8154 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8155 8156 if (HasVolatile) { 8157 ParamTypes[0] 8158 = S.Context.getLValueReferenceType( 8159 S.Context.getCVRQualifiedType(CandidateTy, 8160 (Qualifiers::Volatile | 8161 Qualifiers::Restrict))); 8162 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8163 } 8164 } 8165 8166 } 8167 8168 /// Helper to add an overload candidate for a binary builtin with types \p L 8169 /// and \p R. 8170 void AddCandidate(QualType L, QualType R) { 8171 QualType LandR[2] = {L, R}; 8172 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8173 } 8174 8175 public: 8176 BuiltinOperatorOverloadBuilder( 8177 Sema &S, ArrayRef<Expr *> Args, 8178 Qualifiers VisibleTypeConversionsQuals, 8179 bool HasArithmeticOrEnumeralCandidateType, 8180 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8181 OverloadCandidateSet &CandidateSet) 8182 : S(S), Args(Args), 8183 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8184 HasArithmeticOrEnumeralCandidateType( 8185 HasArithmeticOrEnumeralCandidateType), 8186 CandidateTypes(CandidateTypes), 8187 CandidateSet(CandidateSet) { 8188 8189 InitArithmeticTypes(); 8190 } 8191 8192 // Increment is deprecated for bool since C++17. 8193 // 8194 // C++ [over.built]p3: 8195 // 8196 // For every pair (T, VQ), where T is an arithmetic type other 8197 // than bool, and VQ is either volatile or empty, there exist 8198 // candidate operator functions of the form 8199 // 8200 // VQ T& operator++(VQ T&); 8201 // T operator++(VQ T&, int); 8202 // 8203 // C++ [over.built]p4: 8204 // 8205 // For every pair (T, VQ), where T is an arithmetic type other 8206 // than bool, and VQ is either volatile or empty, there exist 8207 // candidate operator functions of the form 8208 // 8209 // VQ T& operator--(VQ T&); 8210 // T operator--(VQ T&, int); 8211 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8212 if (!HasArithmeticOrEnumeralCandidateType) 8213 return; 8214 8215 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8216 const auto TypeOfT = ArithmeticTypes[Arith]; 8217 if (TypeOfT == S.Context.BoolTy) { 8218 if (Op == OO_MinusMinus) 8219 continue; 8220 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8221 continue; 8222 } 8223 addPlusPlusMinusMinusStyleOverloads( 8224 TypeOfT, 8225 VisibleTypeConversionsQuals.hasVolatile(), 8226 VisibleTypeConversionsQuals.hasRestrict()); 8227 } 8228 } 8229 8230 // C++ [over.built]p5: 8231 // 8232 // For every pair (T, VQ), where T is a cv-qualified or 8233 // cv-unqualified object type, and VQ is either volatile or 8234 // empty, there exist candidate operator functions of the form 8235 // 8236 // T*VQ& operator++(T*VQ&); 8237 // T*VQ& operator--(T*VQ&); 8238 // T* operator++(T*VQ&, int); 8239 // T* operator--(T*VQ&, int); 8240 void addPlusPlusMinusMinusPointerOverloads() { 8241 for (BuiltinCandidateTypeSet::iterator 8242 Ptr = CandidateTypes[0].pointer_begin(), 8243 PtrEnd = CandidateTypes[0].pointer_end(); 8244 Ptr != PtrEnd; ++Ptr) { 8245 // Skip pointer types that aren't pointers to object types. 8246 if (!(*Ptr)->getPointeeType()->isObjectType()) 8247 continue; 8248 8249 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8250 (!(*Ptr).isVolatileQualified() && 8251 VisibleTypeConversionsQuals.hasVolatile()), 8252 (!(*Ptr).isRestrictQualified() && 8253 VisibleTypeConversionsQuals.hasRestrict())); 8254 } 8255 } 8256 8257 // C++ [over.built]p6: 8258 // For every cv-qualified or cv-unqualified object type T, there 8259 // exist candidate operator functions of the form 8260 // 8261 // T& operator*(T*); 8262 // 8263 // C++ [over.built]p7: 8264 // For every function type T that does not have cv-qualifiers or a 8265 // ref-qualifier, there exist candidate operator functions of the form 8266 // T& operator*(T*); 8267 void addUnaryStarPointerOverloads() { 8268 for (BuiltinCandidateTypeSet::iterator 8269 Ptr = CandidateTypes[0].pointer_begin(), 8270 PtrEnd = CandidateTypes[0].pointer_end(); 8271 Ptr != PtrEnd; ++Ptr) { 8272 QualType ParamTy = *Ptr; 8273 QualType PointeeTy = ParamTy->getPointeeType(); 8274 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8275 continue; 8276 8277 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8278 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8279 continue; 8280 8281 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8282 } 8283 } 8284 8285 // C++ [over.built]p9: 8286 // For every promoted arithmetic type T, there exist candidate 8287 // operator functions of the form 8288 // 8289 // T operator+(T); 8290 // T operator-(T); 8291 void addUnaryPlusOrMinusArithmeticOverloads() { 8292 if (!HasArithmeticOrEnumeralCandidateType) 8293 return; 8294 8295 for (unsigned Arith = FirstPromotedArithmeticType; 8296 Arith < LastPromotedArithmeticType; ++Arith) { 8297 QualType ArithTy = ArithmeticTypes[Arith]; 8298 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8299 } 8300 8301 // Extension: We also add these operators for vector types. 8302 for (QualType VecTy : CandidateTypes[0].vector_types()) 8303 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8304 } 8305 8306 // C++ [over.built]p8: 8307 // For every type T, there exist candidate operator functions of 8308 // the form 8309 // 8310 // T* operator+(T*); 8311 void addUnaryPlusPointerOverloads() { 8312 for (BuiltinCandidateTypeSet::iterator 8313 Ptr = CandidateTypes[0].pointer_begin(), 8314 PtrEnd = CandidateTypes[0].pointer_end(); 8315 Ptr != PtrEnd; ++Ptr) { 8316 QualType ParamTy = *Ptr; 8317 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8318 } 8319 } 8320 8321 // C++ [over.built]p10: 8322 // For every promoted integral type T, there exist candidate 8323 // operator functions of the form 8324 // 8325 // T operator~(T); 8326 void addUnaryTildePromotedIntegralOverloads() { 8327 if (!HasArithmeticOrEnumeralCandidateType) 8328 return; 8329 8330 for (unsigned Int = FirstPromotedIntegralType; 8331 Int < LastPromotedIntegralType; ++Int) { 8332 QualType IntTy = ArithmeticTypes[Int]; 8333 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8334 } 8335 8336 // Extension: We also add this operator for vector types. 8337 for (QualType VecTy : CandidateTypes[0].vector_types()) 8338 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8339 } 8340 8341 // C++ [over.match.oper]p16: 8342 // For every pointer to member type T or type std::nullptr_t, there 8343 // exist candidate operator functions of the form 8344 // 8345 // bool operator==(T,T); 8346 // bool operator!=(T,T); 8347 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8348 /// Set of (canonical) types that we've already handled. 8349 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8350 8351 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8352 for (BuiltinCandidateTypeSet::iterator 8353 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8354 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8355 MemPtr != MemPtrEnd; 8356 ++MemPtr) { 8357 // Don't add the same builtin candidate twice. 8358 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8359 continue; 8360 8361 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8362 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8363 } 8364 8365 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8366 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8367 if (AddedTypes.insert(NullPtrTy).second) { 8368 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8369 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8370 } 8371 } 8372 } 8373 } 8374 8375 // C++ [over.built]p15: 8376 // 8377 // For every T, where T is an enumeration type or a pointer type, 8378 // there exist candidate operator functions of the form 8379 // 8380 // bool operator<(T, T); 8381 // bool operator>(T, T); 8382 // bool operator<=(T, T); 8383 // bool operator>=(T, T); 8384 // bool operator==(T, T); 8385 // bool operator!=(T, T); 8386 // R operator<=>(T, T) 8387 void addGenericBinaryPointerOrEnumeralOverloads() { 8388 // C++ [over.match.oper]p3: 8389 // [...]the built-in candidates include all of the candidate operator 8390 // functions defined in 13.6 that, compared to the given operator, [...] 8391 // do not have the same parameter-type-list as any non-template non-member 8392 // candidate. 8393 // 8394 // Note that in practice, this only affects enumeration types because there 8395 // aren't any built-in candidates of record type, and a user-defined operator 8396 // must have an operand of record or enumeration type. Also, the only other 8397 // overloaded operator with enumeration arguments, operator=, 8398 // cannot be overloaded for enumeration types, so this is the only place 8399 // where we must suppress candidates like this. 8400 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8401 UserDefinedBinaryOperators; 8402 8403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8404 if (CandidateTypes[ArgIdx].enumeration_begin() != 8405 CandidateTypes[ArgIdx].enumeration_end()) { 8406 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8407 CEnd = CandidateSet.end(); 8408 C != CEnd; ++C) { 8409 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8410 continue; 8411 8412 if (C->Function->isFunctionTemplateSpecialization()) 8413 continue; 8414 8415 // We interpret "same parameter-type-list" as applying to the 8416 // "synthesized candidate, with the order of the two parameters 8417 // reversed", not to the original function. 8418 bool Reversed = C->isReversed(); 8419 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8420 ->getType() 8421 .getUnqualifiedType(); 8422 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8423 ->getType() 8424 .getUnqualifiedType(); 8425 8426 // Skip if either parameter isn't of enumeral type. 8427 if (!FirstParamType->isEnumeralType() || 8428 !SecondParamType->isEnumeralType()) 8429 continue; 8430 8431 // Add this operator to the set of known user-defined operators. 8432 UserDefinedBinaryOperators.insert( 8433 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8434 S.Context.getCanonicalType(SecondParamType))); 8435 } 8436 } 8437 } 8438 8439 /// Set of (canonical) types that we've already handled. 8440 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8441 8442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8443 for (BuiltinCandidateTypeSet::iterator 8444 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8445 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8446 Ptr != PtrEnd; ++Ptr) { 8447 // Don't add the same builtin candidate twice. 8448 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8449 continue; 8450 8451 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8452 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8453 } 8454 for (BuiltinCandidateTypeSet::iterator 8455 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8456 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8457 Enum != EnumEnd; ++Enum) { 8458 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8459 8460 // Don't add the same builtin candidate twice, or if a user defined 8461 // candidate exists. 8462 if (!AddedTypes.insert(CanonType).second || 8463 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8464 CanonType))) 8465 continue; 8466 QualType ParamTypes[2] = { *Enum, *Enum }; 8467 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8468 } 8469 } 8470 } 8471 8472 // C++ [over.built]p13: 8473 // 8474 // For every cv-qualified or cv-unqualified object type T 8475 // there exist candidate operator functions of the form 8476 // 8477 // T* operator+(T*, ptrdiff_t); 8478 // T& operator[](T*, ptrdiff_t); [BELOW] 8479 // T* operator-(T*, ptrdiff_t); 8480 // T* operator+(ptrdiff_t, T*); 8481 // T& operator[](ptrdiff_t, T*); [BELOW] 8482 // 8483 // C++ [over.built]p14: 8484 // 8485 // For every T, where T is a pointer to object type, there 8486 // exist candidate operator functions of the form 8487 // 8488 // ptrdiff_t operator-(T, T); 8489 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8490 /// Set of (canonical) types that we've already handled. 8491 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8492 8493 for (int Arg = 0; Arg < 2; ++Arg) { 8494 QualType AsymmetricParamTypes[2] = { 8495 S.Context.getPointerDiffType(), 8496 S.Context.getPointerDiffType(), 8497 }; 8498 for (BuiltinCandidateTypeSet::iterator 8499 Ptr = CandidateTypes[Arg].pointer_begin(), 8500 PtrEnd = CandidateTypes[Arg].pointer_end(); 8501 Ptr != PtrEnd; ++Ptr) { 8502 QualType PointeeTy = (*Ptr)->getPointeeType(); 8503 if (!PointeeTy->isObjectType()) 8504 continue; 8505 8506 AsymmetricParamTypes[Arg] = *Ptr; 8507 if (Arg == 0 || Op == OO_Plus) { 8508 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8509 // T* operator+(ptrdiff_t, T*); 8510 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8511 } 8512 if (Op == OO_Minus) { 8513 // ptrdiff_t operator-(T, T); 8514 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8515 continue; 8516 8517 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8518 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8519 } 8520 } 8521 } 8522 } 8523 8524 // C++ [over.built]p12: 8525 // 8526 // For every pair of promoted arithmetic types L and R, there 8527 // exist candidate operator functions of the form 8528 // 8529 // LR operator*(L, R); 8530 // LR operator/(L, R); 8531 // LR operator+(L, R); 8532 // LR operator-(L, R); 8533 // bool operator<(L, R); 8534 // bool operator>(L, R); 8535 // bool operator<=(L, R); 8536 // bool operator>=(L, R); 8537 // bool operator==(L, R); 8538 // bool operator!=(L, R); 8539 // 8540 // where LR is the result of the usual arithmetic conversions 8541 // between types L and R. 8542 // 8543 // C++ [over.built]p24: 8544 // 8545 // For every pair of promoted arithmetic types L and R, there exist 8546 // candidate operator functions of the form 8547 // 8548 // LR operator?(bool, L, R); 8549 // 8550 // where LR is the result of the usual arithmetic conversions 8551 // between types L and R. 8552 // Our candidates ignore the first parameter. 8553 void addGenericBinaryArithmeticOverloads() { 8554 if (!HasArithmeticOrEnumeralCandidateType) 8555 return; 8556 8557 for (unsigned Left = FirstPromotedArithmeticType; 8558 Left < LastPromotedArithmeticType; ++Left) { 8559 for (unsigned Right = FirstPromotedArithmeticType; 8560 Right < LastPromotedArithmeticType; ++Right) { 8561 QualType LandR[2] = { ArithmeticTypes[Left], 8562 ArithmeticTypes[Right] }; 8563 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8564 } 8565 } 8566 8567 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8568 // conditional operator for vector types. 8569 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8570 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8571 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8572 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8573 } 8574 } 8575 8576 /// Add binary operator overloads for each candidate matrix type M1, M2: 8577 /// * (M1, M1) -> M1 8578 /// * (M1, M1.getElementType()) -> M1 8579 /// * (M2.getElementType(), M2) -> M2 8580 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8581 void addMatrixBinaryArithmeticOverloads() { 8582 if (!HasArithmeticOrEnumeralCandidateType) 8583 return; 8584 8585 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8586 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8587 AddCandidate(M1, M1); 8588 } 8589 8590 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8591 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8592 if (!CandidateTypes[0].containsMatrixType(M2)) 8593 AddCandidate(M2, M2); 8594 } 8595 } 8596 8597 // C++2a [over.built]p14: 8598 // 8599 // For every integral type T there exists a candidate operator function 8600 // of the form 8601 // 8602 // std::strong_ordering operator<=>(T, T) 8603 // 8604 // C++2a [over.built]p15: 8605 // 8606 // For every pair of floating-point types L and R, there exists a candidate 8607 // operator function of the form 8608 // 8609 // std::partial_ordering operator<=>(L, R); 8610 // 8611 // FIXME: The current specification for integral types doesn't play nice with 8612 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8613 // comparisons. Under the current spec this can lead to ambiguity during 8614 // overload resolution. For example: 8615 // 8616 // enum A : int {a}; 8617 // auto x = (a <=> (long)42); 8618 // 8619 // error: call is ambiguous for arguments 'A' and 'long'. 8620 // note: candidate operator<=>(int, int) 8621 // note: candidate operator<=>(long, long) 8622 // 8623 // To avoid this error, this function deviates from the specification and adds 8624 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8625 // arithmetic types (the same as the generic relational overloads). 8626 // 8627 // For now this function acts as a placeholder. 8628 void addThreeWayArithmeticOverloads() { 8629 addGenericBinaryArithmeticOverloads(); 8630 } 8631 8632 // C++ [over.built]p17: 8633 // 8634 // For every pair of promoted integral types L and R, there 8635 // exist candidate operator functions of the form 8636 // 8637 // LR operator%(L, R); 8638 // LR operator&(L, R); 8639 // LR operator^(L, R); 8640 // LR operator|(L, R); 8641 // L operator<<(L, R); 8642 // L operator>>(L, R); 8643 // 8644 // where LR is the result of the usual arithmetic conversions 8645 // between types L and R. 8646 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8647 if (!HasArithmeticOrEnumeralCandidateType) 8648 return; 8649 8650 for (unsigned Left = FirstPromotedIntegralType; 8651 Left < LastPromotedIntegralType; ++Left) { 8652 for (unsigned Right = FirstPromotedIntegralType; 8653 Right < LastPromotedIntegralType; ++Right) { 8654 QualType LandR[2] = { ArithmeticTypes[Left], 8655 ArithmeticTypes[Right] }; 8656 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8657 } 8658 } 8659 } 8660 8661 // C++ [over.built]p20: 8662 // 8663 // For every pair (T, VQ), where T is an enumeration or 8664 // pointer to member type and VQ is either volatile or 8665 // empty, there exist candidate operator functions of the form 8666 // 8667 // VQ T& operator=(VQ T&, T); 8668 void addAssignmentMemberPointerOrEnumeralOverloads() { 8669 /// Set of (canonical) types that we've already handled. 8670 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8671 8672 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8673 for (BuiltinCandidateTypeSet::iterator 8674 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8675 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8676 Enum != EnumEnd; ++Enum) { 8677 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8678 continue; 8679 8680 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8681 } 8682 8683 for (BuiltinCandidateTypeSet::iterator 8684 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8685 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8686 MemPtr != MemPtrEnd; ++MemPtr) { 8687 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8688 continue; 8689 8690 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8691 } 8692 } 8693 } 8694 8695 // C++ [over.built]p19: 8696 // 8697 // For every pair (T, VQ), where T is any type and VQ is either 8698 // volatile or empty, there exist candidate operator functions 8699 // of the form 8700 // 8701 // T*VQ& operator=(T*VQ&, T*); 8702 // 8703 // C++ [over.built]p21: 8704 // 8705 // For every pair (T, VQ), where T is a cv-qualified or 8706 // cv-unqualified object type and VQ is either volatile or 8707 // empty, there exist candidate operator functions of the form 8708 // 8709 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8710 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8711 void addAssignmentPointerOverloads(bool isEqualOp) { 8712 /// Set of (canonical) types that we've already handled. 8713 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8714 8715 for (BuiltinCandidateTypeSet::iterator 8716 Ptr = CandidateTypes[0].pointer_begin(), 8717 PtrEnd = CandidateTypes[0].pointer_end(); 8718 Ptr != PtrEnd; ++Ptr) { 8719 // If this is operator=, keep track of the builtin candidates we added. 8720 if (isEqualOp) 8721 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8722 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8723 continue; 8724 8725 // non-volatile version 8726 QualType ParamTypes[2] = { 8727 S.Context.getLValueReferenceType(*Ptr), 8728 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8729 }; 8730 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8731 /*IsAssignmentOperator=*/ isEqualOp); 8732 8733 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8734 VisibleTypeConversionsQuals.hasVolatile(); 8735 if (NeedVolatile) { 8736 // volatile version 8737 ParamTypes[0] = 8738 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8739 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8740 /*IsAssignmentOperator=*/isEqualOp); 8741 } 8742 8743 if (!(*Ptr).isRestrictQualified() && 8744 VisibleTypeConversionsQuals.hasRestrict()) { 8745 // restrict version 8746 ParamTypes[0] 8747 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8748 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8749 /*IsAssignmentOperator=*/isEqualOp); 8750 8751 if (NeedVolatile) { 8752 // volatile restrict version 8753 ParamTypes[0] 8754 = S.Context.getLValueReferenceType( 8755 S.Context.getCVRQualifiedType(*Ptr, 8756 (Qualifiers::Volatile | 8757 Qualifiers::Restrict))); 8758 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8759 /*IsAssignmentOperator=*/isEqualOp); 8760 } 8761 } 8762 } 8763 8764 if (isEqualOp) { 8765 for (BuiltinCandidateTypeSet::iterator 8766 Ptr = CandidateTypes[1].pointer_begin(), 8767 PtrEnd = CandidateTypes[1].pointer_end(); 8768 Ptr != PtrEnd; ++Ptr) { 8769 // Make sure we don't add the same candidate twice. 8770 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8771 continue; 8772 8773 QualType ParamTypes[2] = { 8774 S.Context.getLValueReferenceType(*Ptr), 8775 *Ptr, 8776 }; 8777 8778 // non-volatile version 8779 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8780 /*IsAssignmentOperator=*/true); 8781 8782 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8783 VisibleTypeConversionsQuals.hasVolatile(); 8784 if (NeedVolatile) { 8785 // volatile version 8786 ParamTypes[0] = 8787 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8788 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8789 /*IsAssignmentOperator=*/true); 8790 } 8791 8792 if (!(*Ptr).isRestrictQualified() && 8793 VisibleTypeConversionsQuals.hasRestrict()) { 8794 // restrict version 8795 ParamTypes[0] 8796 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8797 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8798 /*IsAssignmentOperator=*/true); 8799 8800 if (NeedVolatile) { 8801 // volatile restrict version 8802 ParamTypes[0] 8803 = S.Context.getLValueReferenceType( 8804 S.Context.getCVRQualifiedType(*Ptr, 8805 (Qualifiers::Volatile | 8806 Qualifiers::Restrict))); 8807 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8808 /*IsAssignmentOperator=*/true); 8809 } 8810 } 8811 } 8812 } 8813 } 8814 8815 // C++ [over.built]p18: 8816 // 8817 // For every triple (L, VQ, R), where L is an arithmetic type, 8818 // VQ is either volatile or empty, and R is a promoted 8819 // arithmetic type, there exist candidate operator functions of 8820 // the form 8821 // 8822 // VQ L& operator=(VQ L&, R); 8823 // VQ L& operator*=(VQ L&, R); 8824 // VQ L& operator/=(VQ L&, R); 8825 // VQ L& operator+=(VQ L&, R); 8826 // VQ L& operator-=(VQ L&, R); 8827 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8828 if (!HasArithmeticOrEnumeralCandidateType) 8829 return; 8830 8831 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8832 for (unsigned Right = FirstPromotedArithmeticType; 8833 Right < LastPromotedArithmeticType; ++Right) { 8834 QualType ParamTypes[2]; 8835 ParamTypes[1] = ArithmeticTypes[Right]; 8836 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8837 S, ArithmeticTypes[Left], Args[0]); 8838 // Add this built-in operator as a candidate (VQ is empty). 8839 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8840 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8841 /*IsAssignmentOperator=*/isEqualOp); 8842 8843 // Add this built-in operator as a candidate (VQ is 'volatile'). 8844 if (VisibleTypeConversionsQuals.hasVolatile()) { 8845 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8846 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8847 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8848 /*IsAssignmentOperator=*/isEqualOp); 8849 } 8850 } 8851 } 8852 8853 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8854 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8855 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8856 QualType ParamTypes[2]; 8857 ParamTypes[1] = Vec2Ty; 8858 // Add this built-in operator as a candidate (VQ is empty). 8859 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8860 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8861 /*IsAssignmentOperator=*/isEqualOp); 8862 8863 // Add this built-in operator as a candidate (VQ is 'volatile'). 8864 if (VisibleTypeConversionsQuals.hasVolatile()) { 8865 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8866 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8867 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8868 /*IsAssignmentOperator=*/isEqualOp); 8869 } 8870 } 8871 } 8872 8873 // C++ [over.built]p22: 8874 // 8875 // For every triple (L, VQ, R), where L is an integral type, VQ 8876 // is either volatile or empty, and R is a promoted integral 8877 // type, there exist candidate operator functions of the form 8878 // 8879 // VQ L& operator%=(VQ L&, R); 8880 // VQ L& operator<<=(VQ L&, R); 8881 // VQ L& operator>>=(VQ L&, R); 8882 // VQ L& operator&=(VQ L&, R); 8883 // VQ L& operator^=(VQ L&, R); 8884 // VQ L& operator|=(VQ L&, R); 8885 void addAssignmentIntegralOverloads() { 8886 if (!HasArithmeticOrEnumeralCandidateType) 8887 return; 8888 8889 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8890 for (unsigned Right = FirstPromotedIntegralType; 8891 Right < LastPromotedIntegralType; ++Right) { 8892 QualType ParamTypes[2]; 8893 ParamTypes[1] = ArithmeticTypes[Right]; 8894 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8895 S, ArithmeticTypes[Left], Args[0]); 8896 // Add this built-in operator as a candidate (VQ is empty). 8897 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8898 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8899 if (VisibleTypeConversionsQuals.hasVolatile()) { 8900 // Add this built-in operator as a candidate (VQ is 'volatile'). 8901 ParamTypes[0] = LeftBaseTy; 8902 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8903 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8904 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8905 } 8906 } 8907 } 8908 } 8909 8910 // C++ [over.operator]p23: 8911 // 8912 // There also exist candidate operator functions of the form 8913 // 8914 // bool operator!(bool); 8915 // bool operator&&(bool, bool); 8916 // bool operator||(bool, bool); 8917 void addExclaimOverload() { 8918 QualType ParamTy = S.Context.BoolTy; 8919 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8920 /*IsAssignmentOperator=*/false, 8921 /*NumContextualBoolArguments=*/1); 8922 } 8923 void addAmpAmpOrPipePipeOverload() { 8924 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8925 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8926 /*IsAssignmentOperator=*/false, 8927 /*NumContextualBoolArguments=*/2); 8928 } 8929 8930 // C++ [over.built]p13: 8931 // 8932 // For every cv-qualified or cv-unqualified object type T there 8933 // exist candidate operator functions of the form 8934 // 8935 // T* operator+(T*, ptrdiff_t); [ABOVE] 8936 // T& operator[](T*, ptrdiff_t); 8937 // T* operator-(T*, ptrdiff_t); [ABOVE] 8938 // T* operator+(ptrdiff_t, T*); [ABOVE] 8939 // T& operator[](ptrdiff_t, T*); 8940 void addSubscriptOverloads() { 8941 for (BuiltinCandidateTypeSet::iterator 8942 Ptr = CandidateTypes[0].pointer_begin(), 8943 PtrEnd = CandidateTypes[0].pointer_end(); 8944 Ptr != PtrEnd; ++Ptr) { 8945 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8946 QualType PointeeType = (*Ptr)->getPointeeType(); 8947 if (!PointeeType->isObjectType()) 8948 continue; 8949 8950 // T& operator[](T*, ptrdiff_t) 8951 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8952 } 8953 8954 for (BuiltinCandidateTypeSet::iterator 8955 Ptr = CandidateTypes[1].pointer_begin(), 8956 PtrEnd = CandidateTypes[1].pointer_end(); 8957 Ptr != PtrEnd; ++Ptr) { 8958 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8959 QualType PointeeType = (*Ptr)->getPointeeType(); 8960 if (!PointeeType->isObjectType()) 8961 continue; 8962 8963 // T& operator[](ptrdiff_t, T*) 8964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8965 } 8966 } 8967 8968 // C++ [over.built]p11: 8969 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8970 // C1 is the same type as C2 or is a derived class of C2, T is an object 8971 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8972 // there exist candidate operator functions of the form 8973 // 8974 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8975 // 8976 // where CV12 is the union of CV1 and CV2. 8977 void addArrowStarOverloads() { 8978 for (BuiltinCandidateTypeSet::iterator 8979 Ptr = CandidateTypes[0].pointer_begin(), 8980 PtrEnd = CandidateTypes[0].pointer_end(); 8981 Ptr != PtrEnd; ++Ptr) { 8982 QualType C1Ty = (*Ptr); 8983 QualType C1; 8984 QualifierCollector Q1; 8985 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8986 if (!isa<RecordType>(C1)) 8987 continue; 8988 // heuristic to reduce number of builtin candidates in the set. 8989 // Add volatile/restrict version only if there are conversions to a 8990 // volatile/restrict type. 8991 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8992 continue; 8993 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8994 continue; 8995 for (BuiltinCandidateTypeSet::iterator 8996 MemPtr = CandidateTypes[1].member_pointer_begin(), 8997 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8998 MemPtr != MemPtrEnd; ++MemPtr) { 8999 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 9000 QualType C2 = QualType(mptr->getClass(), 0); 9001 C2 = C2.getUnqualifiedType(); 9002 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9003 break; 9004 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 9005 // build CV12 T& 9006 QualType T = mptr->getPointeeType(); 9007 if (!VisibleTypeConversionsQuals.hasVolatile() && 9008 T.isVolatileQualified()) 9009 continue; 9010 if (!VisibleTypeConversionsQuals.hasRestrict() && 9011 T.isRestrictQualified()) 9012 continue; 9013 T = Q1.apply(S.Context, T); 9014 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9015 } 9016 } 9017 } 9018 9019 // Note that we don't consider the first argument, since it has been 9020 // contextually converted to bool long ago. The candidates below are 9021 // therefore added as binary. 9022 // 9023 // C++ [over.built]p25: 9024 // For every type T, where T is a pointer, pointer-to-member, or scoped 9025 // enumeration type, there exist candidate operator functions of the form 9026 // 9027 // T operator?(bool, T, T); 9028 // 9029 void addConditionalOperatorOverloads() { 9030 /// Set of (canonical) types that we've already handled. 9031 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9032 9033 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9034 for (BuiltinCandidateTypeSet::iterator 9035 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9036 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9037 Ptr != PtrEnd; ++Ptr) { 9038 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9039 continue; 9040 9041 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9042 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9043 } 9044 9045 for (BuiltinCandidateTypeSet::iterator 9046 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9047 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9048 MemPtr != MemPtrEnd; ++MemPtr) { 9049 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9050 continue; 9051 9052 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9053 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9054 } 9055 9056 if (S.getLangOpts().CPlusPlus11) { 9057 for (BuiltinCandidateTypeSet::iterator 9058 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9059 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9060 Enum != EnumEnd; ++Enum) { 9061 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9062 continue; 9063 9064 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9065 continue; 9066 9067 QualType ParamTypes[2] = { *Enum, *Enum }; 9068 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9069 } 9070 } 9071 } 9072 } 9073 }; 9074 9075 } // end anonymous namespace 9076 9077 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9078 /// operator overloads to the candidate set (C++ [over.built]), based 9079 /// on the operator @p Op and the arguments given. For example, if the 9080 /// operator is a binary '+', this routine might add "int 9081 /// operator+(int, int)" to cover integer addition. 9082 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9083 SourceLocation OpLoc, 9084 ArrayRef<Expr *> Args, 9085 OverloadCandidateSet &CandidateSet) { 9086 // Find all of the types that the arguments can convert to, but only 9087 // if the operator we're looking at has built-in operator candidates 9088 // that make use of these types. Also record whether we encounter non-record 9089 // candidate types or either arithmetic or enumeral candidate types. 9090 Qualifiers VisibleTypeConversionsQuals; 9091 VisibleTypeConversionsQuals.addConst(); 9092 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9093 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9094 9095 bool HasNonRecordCandidateType = false; 9096 bool HasArithmeticOrEnumeralCandidateType = false; 9097 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9098 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9099 CandidateTypes.emplace_back(*this); 9100 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9101 OpLoc, 9102 true, 9103 (Op == OO_Exclaim || 9104 Op == OO_AmpAmp || 9105 Op == OO_PipePipe), 9106 VisibleTypeConversionsQuals); 9107 HasNonRecordCandidateType = HasNonRecordCandidateType || 9108 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9109 HasArithmeticOrEnumeralCandidateType = 9110 HasArithmeticOrEnumeralCandidateType || 9111 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9112 } 9113 9114 // Exit early when no non-record types have been added to the candidate set 9115 // for any of the arguments to the operator. 9116 // 9117 // We can't exit early for !, ||, or &&, since there we have always have 9118 // 'bool' overloads. 9119 if (!HasNonRecordCandidateType && 9120 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9121 return; 9122 9123 // Setup an object to manage the common state for building overloads. 9124 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9125 VisibleTypeConversionsQuals, 9126 HasArithmeticOrEnumeralCandidateType, 9127 CandidateTypes, CandidateSet); 9128 9129 // Dispatch over the operation to add in only those overloads which apply. 9130 switch (Op) { 9131 case OO_None: 9132 case NUM_OVERLOADED_OPERATORS: 9133 llvm_unreachable("Expected an overloaded operator"); 9134 9135 case OO_New: 9136 case OO_Delete: 9137 case OO_Array_New: 9138 case OO_Array_Delete: 9139 case OO_Call: 9140 llvm_unreachable( 9141 "Special operators don't use AddBuiltinOperatorCandidates"); 9142 9143 case OO_Comma: 9144 case OO_Arrow: 9145 case OO_Coawait: 9146 // C++ [over.match.oper]p3: 9147 // -- For the operator ',', the unary operator '&', the 9148 // operator '->', or the operator 'co_await', the 9149 // built-in candidates set is empty. 9150 break; 9151 9152 case OO_Plus: // '+' is either unary or binary 9153 if (Args.size() == 1) 9154 OpBuilder.addUnaryPlusPointerOverloads(); 9155 LLVM_FALLTHROUGH; 9156 9157 case OO_Minus: // '-' is either unary or binary 9158 if (Args.size() == 1) { 9159 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9160 } else { 9161 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9162 OpBuilder.addGenericBinaryArithmeticOverloads(); 9163 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9164 } 9165 break; 9166 9167 case OO_Star: // '*' is either unary or binary 9168 if (Args.size() == 1) 9169 OpBuilder.addUnaryStarPointerOverloads(); 9170 else 9171 OpBuilder.addGenericBinaryArithmeticOverloads(); 9172 break; 9173 9174 case OO_Slash: 9175 OpBuilder.addGenericBinaryArithmeticOverloads(); 9176 break; 9177 9178 case OO_PlusPlus: 9179 case OO_MinusMinus: 9180 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9181 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9182 break; 9183 9184 case OO_EqualEqual: 9185 case OO_ExclaimEqual: 9186 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9187 LLVM_FALLTHROUGH; 9188 9189 case OO_Less: 9190 case OO_Greater: 9191 case OO_LessEqual: 9192 case OO_GreaterEqual: 9193 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9194 OpBuilder.addGenericBinaryArithmeticOverloads(); 9195 break; 9196 9197 case OO_Spaceship: 9198 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9199 OpBuilder.addThreeWayArithmeticOverloads(); 9200 break; 9201 9202 case OO_Percent: 9203 case OO_Caret: 9204 case OO_Pipe: 9205 case OO_LessLess: 9206 case OO_GreaterGreater: 9207 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9208 break; 9209 9210 case OO_Amp: // '&' is either unary or binary 9211 if (Args.size() == 1) 9212 // C++ [over.match.oper]p3: 9213 // -- For the operator ',', the unary operator '&', or the 9214 // operator '->', the built-in candidates set is empty. 9215 break; 9216 9217 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9218 break; 9219 9220 case OO_Tilde: 9221 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9222 break; 9223 9224 case OO_Equal: 9225 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9226 LLVM_FALLTHROUGH; 9227 9228 case OO_PlusEqual: 9229 case OO_MinusEqual: 9230 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9231 LLVM_FALLTHROUGH; 9232 9233 case OO_StarEqual: 9234 case OO_SlashEqual: 9235 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9236 break; 9237 9238 case OO_PercentEqual: 9239 case OO_LessLessEqual: 9240 case OO_GreaterGreaterEqual: 9241 case OO_AmpEqual: 9242 case OO_CaretEqual: 9243 case OO_PipeEqual: 9244 OpBuilder.addAssignmentIntegralOverloads(); 9245 break; 9246 9247 case OO_Exclaim: 9248 OpBuilder.addExclaimOverload(); 9249 break; 9250 9251 case OO_AmpAmp: 9252 case OO_PipePipe: 9253 OpBuilder.addAmpAmpOrPipePipeOverload(); 9254 break; 9255 9256 case OO_Subscript: 9257 OpBuilder.addSubscriptOverloads(); 9258 break; 9259 9260 case OO_ArrowStar: 9261 OpBuilder.addArrowStarOverloads(); 9262 break; 9263 9264 case OO_Conditional: 9265 OpBuilder.addConditionalOperatorOverloads(); 9266 OpBuilder.addGenericBinaryArithmeticOverloads(); 9267 break; 9268 } 9269 } 9270 9271 /// Add function candidates found via argument-dependent lookup 9272 /// to the set of overloading candidates. 9273 /// 9274 /// This routine performs argument-dependent name lookup based on the 9275 /// given function name (which may also be an operator name) and adds 9276 /// all of the overload candidates found by ADL to the overload 9277 /// candidate set (C++ [basic.lookup.argdep]). 9278 void 9279 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9280 SourceLocation Loc, 9281 ArrayRef<Expr *> Args, 9282 TemplateArgumentListInfo *ExplicitTemplateArgs, 9283 OverloadCandidateSet& CandidateSet, 9284 bool PartialOverloading) { 9285 ADLResult Fns; 9286 9287 // FIXME: This approach for uniquing ADL results (and removing 9288 // redundant candidates from the set) relies on pointer-equality, 9289 // which means we need to key off the canonical decl. However, 9290 // always going back to the canonical decl might not get us the 9291 // right set of default arguments. What default arguments are 9292 // we supposed to consider on ADL candidates, anyway? 9293 9294 // FIXME: Pass in the explicit template arguments? 9295 ArgumentDependentLookup(Name, Loc, Args, Fns); 9296 9297 // Erase all of the candidates we already knew about. 9298 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9299 CandEnd = CandidateSet.end(); 9300 Cand != CandEnd; ++Cand) 9301 if (Cand->Function) { 9302 Fns.erase(Cand->Function); 9303 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9304 Fns.erase(FunTmpl); 9305 } 9306 9307 // For each of the ADL candidates we found, add it to the overload 9308 // set. 9309 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9310 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9311 9312 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9313 if (ExplicitTemplateArgs) 9314 continue; 9315 9316 AddOverloadCandidate( 9317 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9318 PartialOverloading, /*AllowExplicit=*/true, 9319 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9320 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9321 AddOverloadCandidate( 9322 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9323 /*SuppressUserConversions=*/false, PartialOverloading, 9324 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9325 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9326 } 9327 } else { 9328 auto *FTD = cast<FunctionTemplateDecl>(*I); 9329 AddTemplateOverloadCandidate( 9330 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9331 /*SuppressUserConversions=*/false, PartialOverloading, 9332 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9333 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9334 Context, FTD->getTemplatedDecl())) { 9335 AddTemplateOverloadCandidate( 9336 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9337 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9338 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9339 OverloadCandidateParamOrder::Reversed); 9340 } 9341 } 9342 } 9343 } 9344 9345 namespace { 9346 enum class Comparison { Equal, Better, Worse }; 9347 } 9348 9349 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9350 /// overload resolution. 9351 /// 9352 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9353 /// Cand1's first N enable_if attributes have precisely the same conditions as 9354 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9355 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9356 /// 9357 /// Note that you can have a pair of candidates such that Cand1's enable_if 9358 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9359 /// worse than Cand1's. 9360 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9361 const FunctionDecl *Cand2) { 9362 // Common case: One (or both) decls don't have enable_if attrs. 9363 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9364 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9365 if (!Cand1Attr || !Cand2Attr) { 9366 if (Cand1Attr == Cand2Attr) 9367 return Comparison::Equal; 9368 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9369 } 9370 9371 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9372 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9373 9374 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9375 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9376 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9377 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9378 9379 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9380 // has fewer enable_if attributes than Cand2, and vice versa. 9381 if (!Cand1A) 9382 return Comparison::Worse; 9383 if (!Cand2A) 9384 return Comparison::Better; 9385 9386 Cand1ID.clear(); 9387 Cand2ID.clear(); 9388 9389 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9390 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9391 if (Cand1ID != Cand2ID) 9392 return Comparison::Worse; 9393 } 9394 9395 return Comparison::Equal; 9396 } 9397 9398 static Comparison 9399 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9400 const OverloadCandidate &Cand2) { 9401 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9402 !Cand2.Function->isMultiVersion()) 9403 return Comparison::Equal; 9404 9405 // If both are invalid, they are equal. If one of them is invalid, the other 9406 // is better. 9407 if (Cand1.Function->isInvalidDecl()) { 9408 if (Cand2.Function->isInvalidDecl()) 9409 return Comparison::Equal; 9410 return Comparison::Worse; 9411 } 9412 if (Cand2.Function->isInvalidDecl()) 9413 return Comparison::Better; 9414 9415 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9416 // cpu_dispatch, else arbitrarily based on the identifiers. 9417 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9418 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9419 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9420 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9421 9422 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9423 return Comparison::Equal; 9424 9425 if (Cand1CPUDisp && !Cand2CPUDisp) 9426 return Comparison::Better; 9427 if (Cand2CPUDisp && !Cand1CPUDisp) 9428 return Comparison::Worse; 9429 9430 if (Cand1CPUSpec && Cand2CPUSpec) { 9431 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9432 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9433 ? Comparison::Better 9434 : Comparison::Worse; 9435 9436 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9437 FirstDiff = std::mismatch( 9438 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9439 Cand2CPUSpec->cpus_begin(), 9440 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9441 return LHS->getName() == RHS->getName(); 9442 }); 9443 9444 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9445 "Two different cpu-specific versions should not have the same " 9446 "identifier list, otherwise they'd be the same decl!"); 9447 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9448 ? Comparison::Better 9449 : Comparison::Worse; 9450 } 9451 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9452 } 9453 9454 /// Compute the type of the implicit object parameter for the given function, 9455 /// if any. Returns None if there is no implicit object parameter, and a null 9456 /// QualType if there is a 'matches anything' implicit object parameter. 9457 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9458 const FunctionDecl *F) { 9459 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9460 return llvm::None; 9461 9462 auto *M = cast<CXXMethodDecl>(F); 9463 // Static member functions' object parameters match all types. 9464 if (M->isStatic()) 9465 return QualType(); 9466 9467 QualType T = M->getThisObjectType(); 9468 if (M->getRefQualifier() == RQ_RValue) 9469 return Context.getRValueReferenceType(T); 9470 return Context.getLValueReferenceType(T); 9471 } 9472 9473 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9474 const FunctionDecl *F2, unsigned NumParams) { 9475 if (declaresSameEntity(F1, F2)) 9476 return true; 9477 9478 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9479 if (First) { 9480 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9481 return *T; 9482 } 9483 assert(I < F->getNumParams()); 9484 return F->getParamDecl(I++)->getType(); 9485 }; 9486 9487 unsigned I1 = 0, I2 = 0; 9488 for (unsigned I = 0; I != NumParams; ++I) { 9489 QualType T1 = NextParam(F1, I1, I == 0); 9490 QualType T2 = NextParam(F2, I2, I == 0); 9491 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9492 return false; 9493 } 9494 return true; 9495 } 9496 9497 /// isBetterOverloadCandidate - Determines whether the first overload 9498 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9499 bool clang::isBetterOverloadCandidate( 9500 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9501 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9502 // Define viable functions to be better candidates than non-viable 9503 // functions. 9504 if (!Cand2.Viable) 9505 return Cand1.Viable; 9506 else if (!Cand1.Viable) 9507 return false; 9508 9509 // [CUDA] A function with 'never' preference is marked not viable, therefore 9510 // is never shown up here. The worst preference shown up here is 'wrong side', 9511 // e.g. a host function called by a device host function in device 9512 // compilation. This is valid AST as long as the host device function is not 9513 // emitted, e.g. it is an inline function which is called only by a host 9514 // function. A deferred diagnostic will be triggered if it is emitted. 9515 // However a wrong-sided function is still a viable candidate here. 9516 // 9517 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9518 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9519 // can be emitted, Cand1 is not better than Cand2. This rule should have 9520 // precedence over other rules. 9521 // 9522 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9523 // other rules should be used to determine which is better. This is because 9524 // host/device based overloading resolution is mostly for determining 9525 // viability of a function. If two functions are both viable, other factors 9526 // should take precedence in preference, e.g. the standard-defined preferences 9527 // like argument conversion ranks or enable_if partial-ordering. The 9528 // preference for pass-object-size parameters is probably most similar to a 9529 // type-based-overloading decision and so should take priority. 9530 // 9531 // If other rules cannot determine which is better, CUDA preference will be 9532 // used again to determine which is better. 9533 // 9534 // TODO: Currently IdentifyCUDAPreference does not return correct values 9535 // for functions called in global variable initializers due to missing 9536 // correct context about device/host. Therefore we can only enforce this 9537 // rule when there is a caller. We should enforce this rule for functions 9538 // in global variable initializers once proper context is added. 9539 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9540 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9541 bool IsCallerImplicitHD = Sema::IsCUDAImplicitHostDeviceFunction(Caller); 9542 bool IsCand1ImplicitHD = 9543 Sema::IsCUDAImplicitHostDeviceFunction(Cand1.Function); 9544 bool IsCand2ImplicitHD = 9545 Sema::IsCUDAImplicitHostDeviceFunction(Cand2.Function); 9546 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9547 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9548 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9549 // The implicit HD function may be a function in a system header which 9550 // is forced by pragma. In device compilation, if we prefer HD candidates 9551 // over wrong-sided candidates, overloading resolution may change, which 9552 // may result in non-deferrable diagnostics. As a workaround, we let 9553 // implicit HD candidates take equal preference as wrong-sided candidates. 9554 // This will preserve the overloading resolution. 9555 auto EmitThreshold = 9556 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9557 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9558 ? Sema::CFP_Never 9559 : Sema::CFP_WrongSide; 9560 auto Cand1Emittable = P1 > EmitThreshold; 9561 auto Cand2Emittable = P2 > EmitThreshold; 9562 if (Cand1Emittable && !Cand2Emittable) 9563 return true; 9564 if (!Cand1Emittable && Cand2Emittable) 9565 return false; 9566 } 9567 } 9568 9569 // C++ [over.match.best]p1: 9570 // 9571 // -- if F is a static member function, ICS1(F) is defined such 9572 // that ICS1(F) is neither better nor worse than ICS1(G) for 9573 // any function G, and, symmetrically, ICS1(G) is neither 9574 // better nor worse than ICS1(F). 9575 unsigned StartArg = 0; 9576 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9577 StartArg = 1; 9578 9579 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9580 // We don't allow incompatible pointer conversions in C++. 9581 if (!S.getLangOpts().CPlusPlus) 9582 return ICS.isStandard() && 9583 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9584 9585 // The only ill-formed conversion we allow in C++ is the string literal to 9586 // char* conversion, which is only considered ill-formed after C++11. 9587 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9588 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9589 }; 9590 9591 // Define functions that don't require ill-formed conversions for a given 9592 // argument to be better candidates than functions that do. 9593 unsigned NumArgs = Cand1.Conversions.size(); 9594 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9595 bool HasBetterConversion = false; 9596 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9597 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9598 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9599 if (Cand1Bad != Cand2Bad) { 9600 if (Cand1Bad) 9601 return false; 9602 HasBetterConversion = true; 9603 } 9604 } 9605 9606 if (HasBetterConversion) 9607 return true; 9608 9609 // C++ [over.match.best]p1: 9610 // A viable function F1 is defined to be a better function than another 9611 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9612 // conversion sequence than ICSi(F2), and then... 9613 bool HasWorseConversion = false; 9614 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9615 switch (CompareImplicitConversionSequences(S, Loc, 9616 Cand1.Conversions[ArgIdx], 9617 Cand2.Conversions[ArgIdx])) { 9618 case ImplicitConversionSequence::Better: 9619 // Cand1 has a better conversion sequence. 9620 HasBetterConversion = true; 9621 break; 9622 9623 case ImplicitConversionSequence::Worse: 9624 if (Cand1.Function && Cand2.Function && 9625 Cand1.isReversed() != Cand2.isReversed() && 9626 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9627 NumArgs)) { 9628 // Work around large-scale breakage caused by considering reversed 9629 // forms of operator== in C++20: 9630 // 9631 // When comparing a function against a reversed function with the same 9632 // parameter types, if we have a better conversion for one argument and 9633 // a worse conversion for the other, the implicit conversion sequences 9634 // are treated as being equally good. 9635 // 9636 // This prevents a comparison function from being considered ambiguous 9637 // with a reversed form that is written in the same way. 9638 // 9639 // We diagnose this as an extension from CreateOverloadedBinOp. 9640 HasWorseConversion = true; 9641 break; 9642 } 9643 9644 // Cand1 can't be better than Cand2. 9645 return false; 9646 9647 case ImplicitConversionSequence::Indistinguishable: 9648 // Do nothing. 9649 break; 9650 } 9651 } 9652 9653 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9654 // ICSj(F2), or, if not that, 9655 if (HasBetterConversion && !HasWorseConversion) 9656 return true; 9657 9658 // -- the context is an initialization by user-defined conversion 9659 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9660 // from the return type of F1 to the destination type (i.e., 9661 // the type of the entity being initialized) is a better 9662 // conversion sequence than the standard conversion sequence 9663 // from the return type of F2 to the destination type. 9664 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9665 Cand1.Function && Cand2.Function && 9666 isa<CXXConversionDecl>(Cand1.Function) && 9667 isa<CXXConversionDecl>(Cand2.Function)) { 9668 // First check whether we prefer one of the conversion functions over the 9669 // other. This only distinguishes the results in non-standard, extension 9670 // cases such as the conversion from a lambda closure type to a function 9671 // pointer or block. 9672 ImplicitConversionSequence::CompareKind Result = 9673 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9674 if (Result == ImplicitConversionSequence::Indistinguishable) 9675 Result = CompareStandardConversionSequences(S, Loc, 9676 Cand1.FinalConversion, 9677 Cand2.FinalConversion); 9678 9679 if (Result != ImplicitConversionSequence::Indistinguishable) 9680 return Result == ImplicitConversionSequence::Better; 9681 9682 // FIXME: Compare kind of reference binding if conversion functions 9683 // convert to a reference type used in direct reference binding, per 9684 // C++14 [over.match.best]p1 section 2 bullet 3. 9685 } 9686 9687 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9688 // as combined with the resolution to CWG issue 243. 9689 // 9690 // When the context is initialization by constructor ([over.match.ctor] or 9691 // either phase of [over.match.list]), a constructor is preferred over 9692 // a conversion function. 9693 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9694 Cand1.Function && Cand2.Function && 9695 isa<CXXConstructorDecl>(Cand1.Function) != 9696 isa<CXXConstructorDecl>(Cand2.Function)) 9697 return isa<CXXConstructorDecl>(Cand1.Function); 9698 9699 // -- F1 is a non-template function and F2 is a function template 9700 // specialization, or, if not that, 9701 bool Cand1IsSpecialization = Cand1.Function && 9702 Cand1.Function->getPrimaryTemplate(); 9703 bool Cand2IsSpecialization = Cand2.Function && 9704 Cand2.Function->getPrimaryTemplate(); 9705 if (Cand1IsSpecialization != Cand2IsSpecialization) 9706 return Cand2IsSpecialization; 9707 9708 // -- F1 and F2 are function template specializations, and the function 9709 // template for F1 is more specialized than the template for F2 9710 // according to the partial ordering rules described in 14.5.5.2, or, 9711 // if not that, 9712 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9713 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9714 Cand1.Function->getPrimaryTemplate(), 9715 Cand2.Function->getPrimaryTemplate(), Loc, 9716 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9717 : TPOC_Call, 9718 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9719 Cand1.isReversed() ^ Cand2.isReversed())) 9720 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9721 } 9722 9723 // -— F1 and F2 are non-template functions with the same 9724 // parameter-type-lists, and F1 is more constrained than F2 [...], 9725 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9726 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9727 Cand2.Function->hasPrototype()) { 9728 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9729 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9730 if (PT1->getNumParams() == PT2->getNumParams() && 9731 PT1->isVariadic() == PT2->isVariadic() && 9732 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9733 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9734 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9735 if (RC1 && RC2) { 9736 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9737 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9738 {RC2}, AtLeastAsConstrained1) || 9739 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9740 {RC1}, AtLeastAsConstrained2)) 9741 return false; 9742 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9743 return AtLeastAsConstrained1; 9744 } else if (RC1 || RC2) { 9745 return RC1 != nullptr; 9746 } 9747 } 9748 } 9749 9750 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9751 // class B of D, and for all arguments the corresponding parameters of 9752 // F1 and F2 have the same type. 9753 // FIXME: Implement the "all parameters have the same type" check. 9754 bool Cand1IsInherited = 9755 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9756 bool Cand2IsInherited = 9757 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9758 if (Cand1IsInherited != Cand2IsInherited) 9759 return Cand2IsInherited; 9760 else if (Cand1IsInherited) { 9761 assert(Cand2IsInherited); 9762 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9763 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9764 if (Cand1Class->isDerivedFrom(Cand2Class)) 9765 return true; 9766 if (Cand2Class->isDerivedFrom(Cand1Class)) 9767 return false; 9768 // Inherited from sibling base classes: still ambiguous. 9769 } 9770 9771 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9772 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9773 // with reversed order of parameters and F1 is not 9774 // 9775 // We rank reversed + different operator as worse than just reversed, but 9776 // that comparison can never happen, because we only consider reversing for 9777 // the maximally-rewritten operator (== or <=>). 9778 if (Cand1.RewriteKind != Cand2.RewriteKind) 9779 return Cand1.RewriteKind < Cand2.RewriteKind; 9780 9781 // Check C++17 tie-breakers for deduction guides. 9782 { 9783 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9784 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9785 if (Guide1 && Guide2) { 9786 // -- F1 is generated from a deduction-guide and F2 is not 9787 if (Guide1->isImplicit() != Guide2->isImplicit()) 9788 return Guide2->isImplicit(); 9789 9790 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9791 if (Guide1->isCopyDeductionCandidate()) 9792 return true; 9793 } 9794 } 9795 9796 // Check for enable_if value-based overload resolution. 9797 if (Cand1.Function && Cand2.Function) { 9798 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9799 if (Cmp != Comparison::Equal) 9800 return Cmp == Comparison::Better; 9801 } 9802 9803 bool HasPS1 = Cand1.Function != nullptr && 9804 functionHasPassObjectSizeParams(Cand1.Function); 9805 bool HasPS2 = Cand2.Function != nullptr && 9806 functionHasPassObjectSizeParams(Cand2.Function); 9807 if (HasPS1 != HasPS2 && HasPS1) 9808 return true; 9809 9810 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9811 if (MV == Comparison::Better) 9812 return true; 9813 if (MV == Comparison::Worse) 9814 return false; 9815 9816 // If other rules cannot determine which is better, CUDA preference is used 9817 // to determine which is better. 9818 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9819 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9820 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9821 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9822 } 9823 9824 return false; 9825 } 9826 9827 /// Determine whether two declarations are "equivalent" for the purposes of 9828 /// name lookup and overload resolution. This applies when the same internal/no 9829 /// linkage entity is defined by two modules (probably by textually including 9830 /// the same header). In such a case, we don't consider the declarations to 9831 /// declare the same entity, but we also don't want lookups with both 9832 /// declarations visible to be ambiguous in some cases (this happens when using 9833 /// a modularized libstdc++). 9834 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9835 const NamedDecl *B) { 9836 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9837 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9838 if (!VA || !VB) 9839 return false; 9840 9841 // The declarations must be declaring the same name as an internal linkage 9842 // entity in different modules. 9843 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9844 VB->getDeclContext()->getRedeclContext()) || 9845 getOwningModule(VA) == getOwningModule(VB) || 9846 VA->isExternallyVisible() || VB->isExternallyVisible()) 9847 return false; 9848 9849 // Check that the declarations appear to be equivalent. 9850 // 9851 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9852 // For constants and functions, we should check the initializer or body is 9853 // the same. For non-constant variables, we shouldn't allow it at all. 9854 if (Context.hasSameType(VA->getType(), VB->getType())) 9855 return true; 9856 9857 // Enum constants within unnamed enumerations will have different types, but 9858 // may still be similar enough to be interchangeable for our purposes. 9859 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9860 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9861 // Only handle anonymous enums. If the enumerations were named and 9862 // equivalent, they would have been merged to the same type. 9863 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9864 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9865 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9866 !Context.hasSameType(EnumA->getIntegerType(), 9867 EnumB->getIntegerType())) 9868 return false; 9869 // Allow this only if the value is the same for both enumerators. 9870 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9871 } 9872 } 9873 9874 // Nothing else is sufficiently similar. 9875 return false; 9876 } 9877 9878 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9879 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9880 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9881 9882 Module *M = getOwningModule(D); 9883 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9884 << !M << (M ? M->getFullModuleName() : ""); 9885 9886 for (auto *E : Equiv) { 9887 Module *M = getOwningModule(E); 9888 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9889 << !M << (M ? M->getFullModuleName() : ""); 9890 } 9891 } 9892 9893 /// Computes the best viable function (C++ 13.3.3) 9894 /// within an overload candidate set. 9895 /// 9896 /// \param Loc The location of the function name (or operator symbol) for 9897 /// which overload resolution occurs. 9898 /// 9899 /// \param Best If overload resolution was successful or found a deleted 9900 /// function, \p Best points to the candidate function found. 9901 /// 9902 /// \returns The result of overload resolution. 9903 OverloadingResult 9904 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9905 iterator &Best) { 9906 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9907 std::transform(begin(), end(), std::back_inserter(Candidates), 9908 [](OverloadCandidate &Cand) { return &Cand; }); 9909 9910 // Find the best viable function. 9911 Best = end(); 9912 for (auto *Cand : Candidates) { 9913 Cand->Best = false; 9914 if (Cand->Viable) 9915 if (Best == end() || 9916 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9917 Best = Cand; 9918 } 9919 9920 // If we didn't find any viable functions, abort. 9921 if (Best == end()) 9922 return OR_No_Viable_Function; 9923 9924 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9925 9926 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9927 PendingBest.push_back(&*Best); 9928 Best->Best = true; 9929 9930 // Make sure that this function is better than every other viable 9931 // function. If not, we have an ambiguity. 9932 while (!PendingBest.empty()) { 9933 auto *Curr = PendingBest.pop_back_val(); 9934 for (auto *Cand : Candidates) { 9935 if (Cand->Viable && !Cand->Best && 9936 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9937 PendingBest.push_back(Cand); 9938 Cand->Best = true; 9939 9940 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9941 Curr->Function)) 9942 EquivalentCands.push_back(Cand->Function); 9943 else 9944 Best = end(); 9945 } 9946 } 9947 } 9948 9949 // If we found more than one best candidate, this is ambiguous. 9950 if (Best == end()) 9951 return OR_Ambiguous; 9952 9953 // Best is the best viable function. 9954 if (Best->Function && Best->Function->isDeleted()) 9955 return OR_Deleted; 9956 9957 if (!EquivalentCands.empty()) 9958 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9959 EquivalentCands); 9960 9961 return OR_Success; 9962 } 9963 9964 namespace { 9965 9966 enum OverloadCandidateKind { 9967 oc_function, 9968 oc_method, 9969 oc_reversed_binary_operator, 9970 oc_constructor, 9971 oc_implicit_default_constructor, 9972 oc_implicit_copy_constructor, 9973 oc_implicit_move_constructor, 9974 oc_implicit_copy_assignment, 9975 oc_implicit_move_assignment, 9976 oc_implicit_equality_comparison, 9977 oc_inherited_constructor 9978 }; 9979 9980 enum OverloadCandidateSelect { 9981 ocs_non_template, 9982 ocs_template, 9983 ocs_described_template, 9984 }; 9985 9986 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9987 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9988 OverloadCandidateRewriteKind CRK, 9989 std::string &Description) { 9990 9991 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9992 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9993 isTemplate = true; 9994 Description = S.getTemplateArgumentBindingsText( 9995 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9996 } 9997 9998 OverloadCandidateSelect Select = [&]() { 9999 if (!Description.empty()) 10000 return ocs_described_template; 10001 return isTemplate ? ocs_template : ocs_non_template; 10002 }(); 10003 10004 OverloadCandidateKind Kind = [&]() { 10005 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10006 return oc_implicit_equality_comparison; 10007 10008 if (CRK & CRK_Reversed) 10009 return oc_reversed_binary_operator; 10010 10011 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10012 if (!Ctor->isImplicit()) { 10013 if (isa<ConstructorUsingShadowDecl>(Found)) 10014 return oc_inherited_constructor; 10015 else 10016 return oc_constructor; 10017 } 10018 10019 if (Ctor->isDefaultConstructor()) 10020 return oc_implicit_default_constructor; 10021 10022 if (Ctor->isMoveConstructor()) 10023 return oc_implicit_move_constructor; 10024 10025 assert(Ctor->isCopyConstructor() && 10026 "unexpected sort of implicit constructor"); 10027 return oc_implicit_copy_constructor; 10028 } 10029 10030 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10031 // This actually gets spelled 'candidate function' for now, but 10032 // it doesn't hurt to split it out. 10033 if (!Meth->isImplicit()) 10034 return oc_method; 10035 10036 if (Meth->isMoveAssignmentOperator()) 10037 return oc_implicit_move_assignment; 10038 10039 if (Meth->isCopyAssignmentOperator()) 10040 return oc_implicit_copy_assignment; 10041 10042 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10043 return oc_method; 10044 } 10045 10046 return oc_function; 10047 }(); 10048 10049 return std::make_pair(Kind, Select); 10050 } 10051 10052 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10053 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10054 // set. 10055 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10056 S.Diag(FoundDecl->getLocation(), 10057 diag::note_ovl_candidate_inherited_constructor) 10058 << Shadow->getNominatedBaseClass(); 10059 } 10060 10061 } // end anonymous namespace 10062 10063 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10064 const FunctionDecl *FD) { 10065 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10066 bool AlwaysTrue; 10067 if (EnableIf->getCond()->isValueDependent() || 10068 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10069 return false; 10070 if (!AlwaysTrue) 10071 return false; 10072 } 10073 return true; 10074 } 10075 10076 /// Returns true if we can take the address of the function. 10077 /// 10078 /// \param Complain - If true, we'll emit a diagnostic 10079 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10080 /// we in overload resolution? 10081 /// \param Loc - The location of the statement we're complaining about. Ignored 10082 /// if we're not complaining, or if we're in overload resolution. 10083 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10084 bool Complain, 10085 bool InOverloadResolution, 10086 SourceLocation Loc) { 10087 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10088 if (Complain) { 10089 if (InOverloadResolution) 10090 S.Diag(FD->getBeginLoc(), 10091 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10092 else 10093 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10094 } 10095 return false; 10096 } 10097 10098 if (FD->getTrailingRequiresClause()) { 10099 ConstraintSatisfaction Satisfaction; 10100 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10101 return false; 10102 if (!Satisfaction.IsSatisfied) { 10103 if (Complain) { 10104 if (InOverloadResolution) 10105 S.Diag(FD->getBeginLoc(), 10106 diag::note_ovl_candidate_unsatisfied_constraints); 10107 else 10108 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10109 << FD; 10110 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10111 } 10112 return false; 10113 } 10114 } 10115 10116 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10117 return P->hasAttr<PassObjectSizeAttr>(); 10118 }); 10119 if (I == FD->param_end()) 10120 return true; 10121 10122 if (Complain) { 10123 // Add one to ParamNo because it's user-facing 10124 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10125 if (InOverloadResolution) 10126 S.Diag(FD->getLocation(), 10127 diag::note_ovl_candidate_has_pass_object_size_params) 10128 << ParamNo; 10129 else 10130 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10131 << FD << ParamNo; 10132 } 10133 return false; 10134 } 10135 10136 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10137 const FunctionDecl *FD) { 10138 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10139 /*InOverloadResolution=*/true, 10140 /*Loc=*/SourceLocation()); 10141 } 10142 10143 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10144 bool Complain, 10145 SourceLocation Loc) { 10146 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10147 /*InOverloadResolution=*/false, 10148 Loc); 10149 } 10150 10151 // Notes the location of an overload candidate. 10152 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10153 OverloadCandidateRewriteKind RewriteKind, 10154 QualType DestType, bool TakingAddress) { 10155 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10156 return; 10157 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10158 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10159 return; 10160 10161 std::string FnDesc; 10162 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10163 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10164 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10165 << (unsigned)KSPair.first << (unsigned)KSPair.second 10166 << Fn << FnDesc; 10167 10168 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10169 Diag(Fn->getLocation(), PD); 10170 MaybeEmitInheritedConstructorNote(*this, Found); 10171 } 10172 10173 static void 10174 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10175 // Perhaps the ambiguity was caused by two atomic constraints that are 10176 // 'identical' but not equivalent: 10177 // 10178 // void foo() requires (sizeof(T) > 4) { } // #1 10179 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10180 // 10181 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10182 // #2 to subsume #1, but these constraint are not considered equivalent 10183 // according to the subsumption rules because they are not the same 10184 // source-level construct. This behavior is quite confusing and we should try 10185 // to help the user figure out what happened. 10186 10187 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10188 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10189 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10190 if (!I->Function) 10191 continue; 10192 SmallVector<const Expr *, 3> AC; 10193 if (auto *Template = I->Function->getPrimaryTemplate()) 10194 Template->getAssociatedConstraints(AC); 10195 else 10196 I->Function->getAssociatedConstraints(AC); 10197 if (AC.empty()) 10198 continue; 10199 if (FirstCand == nullptr) { 10200 FirstCand = I->Function; 10201 FirstAC = AC; 10202 } else if (SecondCand == nullptr) { 10203 SecondCand = I->Function; 10204 SecondAC = AC; 10205 } else { 10206 // We have more than one pair of constrained functions - this check is 10207 // expensive and we'd rather not try to diagnose it. 10208 return; 10209 } 10210 } 10211 if (!SecondCand) 10212 return; 10213 // The diagnostic can only happen if there are associated constraints on 10214 // both sides (there needs to be some identical atomic constraint). 10215 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10216 SecondCand, SecondAC)) 10217 // Just show the user one diagnostic, they'll probably figure it out 10218 // from here. 10219 return; 10220 } 10221 10222 // Notes the location of all overload candidates designated through 10223 // OverloadedExpr 10224 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10225 bool TakingAddress) { 10226 assert(OverloadedExpr->getType() == Context.OverloadTy); 10227 10228 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10229 OverloadExpr *OvlExpr = Ovl.Expression; 10230 10231 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10232 IEnd = OvlExpr->decls_end(); 10233 I != IEnd; ++I) { 10234 if (FunctionTemplateDecl *FunTmpl = 10235 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10236 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10237 TakingAddress); 10238 } else if (FunctionDecl *Fun 10239 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10240 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10241 } 10242 } 10243 } 10244 10245 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10246 /// "lead" diagnostic; it will be given two arguments, the source and 10247 /// target types of the conversion. 10248 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10249 Sema &S, 10250 SourceLocation CaretLoc, 10251 const PartialDiagnostic &PDiag) const { 10252 S.Diag(CaretLoc, PDiag) 10253 << Ambiguous.getFromType() << Ambiguous.getToType(); 10254 // FIXME: The note limiting machinery is borrowed from 10255 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10256 // refactoring here. 10257 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10258 unsigned CandsShown = 0; 10259 AmbiguousConversionSequence::const_iterator I, E; 10260 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10261 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10262 break; 10263 ++CandsShown; 10264 S.NoteOverloadCandidate(I->first, I->second); 10265 } 10266 if (I != E) 10267 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10268 } 10269 10270 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10271 unsigned I, bool TakingCandidateAddress) { 10272 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10273 assert(Conv.isBad()); 10274 assert(Cand->Function && "for now, candidate must be a function"); 10275 FunctionDecl *Fn = Cand->Function; 10276 10277 // There's a conversion slot for the object argument if this is a 10278 // non-constructor method. Note that 'I' corresponds the 10279 // conversion-slot index. 10280 bool isObjectArgument = false; 10281 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10282 if (I == 0) 10283 isObjectArgument = true; 10284 else 10285 I--; 10286 } 10287 10288 std::string FnDesc; 10289 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10290 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10291 FnDesc); 10292 10293 Expr *FromExpr = Conv.Bad.FromExpr; 10294 QualType FromTy = Conv.Bad.getFromType(); 10295 QualType ToTy = Conv.Bad.getToType(); 10296 10297 if (FromTy == S.Context.OverloadTy) { 10298 assert(FromExpr && "overload set argument came from implicit argument?"); 10299 Expr *E = FromExpr->IgnoreParens(); 10300 if (isa<UnaryOperator>(E)) 10301 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10302 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10303 10304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10305 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10306 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10307 << Name << I + 1; 10308 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10309 return; 10310 } 10311 10312 // Do some hand-waving analysis to see if the non-viability is due 10313 // to a qualifier mismatch. 10314 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10315 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10316 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10317 CToTy = RT->getPointeeType(); 10318 else { 10319 // TODO: detect and diagnose the full richness of const mismatches. 10320 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10321 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10322 CFromTy = FromPT->getPointeeType(); 10323 CToTy = ToPT->getPointeeType(); 10324 } 10325 } 10326 10327 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10328 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10329 Qualifiers FromQs = CFromTy.getQualifiers(); 10330 Qualifiers ToQs = CToTy.getQualifiers(); 10331 10332 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10333 if (isObjectArgument) 10334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10335 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10336 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10337 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10338 else 10339 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10340 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10341 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10342 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10343 << ToTy->isReferenceType() << I + 1; 10344 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10345 return; 10346 } 10347 10348 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10350 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10351 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10352 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10353 << (unsigned)isObjectArgument << I + 1; 10354 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10355 return; 10356 } 10357 10358 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10360 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10361 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10362 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10363 << (unsigned)isObjectArgument << I + 1; 10364 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10365 return; 10366 } 10367 10368 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10369 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10370 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10371 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10372 << FromQs.hasUnaligned() << I + 1; 10373 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10374 return; 10375 } 10376 10377 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10378 assert(CVR && "unexpected qualifiers mismatch"); 10379 10380 if (isObjectArgument) { 10381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10382 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10383 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10384 << (CVR - 1); 10385 } else { 10386 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10387 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10388 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10389 << (CVR - 1) << I + 1; 10390 } 10391 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10392 return; 10393 } 10394 10395 // Special diagnostic for failure to convert an initializer list, since 10396 // telling the user that it has type void is not useful. 10397 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10398 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10399 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10400 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10401 << ToTy << (unsigned)isObjectArgument << I + 1; 10402 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10403 return; 10404 } 10405 10406 // Diagnose references or pointers to incomplete types differently, 10407 // since it's far from impossible that the incompleteness triggered 10408 // the failure. 10409 QualType TempFromTy = FromTy.getNonReferenceType(); 10410 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10411 TempFromTy = PTy->getPointeeType(); 10412 if (TempFromTy->isIncompleteType()) { 10413 // Emit the generic diagnostic and, optionally, add the hints to it. 10414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10415 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10416 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10417 << ToTy << (unsigned)isObjectArgument << I + 1 10418 << (unsigned)(Cand->Fix.Kind); 10419 10420 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10421 return; 10422 } 10423 10424 // Diagnose base -> derived pointer conversions. 10425 unsigned BaseToDerivedConversion = 0; 10426 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10427 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10428 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10429 FromPtrTy->getPointeeType()) && 10430 !FromPtrTy->getPointeeType()->isIncompleteType() && 10431 !ToPtrTy->getPointeeType()->isIncompleteType() && 10432 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10433 FromPtrTy->getPointeeType())) 10434 BaseToDerivedConversion = 1; 10435 } 10436 } else if (const ObjCObjectPointerType *FromPtrTy 10437 = FromTy->getAs<ObjCObjectPointerType>()) { 10438 if (const ObjCObjectPointerType *ToPtrTy 10439 = ToTy->getAs<ObjCObjectPointerType>()) 10440 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10441 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10442 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10443 FromPtrTy->getPointeeType()) && 10444 FromIface->isSuperClassOf(ToIface)) 10445 BaseToDerivedConversion = 2; 10446 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10447 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10448 !FromTy->isIncompleteType() && 10449 !ToRefTy->getPointeeType()->isIncompleteType() && 10450 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10451 BaseToDerivedConversion = 3; 10452 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10453 ToTy.getNonReferenceType().getCanonicalType() == 10454 FromTy.getNonReferenceType().getCanonicalType()) { 10455 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10456 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10457 << (unsigned)isObjectArgument << I + 1 10458 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10459 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10460 return; 10461 } 10462 } 10463 10464 if (BaseToDerivedConversion) { 10465 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10466 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10467 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10468 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10469 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10470 return; 10471 } 10472 10473 if (isa<ObjCObjectPointerType>(CFromTy) && 10474 isa<PointerType>(CToTy)) { 10475 Qualifiers FromQs = CFromTy.getQualifiers(); 10476 Qualifiers ToQs = CToTy.getQualifiers(); 10477 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10478 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10479 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10480 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10481 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10482 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10483 return; 10484 } 10485 } 10486 10487 if (TakingCandidateAddress && 10488 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10489 return; 10490 10491 // Emit the generic diagnostic and, optionally, add the hints to it. 10492 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10493 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10494 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10495 << ToTy << (unsigned)isObjectArgument << I + 1 10496 << (unsigned)(Cand->Fix.Kind); 10497 10498 // If we can fix the conversion, suggest the FixIts. 10499 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10500 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10501 FDiag << *HI; 10502 S.Diag(Fn->getLocation(), FDiag); 10503 10504 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10505 } 10506 10507 /// Additional arity mismatch diagnosis specific to a function overload 10508 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10509 /// over a candidate in any candidate set. 10510 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10511 unsigned NumArgs) { 10512 FunctionDecl *Fn = Cand->Function; 10513 unsigned MinParams = Fn->getMinRequiredArguments(); 10514 10515 // With invalid overloaded operators, it's possible that we think we 10516 // have an arity mismatch when in fact it looks like we have the 10517 // right number of arguments, because only overloaded operators have 10518 // the weird behavior of overloading member and non-member functions. 10519 // Just don't report anything. 10520 if (Fn->isInvalidDecl() && 10521 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10522 return true; 10523 10524 if (NumArgs < MinParams) { 10525 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10526 (Cand->FailureKind == ovl_fail_bad_deduction && 10527 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10528 } else { 10529 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10530 (Cand->FailureKind == ovl_fail_bad_deduction && 10531 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10532 } 10533 10534 return false; 10535 } 10536 10537 /// General arity mismatch diagnosis over a candidate in a candidate set. 10538 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10539 unsigned NumFormalArgs) { 10540 assert(isa<FunctionDecl>(D) && 10541 "The templated declaration should at least be a function" 10542 " when diagnosing bad template argument deduction due to too many" 10543 " or too few arguments"); 10544 10545 FunctionDecl *Fn = cast<FunctionDecl>(D); 10546 10547 // TODO: treat calls to a missing default constructor as a special case 10548 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10549 unsigned MinParams = Fn->getMinRequiredArguments(); 10550 10551 // at least / at most / exactly 10552 unsigned mode, modeCount; 10553 if (NumFormalArgs < MinParams) { 10554 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10555 FnTy->isTemplateVariadic()) 10556 mode = 0; // "at least" 10557 else 10558 mode = 2; // "exactly" 10559 modeCount = MinParams; 10560 } else { 10561 if (MinParams != FnTy->getNumParams()) 10562 mode = 1; // "at most" 10563 else 10564 mode = 2; // "exactly" 10565 modeCount = FnTy->getNumParams(); 10566 } 10567 10568 std::string Description; 10569 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10570 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10571 10572 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10574 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10575 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10576 else 10577 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10578 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10579 << Description << mode << modeCount << NumFormalArgs; 10580 10581 MaybeEmitInheritedConstructorNote(S, Found); 10582 } 10583 10584 /// Arity mismatch diagnosis specific to a function overload candidate. 10585 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10586 unsigned NumFormalArgs) { 10587 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10588 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10589 } 10590 10591 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10592 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10593 return TD; 10594 llvm_unreachable("Unsupported: Getting the described template declaration" 10595 " for bad deduction diagnosis"); 10596 } 10597 10598 /// Diagnose a failed template-argument deduction. 10599 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10600 DeductionFailureInfo &DeductionFailure, 10601 unsigned NumArgs, 10602 bool TakingCandidateAddress) { 10603 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10604 NamedDecl *ParamD; 10605 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10606 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10607 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10608 switch (DeductionFailure.Result) { 10609 case Sema::TDK_Success: 10610 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10611 10612 case Sema::TDK_Incomplete: { 10613 assert(ParamD && "no parameter found for incomplete deduction result"); 10614 S.Diag(Templated->getLocation(), 10615 diag::note_ovl_candidate_incomplete_deduction) 10616 << ParamD->getDeclName(); 10617 MaybeEmitInheritedConstructorNote(S, Found); 10618 return; 10619 } 10620 10621 case Sema::TDK_IncompletePack: { 10622 assert(ParamD && "no parameter found for incomplete deduction result"); 10623 S.Diag(Templated->getLocation(), 10624 diag::note_ovl_candidate_incomplete_deduction_pack) 10625 << ParamD->getDeclName() 10626 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10627 << *DeductionFailure.getFirstArg(); 10628 MaybeEmitInheritedConstructorNote(S, Found); 10629 return; 10630 } 10631 10632 case Sema::TDK_Underqualified: { 10633 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10634 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10635 10636 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10637 10638 // Param will have been canonicalized, but it should just be a 10639 // qualified version of ParamD, so move the qualifiers to that. 10640 QualifierCollector Qs; 10641 Qs.strip(Param); 10642 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10643 assert(S.Context.hasSameType(Param, NonCanonParam)); 10644 10645 // Arg has also been canonicalized, but there's nothing we can do 10646 // about that. It also doesn't matter as much, because it won't 10647 // have any template parameters in it (because deduction isn't 10648 // done on dependent types). 10649 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10650 10651 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10652 << ParamD->getDeclName() << Arg << NonCanonParam; 10653 MaybeEmitInheritedConstructorNote(S, Found); 10654 return; 10655 } 10656 10657 case Sema::TDK_Inconsistent: { 10658 assert(ParamD && "no parameter found for inconsistent deduction result"); 10659 int which = 0; 10660 if (isa<TemplateTypeParmDecl>(ParamD)) 10661 which = 0; 10662 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10663 // Deduction might have failed because we deduced arguments of two 10664 // different types for a non-type template parameter. 10665 // FIXME: Use a different TDK value for this. 10666 QualType T1 = 10667 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10668 QualType T2 = 10669 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10670 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10671 S.Diag(Templated->getLocation(), 10672 diag::note_ovl_candidate_inconsistent_deduction_types) 10673 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10674 << *DeductionFailure.getSecondArg() << T2; 10675 MaybeEmitInheritedConstructorNote(S, Found); 10676 return; 10677 } 10678 10679 which = 1; 10680 } else { 10681 which = 2; 10682 } 10683 10684 // Tweak the diagnostic if the problem is that we deduced packs of 10685 // different arities. We'll print the actual packs anyway in case that 10686 // includes additional useful information. 10687 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10688 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10689 DeductionFailure.getFirstArg()->pack_size() != 10690 DeductionFailure.getSecondArg()->pack_size()) { 10691 which = 3; 10692 } 10693 10694 S.Diag(Templated->getLocation(), 10695 diag::note_ovl_candidate_inconsistent_deduction) 10696 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10697 << *DeductionFailure.getSecondArg(); 10698 MaybeEmitInheritedConstructorNote(S, Found); 10699 return; 10700 } 10701 10702 case Sema::TDK_InvalidExplicitArguments: 10703 assert(ParamD && "no parameter found for invalid explicit arguments"); 10704 if (ParamD->getDeclName()) 10705 S.Diag(Templated->getLocation(), 10706 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10707 << ParamD->getDeclName(); 10708 else { 10709 int index = 0; 10710 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10711 index = TTP->getIndex(); 10712 else if (NonTypeTemplateParmDecl *NTTP 10713 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10714 index = NTTP->getIndex(); 10715 else 10716 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10717 S.Diag(Templated->getLocation(), 10718 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10719 << (index + 1); 10720 } 10721 MaybeEmitInheritedConstructorNote(S, Found); 10722 return; 10723 10724 case Sema::TDK_ConstraintsNotSatisfied: { 10725 // Format the template argument list into the argument string. 10726 SmallString<128> TemplateArgString; 10727 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10728 TemplateArgString = " "; 10729 TemplateArgString += S.getTemplateArgumentBindingsText( 10730 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10731 if (TemplateArgString.size() == 1) 10732 TemplateArgString.clear(); 10733 S.Diag(Templated->getLocation(), 10734 diag::note_ovl_candidate_unsatisfied_constraints) 10735 << TemplateArgString; 10736 10737 S.DiagnoseUnsatisfiedConstraint( 10738 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10739 return; 10740 } 10741 case Sema::TDK_TooManyArguments: 10742 case Sema::TDK_TooFewArguments: 10743 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10744 return; 10745 10746 case Sema::TDK_InstantiationDepth: 10747 S.Diag(Templated->getLocation(), 10748 diag::note_ovl_candidate_instantiation_depth); 10749 MaybeEmitInheritedConstructorNote(S, Found); 10750 return; 10751 10752 case Sema::TDK_SubstitutionFailure: { 10753 // Format the template argument list into the argument string. 10754 SmallString<128> TemplateArgString; 10755 if (TemplateArgumentList *Args = 10756 DeductionFailure.getTemplateArgumentList()) { 10757 TemplateArgString = " "; 10758 TemplateArgString += S.getTemplateArgumentBindingsText( 10759 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10760 if (TemplateArgString.size() == 1) 10761 TemplateArgString.clear(); 10762 } 10763 10764 // If this candidate was disabled by enable_if, say so. 10765 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10766 if (PDiag && PDiag->second.getDiagID() == 10767 diag::err_typename_nested_not_found_enable_if) { 10768 // FIXME: Use the source range of the condition, and the fully-qualified 10769 // name of the enable_if template. These are both present in PDiag. 10770 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10771 << "'enable_if'" << TemplateArgString; 10772 return; 10773 } 10774 10775 // We found a specific requirement that disabled the enable_if. 10776 if (PDiag && PDiag->second.getDiagID() == 10777 diag::err_typename_nested_not_found_requirement) { 10778 S.Diag(Templated->getLocation(), 10779 diag::note_ovl_candidate_disabled_by_requirement) 10780 << PDiag->second.getStringArg(0) << TemplateArgString; 10781 return; 10782 } 10783 10784 // Format the SFINAE diagnostic into the argument string. 10785 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10786 // formatted message in another diagnostic. 10787 SmallString<128> SFINAEArgString; 10788 SourceRange R; 10789 if (PDiag) { 10790 SFINAEArgString = ": "; 10791 R = SourceRange(PDiag->first, PDiag->first); 10792 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10793 } 10794 10795 S.Diag(Templated->getLocation(), 10796 diag::note_ovl_candidate_substitution_failure) 10797 << TemplateArgString << SFINAEArgString << R; 10798 MaybeEmitInheritedConstructorNote(S, Found); 10799 return; 10800 } 10801 10802 case Sema::TDK_DeducedMismatch: 10803 case Sema::TDK_DeducedMismatchNested: { 10804 // Format the template argument list into the argument string. 10805 SmallString<128> TemplateArgString; 10806 if (TemplateArgumentList *Args = 10807 DeductionFailure.getTemplateArgumentList()) { 10808 TemplateArgString = " "; 10809 TemplateArgString += S.getTemplateArgumentBindingsText( 10810 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10811 if (TemplateArgString.size() == 1) 10812 TemplateArgString.clear(); 10813 } 10814 10815 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10816 << (*DeductionFailure.getCallArgIndex() + 1) 10817 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10818 << TemplateArgString 10819 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10820 break; 10821 } 10822 10823 case Sema::TDK_NonDeducedMismatch: { 10824 // FIXME: Provide a source location to indicate what we couldn't match. 10825 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10826 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10827 if (FirstTA.getKind() == TemplateArgument::Template && 10828 SecondTA.getKind() == TemplateArgument::Template) { 10829 TemplateName FirstTN = FirstTA.getAsTemplate(); 10830 TemplateName SecondTN = SecondTA.getAsTemplate(); 10831 if (FirstTN.getKind() == TemplateName::Template && 10832 SecondTN.getKind() == TemplateName::Template) { 10833 if (FirstTN.getAsTemplateDecl()->getName() == 10834 SecondTN.getAsTemplateDecl()->getName()) { 10835 // FIXME: This fixes a bad diagnostic where both templates are named 10836 // the same. This particular case is a bit difficult since: 10837 // 1) It is passed as a string to the diagnostic printer. 10838 // 2) The diagnostic printer only attempts to find a better 10839 // name for types, not decls. 10840 // Ideally, this should folded into the diagnostic printer. 10841 S.Diag(Templated->getLocation(), 10842 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10843 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10844 return; 10845 } 10846 } 10847 } 10848 10849 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10850 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10851 return; 10852 10853 // FIXME: For generic lambda parameters, check if the function is a lambda 10854 // call operator, and if so, emit a prettier and more informative 10855 // diagnostic that mentions 'auto' and lambda in addition to 10856 // (or instead of?) the canonical template type parameters. 10857 S.Diag(Templated->getLocation(), 10858 diag::note_ovl_candidate_non_deduced_mismatch) 10859 << FirstTA << SecondTA; 10860 return; 10861 } 10862 // TODO: diagnose these individually, then kill off 10863 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10864 case Sema::TDK_MiscellaneousDeductionFailure: 10865 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10866 MaybeEmitInheritedConstructorNote(S, Found); 10867 return; 10868 case Sema::TDK_CUDATargetMismatch: 10869 S.Diag(Templated->getLocation(), 10870 diag::note_cuda_ovl_candidate_target_mismatch); 10871 return; 10872 } 10873 } 10874 10875 /// Diagnose a failed template-argument deduction, for function calls. 10876 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10877 unsigned NumArgs, 10878 bool TakingCandidateAddress) { 10879 unsigned TDK = Cand->DeductionFailure.Result; 10880 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10881 if (CheckArityMismatch(S, Cand, NumArgs)) 10882 return; 10883 } 10884 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10885 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10886 } 10887 10888 /// CUDA: diagnose an invalid call across targets. 10889 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10890 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10891 FunctionDecl *Callee = Cand->Function; 10892 10893 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10894 CalleeTarget = S.IdentifyCUDATarget(Callee); 10895 10896 std::string FnDesc; 10897 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10898 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10899 Cand->getRewriteKind(), FnDesc); 10900 10901 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10902 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10903 << FnDesc /* Ignored */ 10904 << CalleeTarget << CallerTarget; 10905 10906 // This could be an implicit constructor for which we could not infer the 10907 // target due to a collsion. Diagnose that case. 10908 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10909 if (Meth != nullptr && Meth->isImplicit()) { 10910 CXXRecordDecl *ParentClass = Meth->getParent(); 10911 Sema::CXXSpecialMember CSM; 10912 10913 switch (FnKindPair.first) { 10914 default: 10915 return; 10916 case oc_implicit_default_constructor: 10917 CSM = Sema::CXXDefaultConstructor; 10918 break; 10919 case oc_implicit_copy_constructor: 10920 CSM = Sema::CXXCopyConstructor; 10921 break; 10922 case oc_implicit_move_constructor: 10923 CSM = Sema::CXXMoveConstructor; 10924 break; 10925 case oc_implicit_copy_assignment: 10926 CSM = Sema::CXXCopyAssignment; 10927 break; 10928 case oc_implicit_move_assignment: 10929 CSM = Sema::CXXMoveAssignment; 10930 break; 10931 }; 10932 10933 bool ConstRHS = false; 10934 if (Meth->getNumParams()) { 10935 if (const ReferenceType *RT = 10936 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10937 ConstRHS = RT->getPointeeType().isConstQualified(); 10938 } 10939 } 10940 10941 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10942 /* ConstRHS */ ConstRHS, 10943 /* Diagnose */ true); 10944 } 10945 } 10946 10947 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10948 FunctionDecl *Callee = Cand->Function; 10949 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10950 10951 S.Diag(Callee->getLocation(), 10952 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10953 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10954 } 10955 10956 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10957 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10958 assert(ES.isExplicit() && "not an explicit candidate"); 10959 10960 unsigned Kind; 10961 switch (Cand->Function->getDeclKind()) { 10962 case Decl::Kind::CXXConstructor: 10963 Kind = 0; 10964 break; 10965 case Decl::Kind::CXXConversion: 10966 Kind = 1; 10967 break; 10968 case Decl::Kind::CXXDeductionGuide: 10969 Kind = Cand->Function->isImplicit() ? 0 : 2; 10970 break; 10971 default: 10972 llvm_unreachable("invalid Decl"); 10973 } 10974 10975 // Note the location of the first (in-class) declaration; a redeclaration 10976 // (particularly an out-of-class definition) will typically lack the 10977 // 'explicit' specifier. 10978 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10979 FunctionDecl *First = Cand->Function->getFirstDecl(); 10980 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10981 First = Pattern->getFirstDecl(); 10982 10983 S.Diag(First->getLocation(), 10984 diag::note_ovl_candidate_explicit) 10985 << Kind << (ES.getExpr() ? 1 : 0) 10986 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10987 } 10988 10989 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10990 FunctionDecl *Callee = Cand->Function; 10991 10992 S.Diag(Callee->getLocation(), 10993 diag::note_ovl_candidate_disabled_by_extension) 10994 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10995 } 10996 10997 /// Generates a 'note' diagnostic for an overload candidate. We've 10998 /// already generated a primary error at the call site. 10999 /// 11000 /// It really does need to be a single diagnostic with its caret 11001 /// pointed at the candidate declaration. Yes, this creates some 11002 /// major challenges of technical writing. Yes, this makes pointing 11003 /// out problems with specific arguments quite awkward. It's still 11004 /// better than generating twenty screens of text for every failed 11005 /// overload. 11006 /// 11007 /// It would be great to be able to express per-candidate problems 11008 /// more richly for those diagnostic clients that cared, but we'd 11009 /// still have to be just as careful with the default diagnostics. 11010 /// \param CtorDestAS Addr space of object being constructed (for ctor 11011 /// candidates only). 11012 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11013 unsigned NumArgs, 11014 bool TakingCandidateAddress, 11015 LangAS CtorDestAS = LangAS::Default) { 11016 FunctionDecl *Fn = Cand->Function; 11017 11018 // Note deleted candidates, but only if they're viable. 11019 if (Cand->Viable) { 11020 if (Fn->isDeleted()) { 11021 std::string FnDesc; 11022 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11023 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11024 Cand->getRewriteKind(), FnDesc); 11025 11026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11027 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11028 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11029 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11030 return; 11031 } 11032 11033 // We don't really have anything else to say about viable candidates. 11034 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11035 return; 11036 } 11037 11038 switch (Cand->FailureKind) { 11039 case ovl_fail_too_many_arguments: 11040 case ovl_fail_too_few_arguments: 11041 return DiagnoseArityMismatch(S, Cand, NumArgs); 11042 11043 case ovl_fail_bad_deduction: 11044 return DiagnoseBadDeduction(S, Cand, NumArgs, 11045 TakingCandidateAddress); 11046 11047 case ovl_fail_illegal_constructor: { 11048 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11049 << (Fn->getPrimaryTemplate() ? 1 : 0); 11050 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11051 return; 11052 } 11053 11054 case ovl_fail_object_addrspace_mismatch: { 11055 Qualifiers QualsForPrinting; 11056 QualsForPrinting.setAddressSpace(CtorDestAS); 11057 S.Diag(Fn->getLocation(), 11058 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11059 << QualsForPrinting; 11060 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11061 return; 11062 } 11063 11064 case ovl_fail_trivial_conversion: 11065 case ovl_fail_bad_final_conversion: 11066 case ovl_fail_final_conversion_not_exact: 11067 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11068 11069 case ovl_fail_bad_conversion: { 11070 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11071 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11072 if (Cand->Conversions[I].isBad()) 11073 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11074 11075 // FIXME: this currently happens when we're called from SemaInit 11076 // when user-conversion overload fails. Figure out how to handle 11077 // those conditions and diagnose them well. 11078 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11079 } 11080 11081 case ovl_fail_bad_target: 11082 return DiagnoseBadTarget(S, Cand); 11083 11084 case ovl_fail_enable_if: 11085 return DiagnoseFailedEnableIfAttr(S, Cand); 11086 11087 case ovl_fail_explicit: 11088 return DiagnoseFailedExplicitSpec(S, Cand); 11089 11090 case ovl_fail_ext_disabled: 11091 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11092 11093 case ovl_fail_inhctor_slice: 11094 // It's generally not interesting to note copy/move constructors here. 11095 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11096 return; 11097 S.Diag(Fn->getLocation(), 11098 diag::note_ovl_candidate_inherited_constructor_slice) 11099 << (Fn->getPrimaryTemplate() ? 1 : 0) 11100 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11101 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11102 return; 11103 11104 case ovl_fail_addr_not_available: { 11105 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11106 (void)Available; 11107 assert(!Available); 11108 break; 11109 } 11110 case ovl_non_default_multiversion_function: 11111 // Do nothing, these should simply be ignored. 11112 break; 11113 11114 case ovl_fail_constraints_not_satisfied: { 11115 std::string FnDesc; 11116 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11117 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11118 Cand->getRewriteKind(), FnDesc); 11119 11120 S.Diag(Fn->getLocation(), 11121 diag::note_ovl_candidate_constraints_not_satisfied) 11122 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11123 << FnDesc /* Ignored */; 11124 ConstraintSatisfaction Satisfaction; 11125 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11126 break; 11127 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11128 } 11129 } 11130 } 11131 11132 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11133 // Desugar the type of the surrogate down to a function type, 11134 // retaining as many typedefs as possible while still showing 11135 // the function type (and, therefore, its parameter types). 11136 QualType FnType = Cand->Surrogate->getConversionType(); 11137 bool isLValueReference = false; 11138 bool isRValueReference = false; 11139 bool isPointer = false; 11140 if (const LValueReferenceType *FnTypeRef = 11141 FnType->getAs<LValueReferenceType>()) { 11142 FnType = FnTypeRef->getPointeeType(); 11143 isLValueReference = true; 11144 } else if (const RValueReferenceType *FnTypeRef = 11145 FnType->getAs<RValueReferenceType>()) { 11146 FnType = FnTypeRef->getPointeeType(); 11147 isRValueReference = true; 11148 } 11149 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11150 FnType = FnTypePtr->getPointeeType(); 11151 isPointer = true; 11152 } 11153 // Desugar down to a function type. 11154 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11155 // Reconstruct the pointer/reference as appropriate. 11156 if (isPointer) FnType = S.Context.getPointerType(FnType); 11157 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11158 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11159 11160 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11161 << FnType; 11162 } 11163 11164 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11165 SourceLocation OpLoc, 11166 OverloadCandidate *Cand) { 11167 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11168 std::string TypeStr("operator"); 11169 TypeStr += Opc; 11170 TypeStr += "("; 11171 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11172 if (Cand->Conversions.size() == 1) { 11173 TypeStr += ")"; 11174 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11175 } else { 11176 TypeStr += ", "; 11177 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11178 TypeStr += ")"; 11179 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11180 } 11181 } 11182 11183 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11184 OverloadCandidate *Cand) { 11185 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11186 if (ICS.isBad()) break; // all meaningless after first invalid 11187 if (!ICS.isAmbiguous()) continue; 11188 11189 ICS.DiagnoseAmbiguousConversion( 11190 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11191 } 11192 } 11193 11194 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11195 if (Cand->Function) 11196 return Cand->Function->getLocation(); 11197 if (Cand->IsSurrogate) 11198 return Cand->Surrogate->getLocation(); 11199 return SourceLocation(); 11200 } 11201 11202 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11203 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11204 case Sema::TDK_Success: 11205 case Sema::TDK_NonDependentConversionFailure: 11206 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11207 11208 case Sema::TDK_Invalid: 11209 case Sema::TDK_Incomplete: 11210 case Sema::TDK_IncompletePack: 11211 return 1; 11212 11213 case Sema::TDK_Underqualified: 11214 case Sema::TDK_Inconsistent: 11215 return 2; 11216 11217 case Sema::TDK_SubstitutionFailure: 11218 case Sema::TDK_DeducedMismatch: 11219 case Sema::TDK_ConstraintsNotSatisfied: 11220 case Sema::TDK_DeducedMismatchNested: 11221 case Sema::TDK_NonDeducedMismatch: 11222 case Sema::TDK_MiscellaneousDeductionFailure: 11223 case Sema::TDK_CUDATargetMismatch: 11224 return 3; 11225 11226 case Sema::TDK_InstantiationDepth: 11227 return 4; 11228 11229 case Sema::TDK_InvalidExplicitArguments: 11230 return 5; 11231 11232 case Sema::TDK_TooManyArguments: 11233 case Sema::TDK_TooFewArguments: 11234 return 6; 11235 } 11236 llvm_unreachable("Unhandled deduction result"); 11237 } 11238 11239 namespace { 11240 struct CompareOverloadCandidatesForDisplay { 11241 Sema &S; 11242 SourceLocation Loc; 11243 size_t NumArgs; 11244 OverloadCandidateSet::CandidateSetKind CSK; 11245 11246 CompareOverloadCandidatesForDisplay( 11247 Sema &S, SourceLocation Loc, size_t NArgs, 11248 OverloadCandidateSet::CandidateSetKind CSK) 11249 : S(S), NumArgs(NArgs), CSK(CSK) {} 11250 11251 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11252 // If there are too many or too few arguments, that's the high-order bit we 11253 // want to sort by, even if the immediate failure kind was something else. 11254 if (C->FailureKind == ovl_fail_too_many_arguments || 11255 C->FailureKind == ovl_fail_too_few_arguments) 11256 return static_cast<OverloadFailureKind>(C->FailureKind); 11257 11258 if (C->Function) { 11259 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11260 return ovl_fail_too_many_arguments; 11261 if (NumArgs < C->Function->getMinRequiredArguments()) 11262 return ovl_fail_too_few_arguments; 11263 } 11264 11265 return static_cast<OverloadFailureKind>(C->FailureKind); 11266 } 11267 11268 bool operator()(const OverloadCandidate *L, 11269 const OverloadCandidate *R) { 11270 // Fast-path this check. 11271 if (L == R) return false; 11272 11273 // Order first by viability. 11274 if (L->Viable) { 11275 if (!R->Viable) return true; 11276 11277 // TODO: introduce a tri-valued comparison for overload 11278 // candidates. Would be more worthwhile if we had a sort 11279 // that could exploit it. 11280 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11281 return true; 11282 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11283 return false; 11284 } else if (R->Viable) 11285 return false; 11286 11287 assert(L->Viable == R->Viable); 11288 11289 // Criteria by which we can sort non-viable candidates: 11290 if (!L->Viable) { 11291 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11292 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11293 11294 // 1. Arity mismatches come after other candidates. 11295 if (LFailureKind == ovl_fail_too_many_arguments || 11296 LFailureKind == ovl_fail_too_few_arguments) { 11297 if (RFailureKind == ovl_fail_too_many_arguments || 11298 RFailureKind == ovl_fail_too_few_arguments) { 11299 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11300 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11301 if (LDist == RDist) { 11302 if (LFailureKind == RFailureKind) 11303 // Sort non-surrogates before surrogates. 11304 return !L->IsSurrogate && R->IsSurrogate; 11305 // Sort candidates requiring fewer parameters than there were 11306 // arguments given after candidates requiring more parameters 11307 // than there were arguments given. 11308 return LFailureKind == ovl_fail_too_many_arguments; 11309 } 11310 return LDist < RDist; 11311 } 11312 return false; 11313 } 11314 if (RFailureKind == ovl_fail_too_many_arguments || 11315 RFailureKind == ovl_fail_too_few_arguments) 11316 return true; 11317 11318 // 2. Bad conversions come first and are ordered by the number 11319 // of bad conversions and quality of good conversions. 11320 if (LFailureKind == ovl_fail_bad_conversion) { 11321 if (RFailureKind != ovl_fail_bad_conversion) 11322 return true; 11323 11324 // The conversion that can be fixed with a smaller number of changes, 11325 // comes first. 11326 unsigned numLFixes = L->Fix.NumConversionsFixed; 11327 unsigned numRFixes = R->Fix.NumConversionsFixed; 11328 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11329 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11330 if (numLFixes != numRFixes) { 11331 return numLFixes < numRFixes; 11332 } 11333 11334 // If there's any ordering between the defined conversions... 11335 // FIXME: this might not be transitive. 11336 assert(L->Conversions.size() == R->Conversions.size()); 11337 11338 int leftBetter = 0; 11339 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11340 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11341 switch (CompareImplicitConversionSequences(S, Loc, 11342 L->Conversions[I], 11343 R->Conversions[I])) { 11344 case ImplicitConversionSequence::Better: 11345 leftBetter++; 11346 break; 11347 11348 case ImplicitConversionSequence::Worse: 11349 leftBetter--; 11350 break; 11351 11352 case ImplicitConversionSequence::Indistinguishable: 11353 break; 11354 } 11355 } 11356 if (leftBetter > 0) return true; 11357 if (leftBetter < 0) return false; 11358 11359 } else if (RFailureKind == ovl_fail_bad_conversion) 11360 return false; 11361 11362 if (LFailureKind == ovl_fail_bad_deduction) { 11363 if (RFailureKind != ovl_fail_bad_deduction) 11364 return true; 11365 11366 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11367 return RankDeductionFailure(L->DeductionFailure) 11368 < RankDeductionFailure(R->DeductionFailure); 11369 } else if (RFailureKind == ovl_fail_bad_deduction) 11370 return false; 11371 11372 // TODO: others? 11373 } 11374 11375 // Sort everything else by location. 11376 SourceLocation LLoc = GetLocationForCandidate(L); 11377 SourceLocation RLoc = GetLocationForCandidate(R); 11378 11379 // Put candidates without locations (e.g. builtins) at the end. 11380 if (LLoc.isInvalid()) return false; 11381 if (RLoc.isInvalid()) return true; 11382 11383 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11384 } 11385 }; 11386 } 11387 11388 /// CompleteNonViableCandidate - Normally, overload resolution only 11389 /// computes up to the first bad conversion. Produces the FixIt set if 11390 /// possible. 11391 static void 11392 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11393 ArrayRef<Expr *> Args, 11394 OverloadCandidateSet::CandidateSetKind CSK) { 11395 assert(!Cand->Viable); 11396 11397 // Don't do anything on failures other than bad conversion. 11398 if (Cand->FailureKind != ovl_fail_bad_conversion) 11399 return; 11400 11401 // We only want the FixIts if all the arguments can be corrected. 11402 bool Unfixable = false; 11403 // Use a implicit copy initialization to check conversion fixes. 11404 Cand->Fix.setConversionChecker(TryCopyInitialization); 11405 11406 // Attempt to fix the bad conversion. 11407 unsigned ConvCount = Cand->Conversions.size(); 11408 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11409 ++ConvIdx) { 11410 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11411 if (Cand->Conversions[ConvIdx].isInitialized() && 11412 Cand->Conversions[ConvIdx].isBad()) { 11413 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11414 break; 11415 } 11416 } 11417 11418 // FIXME: this should probably be preserved from the overload 11419 // operation somehow. 11420 bool SuppressUserConversions = false; 11421 11422 unsigned ConvIdx = 0; 11423 unsigned ArgIdx = 0; 11424 ArrayRef<QualType> ParamTypes; 11425 bool Reversed = Cand->isReversed(); 11426 11427 if (Cand->IsSurrogate) { 11428 QualType ConvType 11429 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11430 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11431 ConvType = ConvPtrType->getPointeeType(); 11432 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11433 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11434 ConvIdx = 1; 11435 } else if (Cand->Function) { 11436 ParamTypes = 11437 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11438 if (isa<CXXMethodDecl>(Cand->Function) && 11439 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11440 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11441 ConvIdx = 1; 11442 if (CSK == OverloadCandidateSet::CSK_Operator && 11443 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11444 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11445 ArgIdx = 1; 11446 } 11447 } else { 11448 // Builtin operator. 11449 assert(ConvCount <= 3); 11450 ParamTypes = Cand->BuiltinParamTypes; 11451 } 11452 11453 // Fill in the rest of the conversions. 11454 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11455 ConvIdx != ConvCount; 11456 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11457 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11458 if (Cand->Conversions[ConvIdx].isInitialized()) { 11459 // We've already checked this conversion. 11460 } else if (ParamIdx < ParamTypes.size()) { 11461 if (ParamTypes[ParamIdx]->isDependentType()) 11462 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11463 Args[ArgIdx]->getType()); 11464 else { 11465 Cand->Conversions[ConvIdx] = 11466 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11467 SuppressUserConversions, 11468 /*InOverloadResolution=*/true, 11469 /*AllowObjCWritebackConversion=*/ 11470 S.getLangOpts().ObjCAutoRefCount); 11471 // Store the FixIt in the candidate if it exists. 11472 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11473 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11474 } 11475 } else 11476 Cand->Conversions[ConvIdx].setEllipsis(); 11477 } 11478 } 11479 11480 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11481 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11482 SourceLocation OpLoc, 11483 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11484 // Sort the candidates by viability and position. Sorting directly would 11485 // be prohibitive, so we make a set of pointers and sort those. 11486 SmallVector<OverloadCandidate*, 32> Cands; 11487 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11488 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11489 if (!Filter(*Cand)) 11490 continue; 11491 switch (OCD) { 11492 case OCD_AllCandidates: 11493 if (!Cand->Viable) { 11494 if (!Cand->Function && !Cand->IsSurrogate) { 11495 // This a non-viable builtin candidate. We do not, in general, 11496 // want to list every possible builtin candidate. 11497 continue; 11498 } 11499 CompleteNonViableCandidate(S, Cand, Args, Kind); 11500 } 11501 break; 11502 11503 case OCD_ViableCandidates: 11504 if (!Cand->Viable) 11505 continue; 11506 break; 11507 11508 case OCD_AmbiguousCandidates: 11509 if (!Cand->Best) 11510 continue; 11511 break; 11512 } 11513 11514 Cands.push_back(Cand); 11515 } 11516 11517 llvm::stable_sort( 11518 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11519 11520 return Cands; 11521 } 11522 11523 /// When overload resolution fails, prints diagnostic messages containing the 11524 /// candidates in the candidate set. 11525 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11526 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11527 StringRef Opc, SourceLocation OpLoc, 11528 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11529 11530 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11531 11532 S.Diag(PD.first, PD.second); 11533 11534 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11535 11536 if (OCD == OCD_AmbiguousCandidates) 11537 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11538 } 11539 11540 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11541 ArrayRef<OverloadCandidate *> Cands, 11542 StringRef Opc, SourceLocation OpLoc) { 11543 bool ReportedAmbiguousConversions = false; 11544 11545 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11546 unsigned CandsShown = 0; 11547 auto I = Cands.begin(), E = Cands.end(); 11548 for (; I != E; ++I) { 11549 OverloadCandidate *Cand = *I; 11550 11551 // Set an arbitrary limit on the number of candidate functions we'll spam 11552 // the user with. FIXME: This limit should depend on details of the 11553 // candidate list. 11554 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11555 break; 11556 } 11557 ++CandsShown; 11558 11559 if (Cand->Function) 11560 NoteFunctionCandidate(S, Cand, Args.size(), 11561 /*TakingCandidateAddress=*/false, DestAS); 11562 else if (Cand->IsSurrogate) 11563 NoteSurrogateCandidate(S, Cand); 11564 else { 11565 assert(Cand->Viable && 11566 "Non-viable built-in candidates are not added to Cands."); 11567 // Generally we only see ambiguities including viable builtin 11568 // operators if overload resolution got screwed up by an 11569 // ambiguous user-defined conversion. 11570 // 11571 // FIXME: It's quite possible for different conversions to see 11572 // different ambiguities, though. 11573 if (!ReportedAmbiguousConversions) { 11574 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11575 ReportedAmbiguousConversions = true; 11576 } 11577 11578 // If this is a viable builtin, print it. 11579 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11580 } 11581 } 11582 11583 if (I != E) 11584 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11585 } 11586 11587 static SourceLocation 11588 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11589 return Cand->Specialization ? Cand->Specialization->getLocation() 11590 : SourceLocation(); 11591 } 11592 11593 namespace { 11594 struct CompareTemplateSpecCandidatesForDisplay { 11595 Sema &S; 11596 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11597 11598 bool operator()(const TemplateSpecCandidate *L, 11599 const TemplateSpecCandidate *R) { 11600 // Fast-path this check. 11601 if (L == R) 11602 return false; 11603 11604 // Assuming that both candidates are not matches... 11605 11606 // Sort by the ranking of deduction failures. 11607 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11608 return RankDeductionFailure(L->DeductionFailure) < 11609 RankDeductionFailure(R->DeductionFailure); 11610 11611 // Sort everything else by location. 11612 SourceLocation LLoc = GetLocationForCandidate(L); 11613 SourceLocation RLoc = GetLocationForCandidate(R); 11614 11615 // Put candidates without locations (e.g. builtins) at the end. 11616 if (LLoc.isInvalid()) 11617 return false; 11618 if (RLoc.isInvalid()) 11619 return true; 11620 11621 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11622 } 11623 }; 11624 } 11625 11626 /// Diagnose a template argument deduction failure. 11627 /// We are treating these failures as overload failures due to bad 11628 /// deductions. 11629 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11630 bool ForTakingAddress) { 11631 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11632 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11633 } 11634 11635 void TemplateSpecCandidateSet::destroyCandidates() { 11636 for (iterator i = begin(), e = end(); i != e; ++i) { 11637 i->DeductionFailure.Destroy(); 11638 } 11639 } 11640 11641 void TemplateSpecCandidateSet::clear() { 11642 destroyCandidates(); 11643 Candidates.clear(); 11644 } 11645 11646 /// NoteCandidates - When no template specialization match is found, prints 11647 /// diagnostic messages containing the non-matching specializations that form 11648 /// the candidate set. 11649 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11650 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11651 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11652 // Sort the candidates by position (assuming no candidate is a match). 11653 // Sorting directly would be prohibitive, so we make a set of pointers 11654 // and sort those. 11655 SmallVector<TemplateSpecCandidate *, 32> Cands; 11656 Cands.reserve(size()); 11657 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11658 if (Cand->Specialization) 11659 Cands.push_back(Cand); 11660 // Otherwise, this is a non-matching builtin candidate. We do not, 11661 // in general, want to list every possible builtin candidate. 11662 } 11663 11664 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11665 11666 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11667 // for generalization purposes (?). 11668 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11669 11670 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11671 unsigned CandsShown = 0; 11672 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11673 TemplateSpecCandidate *Cand = *I; 11674 11675 // Set an arbitrary limit on the number of candidates we'll spam 11676 // the user with. FIXME: This limit should depend on details of the 11677 // candidate list. 11678 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11679 break; 11680 ++CandsShown; 11681 11682 assert(Cand->Specialization && 11683 "Non-matching built-in candidates are not added to Cands."); 11684 Cand->NoteDeductionFailure(S, ForTakingAddress); 11685 } 11686 11687 if (I != E) 11688 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11689 } 11690 11691 // [PossiblyAFunctionType] --> [Return] 11692 // NonFunctionType --> NonFunctionType 11693 // R (A) --> R(A) 11694 // R (*)(A) --> R (A) 11695 // R (&)(A) --> R (A) 11696 // R (S::*)(A) --> R (A) 11697 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11698 QualType Ret = PossiblyAFunctionType; 11699 if (const PointerType *ToTypePtr = 11700 PossiblyAFunctionType->getAs<PointerType>()) 11701 Ret = ToTypePtr->getPointeeType(); 11702 else if (const ReferenceType *ToTypeRef = 11703 PossiblyAFunctionType->getAs<ReferenceType>()) 11704 Ret = ToTypeRef->getPointeeType(); 11705 else if (const MemberPointerType *MemTypePtr = 11706 PossiblyAFunctionType->getAs<MemberPointerType>()) 11707 Ret = MemTypePtr->getPointeeType(); 11708 Ret = 11709 Context.getCanonicalType(Ret).getUnqualifiedType(); 11710 return Ret; 11711 } 11712 11713 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11714 bool Complain = true) { 11715 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11716 S.DeduceReturnType(FD, Loc, Complain)) 11717 return true; 11718 11719 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11720 if (S.getLangOpts().CPlusPlus17 && 11721 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11722 !S.ResolveExceptionSpec(Loc, FPT)) 11723 return true; 11724 11725 return false; 11726 } 11727 11728 namespace { 11729 // A helper class to help with address of function resolution 11730 // - allows us to avoid passing around all those ugly parameters 11731 class AddressOfFunctionResolver { 11732 Sema& S; 11733 Expr* SourceExpr; 11734 const QualType& TargetType; 11735 QualType TargetFunctionType; // Extracted function type from target type 11736 11737 bool Complain; 11738 //DeclAccessPair& ResultFunctionAccessPair; 11739 ASTContext& Context; 11740 11741 bool TargetTypeIsNonStaticMemberFunction; 11742 bool FoundNonTemplateFunction; 11743 bool StaticMemberFunctionFromBoundPointer; 11744 bool HasComplained; 11745 11746 OverloadExpr::FindResult OvlExprInfo; 11747 OverloadExpr *OvlExpr; 11748 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11749 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11750 TemplateSpecCandidateSet FailedCandidates; 11751 11752 public: 11753 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11754 const QualType &TargetType, bool Complain) 11755 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11756 Complain(Complain), Context(S.getASTContext()), 11757 TargetTypeIsNonStaticMemberFunction( 11758 !!TargetType->getAs<MemberPointerType>()), 11759 FoundNonTemplateFunction(false), 11760 StaticMemberFunctionFromBoundPointer(false), 11761 HasComplained(false), 11762 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11763 OvlExpr(OvlExprInfo.Expression), 11764 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11765 ExtractUnqualifiedFunctionTypeFromTargetType(); 11766 11767 if (TargetFunctionType->isFunctionType()) { 11768 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11769 if (!UME->isImplicitAccess() && 11770 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11771 StaticMemberFunctionFromBoundPointer = true; 11772 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11773 DeclAccessPair dap; 11774 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11775 OvlExpr, false, &dap)) { 11776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11777 if (!Method->isStatic()) { 11778 // If the target type is a non-function type and the function found 11779 // is a non-static member function, pretend as if that was the 11780 // target, it's the only possible type to end up with. 11781 TargetTypeIsNonStaticMemberFunction = true; 11782 11783 // And skip adding the function if its not in the proper form. 11784 // We'll diagnose this due to an empty set of functions. 11785 if (!OvlExprInfo.HasFormOfMemberPointer) 11786 return; 11787 } 11788 11789 Matches.push_back(std::make_pair(dap, Fn)); 11790 } 11791 return; 11792 } 11793 11794 if (OvlExpr->hasExplicitTemplateArgs()) 11795 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11796 11797 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11798 // C++ [over.over]p4: 11799 // If more than one function is selected, [...] 11800 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11801 if (FoundNonTemplateFunction) 11802 EliminateAllTemplateMatches(); 11803 else 11804 EliminateAllExceptMostSpecializedTemplate(); 11805 } 11806 } 11807 11808 if (S.getLangOpts().CUDA && Matches.size() > 1) 11809 EliminateSuboptimalCudaMatches(); 11810 } 11811 11812 bool hasComplained() const { return HasComplained; } 11813 11814 private: 11815 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11816 QualType Discard; 11817 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11818 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11819 } 11820 11821 /// \return true if A is considered a better overload candidate for the 11822 /// desired type than B. 11823 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11824 // If A doesn't have exactly the correct type, we don't want to classify it 11825 // as "better" than anything else. This way, the user is required to 11826 // disambiguate for us if there are multiple candidates and no exact match. 11827 return candidateHasExactlyCorrectType(A) && 11828 (!candidateHasExactlyCorrectType(B) || 11829 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11830 } 11831 11832 /// \return true if we were able to eliminate all but one overload candidate, 11833 /// false otherwise. 11834 bool eliminiateSuboptimalOverloadCandidates() { 11835 // Same algorithm as overload resolution -- one pass to pick the "best", 11836 // another pass to be sure that nothing is better than the best. 11837 auto Best = Matches.begin(); 11838 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11839 if (isBetterCandidate(I->second, Best->second)) 11840 Best = I; 11841 11842 const FunctionDecl *BestFn = Best->second; 11843 auto IsBestOrInferiorToBest = [this, BestFn]( 11844 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11845 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11846 }; 11847 11848 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11849 // option, so we can potentially give the user a better error 11850 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11851 return false; 11852 Matches[0] = *Best; 11853 Matches.resize(1); 11854 return true; 11855 } 11856 11857 bool isTargetTypeAFunction() const { 11858 return TargetFunctionType->isFunctionType(); 11859 } 11860 11861 // [ToType] [Return] 11862 11863 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11864 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11865 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11866 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11867 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11868 } 11869 11870 // return true if any matching specializations were found 11871 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11872 const DeclAccessPair& CurAccessFunPair) { 11873 if (CXXMethodDecl *Method 11874 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11875 // Skip non-static function templates when converting to pointer, and 11876 // static when converting to member pointer. 11877 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11878 return false; 11879 } 11880 else if (TargetTypeIsNonStaticMemberFunction) 11881 return false; 11882 11883 // C++ [over.over]p2: 11884 // If the name is a function template, template argument deduction is 11885 // done (14.8.2.2), and if the argument deduction succeeds, the 11886 // resulting template argument list is used to generate a single 11887 // function template specialization, which is added to the set of 11888 // overloaded functions considered. 11889 FunctionDecl *Specialization = nullptr; 11890 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11891 if (Sema::TemplateDeductionResult Result 11892 = S.DeduceTemplateArguments(FunctionTemplate, 11893 &OvlExplicitTemplateArgs, 11894 TargetFunctionType, Specialization, 11895 Info, /*IsAddressOfFunction*/true)) { 11896 // Make a note of the failed deduction for diagnostics. 11897 FailedCandidates.addCandidate() 11898 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11899 MakeDeductionFailureInfo(Context, Result, Info)); 11900 return false; 11901 } 11902 11903 // Template argument deduction ensures that we have an exact match or 11904 // compatible pointer-to-function arguments that would be adjusted by ICS. 11905 // This function template specicalization works. 11906 assert(S.isSameOrCompatibleFunctionType( 11907 Context.getCanonicalType(Specialization->getType()), 11908 Context.getCanonicalType(TargetFunctionType))); 11909 11910 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11911 return false; 11912 11913 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11914 return true; 11915 } 11916 11917 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11918 const DeclAccessPair& CurAccessFunPair) { 11919 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11920 // Skip non-static functions when converting to pointer, and static 11921 // when converting to member pointer. 11922 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11923 return false; 11924 } 11925 else if (TargetTypeIsNonStaticMemberFunction) 11926 return false; 11927 11928 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11929 if (S.getLangOpts().CUDA) 11930 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11931 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11932 return false; 11933 if (FunDecl->isMultiVersion()) { 11934 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11935 if (TA && !TA->isDefaultVersion()) 11936 return false; 11937 } 11938 11939 // If any candidate has a placeholder return type, trigger its deduction 11940 // now. 11941 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11942 Complain)) { 11943 HasComplained |= Complain; 11944 return false; 11945 } 11946 11947 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11948 return false; 11949 11950 // If we're in C, we need to support types that aren't exactly identical. 11951 if (!S.getLangOpts().CPlusPlus || 11952 candidateHasExactlyCorrectType(FunDecl)) { 11953 Matches.push_back(std::make_pair( 11954 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11955 FoundNonTemplateFunction = true; 11956 return true; 11957 } 11958 } 11959 11960 return false; 11961 } 11962 11963 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11964 bool Ret = false; 11965 11966 // If the overload expression doesn't have the form of a pointer to 11967 // member, don't try to convert it to a pointer-to-member type. 11968 if (IsInvalidFormOfPointerToMemberFunction()) 11969 return false; 11970 11971 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11972 E = OvlExpr->decls_end(); 11973 I != E; ++I) { 11974 // Look through any using declarations to find the underlying function. 11975 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11976 11977 // C++ [over.over]p3: 11978 // Non-member functions and static member functions match 11979 // targets of type "pointer-to-function" or "reference-to-function." 11980 // Nonstatic member functions match targets of 11981 // type "pointer-to-member-function." 11982 // Note that according to DR 247, the containing class does not matter. 11983 if (FunctionTemplateDecl *FunctionTemplate 11984 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11985 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11986 Ret = true; 11987 } 11988 // If we have explicit template arguments supplied, skip non-templates. 11989 else if (!OvlExpr->hasExplicitTemplateArgs() && 11990 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11991 Ret = true; 11992 } 11993 assert(Ret || Matches.empty()); 11994 return Ret; 11995 } 11996 11997 void EliminateAllExceptMostSpecializedTemplate() { 11998 // [...] and any given function template specialization F1 is 11999 // eliminated if the set contains a second function template 12000 // specialization whose function template is more specialized 12001 // than the function template of F1 according to the partial 12002 // ordering rules of 14.5.5.2. 12003 12004 // The algorithm specified above is quadratic. We instead use a 12005 // two-pass algorithm (similar to the one used to identify the 12006 // best viable function in an overload set) that identifies the 12007 // best function template (if it exists). 12008 12009 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12010 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12011 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12012 12013 // TODO: It looks like FailedCandidates does not serve much purpose 12014 // here, since the no_viable diagnostic has index 0. 12015 UnresolvedSetIterator Result = S.getMostSpecialized( 12016 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12017 SourceExpr->getBeginLoc(), S.PDiag(), 12018 S.PDiag(diag::err_addr_ovl_ambiguous) 12019 << Matches[0].second->getDeclName(), 12020 S.PDiag(diag::note_ovl_candidate) 12021 << (unsigned)oc_function << (unsigned)ocs_described_template, 12022 Complain, TargetFunctionType); 12023 12024 if (Result != MatchesCopy.end()) { 12025 // Make it the first and only element 12026 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12027 Matches[0].second = cast<FunctionDecl>(*Result); 12028 Matches.resize(1); 12029 } else 12030 HasComplained |= Complain; 12031 } 12032 12033 void EliminateAllTemplateMatches() { 12034 // [...] any function template specializations in the set are 12035 // eliminated if the set also contains a non-template function, [...] 12036 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12037 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12038 ++I; 12039 else { 12040 Matches[I] = Matches[--N]; 12041 Matches.resize(N); 12042 } 12043 } 12044 } 12045 12046 void EliminateSuboptimalCudaMatches() { 12047 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12048 } 12049 12050 public: 12051 void ComplainNoMatchesFound() const { 12052 assert(Matches.empty()); 12053 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12054 << OvlExpr->getName() << TargetFunctionType 12055 << OvlExpr->getSourceRange(); 12056 if (FailedCandidates.empty()) 12057 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12058 /*TakingAddress=*/true); 12059 else { 12060 // We have some deduction failure messages. Use them to diagnose 12061 // the function templates, and diagnose the non-template candidates 12062 // normally. 12063 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12064 IEnd = OvlExpr->decls_end(); 12065 I != IEnd; ++I) 12066 if (FunctionDecl *Fun = 12067 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12068 if (!functionHasPassObjectSizeParams(Fun)) 12069 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12070 /*TakingAddress=*/true); 12071 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12072 } 12073 } 12074 12075 bool IsInvalidFormOfPointerToMemberFunction() const { 12076 return TargetTypeIsNonStaticMemberFunction && 12077 !OvlExprInfo.HasFormOfMemberPointer; 12078 } 12079 12080 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12081 // TODO: Should we condition this on whether any functions might 12082 // have matched, or is it more appropriate to do that in callers? 12083 // TODO: a fixit wouldn't hurt. 12084 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12085 << TargetType << OvlExpr->getSourceRange(); 12086 } 12087 12088 bool IsStaticMemberFunctionFromBoundPointer() const { 12089 return StaticMemberFunctionFromBoundPointer; 12090 } 12091 12092 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12093 S.Diag(OvlExpr->getBeginLoc(), 12094 diag::err_invalid_form_pointer_member_function) 12095 << OvlExpr->getSourceRange(); 12096 } 12097 12098 void ComplainOfInvalidConversion() const { 12099 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12100 << OvlExpr->getName() << TargetType; 12101 } 12102 12103 void ComplainMultipleMatchesFound() const { 12104 assert(Matches.size() > 1); 12105 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12106 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12107 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12108 /*TakingAddress=*/true); 12109 } 12110 12111 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12112 12113 int getNumMatches() const { return Matches.size(); } 12114 12115 FunctionDecl* getMatchingFunctionDecl() const { 12116 if (Matches.size() != 1) return nullptr; 12117 return Matches[0].second; 12118 } 12119 12120 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12121 if (Matches.size() != 1) return nullptr; 12122 return &Matches[0].first; 12123 } 12124 }; 12125 } 12126 12127 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12128 /// an overloaded function (C++ [over.over]), where @p From is an 12129 /// expression with overloaded function type and @p ToType is the type 12130 /// we're trying to resolve to. For example: 12131 /// 12132 /// @code 12133 /// int f(double); 12134 /// int f(int); 12135 /// 12136 /// int (*pfd)(double) = f; // selects f(double) 12137 /// @endcode 12138 /// 12139 /// This routine returns the resulting FunctionDecl if it could be 12140 /// resolved, and NULL otherwise. When @p Complain is true, this 12141 /// routine will emit diagnostics if there is an error. 12142 FunctionDecl * 12143 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12144 QualType TargetType, 12145 bool Complain, 12146 DeclAccessPair &FoundResult, 12147 bool *pHadMultipleCandidates) { 12148 assert(AddressOfExpr->getType() == Context.OverloadTy); 12149 12150 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12151 Complain); 12152 int NumMatches = Resolver.getNumMatches(); 12153 FunctionDecl *Fn = nullptr; 12154 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12155 if (NumMatches == 0 && ShouldComplain) { 12156 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12157 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12158 else 12159 Resolver.ComplainNoMatchesFound(); 12160 } 12161 else if (NumMatches > 1 && ShouldComplain) 12162 Resolver.ComplainMultipleMatchesFound(); 12163 else if (NumMatches == 1) { 12164 Fn = Resolver.getMatchingFunctionDecl(); 12165 assert(Fn); 12166 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12167 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12168 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12169 if (Complain) { 12170 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12171 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12172 else 12173 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12174 } 12175 } 12176 12177 if (pHadMultipleCandidates) 12178 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12179 return Fn; 12180 } 12181 12182 /// Given an expression that refers to an overloaded function, try to 12183 /// resolve that function to a single function that can have its address taken. 12184 /// This will modify `Pair` iff it returns non-null. 12185 /// 12186 /// This routine can only succeed if from all of the candidates in the overload 12187 /// set for SrcExpr that can have their addresses taken, there is one candidate 12188 /// that is more constrained than the rest. 12189 FunctionDecl * 12190 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12191 OverloadExpr::FindResult R = OverloadExpr::find(E); 12192 OverloadExpr *Ovl = R.Expression; 12193 bool IsResultAmbiguous = false; 12194 FunctionDecl *Result = nullptr; 12195 DeclAccessPair DAP; 12196 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12197 12198 auto CheckMoreConstrained = 12199 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12200 SmallVector<const Expr *, 1> AC1, AC2; 12201 FD1->getAssociatedConstraints(AC1); 12202 FD2->getAssociatedConstraints(AC2); 12203 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12204 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12205 return None; 12206 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12207 return None; 12208 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12209 return None; 12210 return AtLeastAsConstrained1; 12211 }; 12212 12213 // Don't use the AddressOfResolver because we're specifically looking for 12214 // cases where we have one overload candidate that lacks 12215 // enable_if/pass_object_size/... 12216 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12217 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12218 if (!FD) 12219 return nullptr; 12220 12221 if (!checkAddressOfFunctionIsAvailable(FD)) 12222 continue; 12223 12224 // We have more than one result - see if it is more constrained than the 12225 // previous one. 12226 if (Result) { 12227 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12228 Result); 12229 if (!MoreConstrainedThanPrevious) { 12230 IsResultAmbiguous = true; 12231 AmbiguousDecls.push_back(FD); 12232 continue; 12233 } 12234 if (!*MoreConstrainedThanPrevious) 12235 continue; 12236 // FD is more constrained - replace Result with it. 12237 } 12238 IsResultAmbiguous = false; 12239 DAP = I.getPair(); 12240 Result = FD; 12241 } 12242 12243 if (IsResultAmbiguous) 12244 return nullptr; 12245 12246 if (Result) { 12247 SmallVector<const Expr *, 1> ResultAC; 12248 // We skipped over some ambiguous declarations which might be ambiguous with 12249 // the selected result. 12250 for (FunctionDecl *Skipped : AmbiguousDecls) 12251 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12252 return nullptr; 12253 Pair = DAP; 12254 } 12255 return Result; 12256 } 12257 12258 /// Given an overloaded function, tries to turn it into a non-overloaded 12259 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12260 /// will perform access checks, diagnose the use of the resultant decl, and, if 12261 /// requested, potentially perform a function-to-pointer decay. 12262 /// 12263 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12264 /// Otherwise, returns true. This may emit diagnostics and return true. 12265 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12266 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12267 Expr *E = SrcExpr.get(); 12268 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12269 12270 DeclAccessPair DAP; 12271 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12272 if (!Found || Found->isCPUDispatchMultiVersion() || 12273 Found->isCPUSpecificMultiVersion()) 12274 return false; 12275 12276 // Emitting multiple diagnostics for a function that is both inaccessible and 12277 // unavailable is consistent with our behavior elsewhere. So, always check 12278 // for both. 12279 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12280 CheckAddressOfMemberAccess(E, DAP); 12281 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12282 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12283 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12284 else 12285 SrcExpr = Fixed; 12286 return true; 12287 } 12288 12289 /// Given an expression that refers to an overloaded function, try to 12290 /// resolve that overloaded function expression down to a single function. 12291 /// 12292 /// This routine can only resolve template-ids that refer to a single function 12293 /// template, where that template-id refers to a single template whose template 12294 /// arguments are either provided by the template-id or have defaults, 12295 /// as described in C++0x [temp.arg.explicit]p3. 12296 /// 12297 /// If no template-ids are found, no diagnostics are emitted and NULL is 12298 /// returned. 12299 FunctionDecl * 12300 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12301 bool Complain, 12302 DeclAccessPair *FoundResult) { 12303 // C++ [over.over]p1: 12304 // [...] [Note: any redundant set of parentheses surrounding the 12305 // overloaded function name is ignored (5.1). ] 12306 // C++ [over.over]p1: 12307 // [...] The overloaded function name can be preceded by the & 12308 // operator. 12309 12310 // If we didn't actually find any template-ids, we're done. 12311 if (!ovl->hasExplicitTemplateArgs()) 12312 return nullptr; 12313 12314 TemplateArgumentListInfo ExplicitTemplateArgs; 12315 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12316 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12317 12318 // Look through all of the overloaded functions, searching for one 12319 // whose type matches exactly. 12320 FunctionDecl *Matched = nullptr; 12321 for (UnresolvedSetIterator I = ovl->decls_begin(), 12322 E = ovl->decls_end(); I != E; ++I) { 12323 // C++0x [temp.arg.explicit]p3: 12324 // [...] In contexts where deduction is done and fails, or in contexts 12325 // where deduction is not done, if a template argument list is 12326 // specified and it, along with any default template arguments, 12327 // identifies a single function template specialization, then the 12328 // template-id is an lvalue for the function template specialization. 12329 FunctionTemplateDecl *FunctionTemplate 12330 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12331 12332 // C++ [over.over]p2: 12333 // If the name is a function template, template argument deduction is 12334 // done (14.8.2.2), and if the argument deduction succeeds, the 12335 // resulting template argument list is used to generate a single 12336 // function template specialization, which is added to the set of 12337 // overloaded functions considered. 12338 FunctionDecl *Specialization = nullptr; 12339 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12340 if (TemplateDeductionResult Result 12341 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12342 Specialization, Info, 12343 /*IsAddressOfFunction*/true)) { 12344 // Make a note of the failed deduction for diagnostics. 12345 // TODO: Actually use the failed-deduction info? 12346 FailedCandidates.addCandidate() 12347 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12348 MakeDeductionFailureInfo(Context, Result, Info)); 12349 continue; 12350 } 12351 12352 assert(Specialization && "no specialization and no error?"); 12353 12354 // Multiple matches; we can't resolve to a single declaration. 12355 if (Matched) { 12356 if (Complain) { 12357 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12358 << ovl->getName(); 12359 NoteAllOverloadCandidates(ovl); 12360 } 12361 return nullptr; 12362 } 12363 12364 Matched = Specialization; 12365 if (FoundResult) *FoundResult = I.getPair(); 12366 } 12367 12368 if (Matched && 12369 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12370 return nullptr; 12371 12372 return Matched; 12373 } 12374 12375 // Resolve and fix an overloaded expression that can be resolved 12376 // because it identifies a single function template specialization. 12377 // 12378 // Last three arguments should only be supplied if Complain = true 12379 // 12380 // Return true if it was logically possible to so resolve the 12381 // expression, regardless of whether or not it succeeded. Always 12382 // returns true if 'complain' is set. 12383 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12384 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12385 bool complain, SourceRange OpRangeForComplaining, 12386 QualType DestTypeForComplaining, 12387 unsigned DiagIDForComplaining) { 12388 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12389 12390 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12391 12392 DeclAccessPair found; 12393 ExprResult SingleFunctionExpression; 12394 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12395 ovl.Expression, /*complain*/ false, &found)) { 12396 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12397 SrcExpr = ExprError(); 12398 return true; 12399 } 12400 12401 // It is only correct to resolve to an instance method if we're 12402 // resolving a form that's permitted to be a pointer to member. 12403 // Otherwise we'll end up making a bound member expression, which 12404 // is illegal in all the contexts we resolve like this. 12405 if (!ovl.HasFormOfMemberPointer && 12406 isa<CXXMethodDecl>(fn) && 12407 cast<CXXMethodDecl>(fn)->isInstance()) { 12408 if (!complain) return false; 12409 12410 Diag(ovl.Expression->getExprLoc(), 12411 diag::err_bound_member_function) 12412 << 0 << ovl.Expression->getSourceRange(); 12413 12414 // TODO: I believe we only end up here if there's a mix of 12415 // static and non-static candidates (otherwise the expression 12416 // would have 'bound member' type, not 'overload' type). 12417 // Ideally we would note which candidate was chosen and why 12418 // the static candidates were rejected. 12419 SrcExpr = ExprError(); 12420 return true; 12421 } 12422 12423 // Fix the expression to refer to 'fn'. 12424 SingleFunctionExpression = 12425 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12426 12427 // If desired, do function-to-pointer decay. 12428 if (doFunctionPointerConverion) { 12429 SingleFunctionExpression = 12430 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12431 if (SingleFunctionExpression.isInvalid()) { 12432 SrcExpr = ExprError(); 12433 return true; 12434 } 12435 } 12436 } 12437 12438 if (!SingleFunctionExpression.isUsable()) { 12439 if (complain) { 12440 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12441 << ovl.Expression->getName() 12442 << DestTypeForComplaining 12443 << OpRangeForComplaining 12444 << ovl.Expression->getQualifierLoc().getSourceRange(); 12445 NoteAllOverloadCandidates(SrcExpr.get()); 12446 12447 SrcExpr = ExprError(); 12448 return true; 12449 } 12450 12451 return false; 12452 } 12453 12454 SrcExpr = SingleFunctionExpression; 12455 return true; 12456 } 12457 12458 /// Add a single candidate to the overload set. 12459 static void AddOverloadedCallCandidate(Sema &S, 12460 DeclAccessPair FoundDecl, 12461 TemplateArgumentListInfo *ExplicitTemplateArgs, 12462 ArrayRef<Expr *> Args, 12463 OverloadCandidateSet &CandidateSet, 12464 bool PartialOverloading, 12465 bool KnownValid) { 12466 NamedDecl *Callee = FoundDecl.getDecl(); 12467 if (isa<UsingShadowDecl>(Callee)) 12468 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12469 12470 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12471 if (ExplicitTemplateArgs) { 12472 assert(!KnownValid && "Explicit template arguments?"); 12473 return; 12474 } 12475 // Prevent ill-formed function decls to be added as overload candidates. 12476 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12477 return; 12478 12479 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12480 /*SuppressUserConversions=*/false, 12481 PartialOverloading); 12482 return; 12483 } 12484 12485 if (FunctionTemplateDecl *FuncTemplate 12486 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12487 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12488 ExplicitTemplateArgs, Args, CandidateSet, 12489 /*SuppressUserConversions=*/false, 12490 PartialOverloading); 12491 return; 12492 } 12493 12494 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12495 } 12496 12497 /// Add the overload candidates named by callee and/or found by argument 12498 /// dependent lookup to the given overload set. 12499 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12500 ArrayRef<Expr *> Args, 12501 OverloadCandidateSet &CandidateSet, 12502 bool PartialOverloading) { 12503 12504 #ifndef NDEBUG 12505 // Verify that ArgumentDependentLookup is consistent with the rules 12506 // in C++0x [basic.lookup.argdep]p3: 12507 // 12508 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12509 // and let Y be the lookup set produced by argument dependent 12510 // lookup (defined as follows). If X contains 12511 // 12512 // -- a declaration of a class member, or 12513 // 12514 // -- a block-scope function declaration that is not a 12515 // using-declaration, or 12516 // 12517 // -- a declaration that is neither a function or a function 12518 // template 12519 // 12520 // then Y is empty. 12521 12522 if (ULE->requiresADL()) { 12523 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12524 E = ULE->decls_end(); I != E; ++I) { 12525 assert(!(*I)->getDeclContext()->isRecord()); 12526 assert(isa<UsingShadowDecl>(*I) || 12527 !(*I)->getDeclContext()->isFunctionOrMethod()); 12528 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12529 } 12530 } 12531 #endif 12532 12533 // It would be nice to avoid this copy. 12534 TemplateArgumentListInfo TABuffer; 12535 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12536 if (ULE->hasExplicitTemplateArgs()) { 12537 ULE->copyTemplateArgumentsInto(TABuffer); 12538 ExplicitTemplateArgs = &TABuffer; 12539 } 12540 12541 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12542 E = ULE->decls_end(); I != E; ++I) 12543 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12544 CandidateSet, PartialOverloading, 12545 /*KnownValid*/ true); 12546 12547 if (ULE->requiresADL()) 12548 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12549 Args, ExplicitTemplateArgs, 12550 CandidateSet, PartialOverloading); 12551 } 12552 12553 /// Determine whether a declaration with the specified name could be moved into 12554 /// a different namespace. 12555 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12556 switch (Name.getCXXOverloadedOperator()) { 12557 case OO_New: case OO_Array_New: 12558 case OO_Delete: case OO_Array_Delete: 12559 return false; 12560 12561 default: 12562 return true; 12563 } 12564 } 12565 12566 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12567 /// template, where the non-dependent name was declared after the template 12568 /// was defined. This is common in code written for a compilers which do not 12569 /// correctly implement two-stage name lookup. 12570 /// 12571 /// Returns true if a viable candidate was found and a diagnostic was issued. 12572 static bool 12573 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12574 const CXXScopeSpec &SS, LookupResult &R, 12575 OverloadCandidateSet::CandidateSetKind CSK, 12576 TemplateArgumentListInfo *ExplicitTemplateArgs, 12577 ArrayRef<Expr *> Args, 12578 bool *DoDiagnoseEmptyLookup = nullptr) { 12579 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12580 return false; 12581 12582 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12583 if (DC->isTransparentContext()) 12584 continue; 12585 12586 SemaRef.LookupQualifiedName(R, DC); 12587 12588 if (!R.empty()) { 12589 R.suppressDiagnostics(); 12590 12591 if (isa<CXXRecordDecl>(DC)) { 12592 // Don't diagnose names we find in classes; we get much better 12593 // diagnostics for these from DiagnoseEmptyLookup. 12594 R.clear(); 12595 if (DoDiagnoseEmptyLookup) 12596 *DoDiagnoseEmptyLookup = true; 12597 return false; 12598 } 12599 12600 OverloadCandidateSet Candidates(FnLoc, CSK); 12601 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12602 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12603 ExplicitTemplateArgs, Args, 12604 Candidates, false, /*KnownValid*/ false); 12605 12606 OverloadCandidateSet::iterator Best; 12607 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12608 // No viable functions. Don't bother the user with notes for functions 12609 // which don't work and shouldn't be found anyway. 12610 R.clear(); 12611 return false; 12612 } 12613 12614 // Find the namespaces where ADL would have looked, and suggest 12615 // declaring the function there instead. 12616 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12617 Sema::AssociatedClassSet AssociatedClasses; 12618 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12619 AssociatedNamespaces, 12620 AssociatedClasses); 12621 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12622 if (canBeDeclaredInNamespace(R.getLookupName())) { 12623 DeclContext *Std = SemaRef.getStdNamespace(); 12624 for (Sema::AssociatedNamespaceSet::iterator 12625 it = AssociatedNamespaces.begin(), 12626 end = AssociatedNamespaces.end(); it != end; ++it) { 12627 // Never suggest declaring a function within namespace 'std'. 12628 if (Std && Std->Encloses(*it)) 12629 continue; 12630 12631 // Never suggest declaring a function within a namespace with a 12632 // reserved name, like __gnu_cxx. 12633 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12634 if (NS && 12635 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12636 continue; 12637 12638 SuggestedNamespaces.insert(*it); 12639 } 12640 } 12641 12642 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12643 << R.getLookupName(); 12644 if (SuggestedNamespaces.empty()) { 12645 SemaRef.Diag(Best->Function->getLocation(), 12646 diag::note_not_found_by_two_phase_lookup) 12647 << R.getLookupName() << 0; 12648 } else if (SuggestedNamespaces.size() == 1) { 12649 SemaRef.Diag(Best->Function->getLocation(), 12650 diag::note_not_found_by_two_phase_lookup) 12651 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12652 } else { 12653 // FIXME: It would be useful to list the associated namespaces here, 12654 // but the diagnostics infrastructure doesn't provide a way to produce 12655 // a localized representation of a list of items. 12656 SemaRef.Diag(Best->Function->getLocation(), 12657 diag::note_not_found_by_two_phase_lookup) 12658 << R.getLookupName() << 2; 12659 } 12660 12661 // Try to recover by calling this function. 12662 return true; 12663 } 12664 12665 R.clear(); 12666 } 12667 12668 return false; 12669 } 12670 12671 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12672 /// template, where the non-dependent operator was declared after the template 12673 /// was defined. 12674 /// 12675 /// Returns true if a viable candidate was found and a diagnostic was issued. 12676 static bool 12677 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12678 SourceLocation OpLoc, 12679 ArrayRef<Expr *> Args) { 12680 DeclarationName OpName = 12681 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12682 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12683 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12684 OverloadCandidateSet::CSK_Operator, 12685 /*ExplicitTemplateArgs=*/nullptr, Args); 12686 } 12687 12688 namespace { 12689 class BuildRecoveryCallExprRAII { 12690 Sema &SemaRef; 12691 public: 12692 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12693 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12694 SemaRef.IsBuildingRecoveryCallExpr = true; 12695 } 12696 12697 ~BuildRecoveryCallExprRAII() { 12698 SemaRef.IsBuildingRecoveryCallExpr = false; 12699 } 12700 }; 12701 12702 } 12703 12704 /// Attempts to recover from a call where no functions were found. 12705 /// 12706 /// Returns true if new candidates were found. 12707 static ExprResult 12708 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12709 UnresolvedLookupExpr *ULE, 12710 SourceLocation LParenLoc, 12711 MutableArrayRef<Expr *> Args, 12712 SourceLocation RParenLoc, 12713 bool EmptyLookup, bool AllowTypoCorrection) { 12714 // Do not try to recover if it is already building a recovery call. 12715 // This stops infinite loops for template instantiations like 12716 // 12717 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12718 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12719 // 12720 if (SemaRef.IsBuildingRecoveryCallExpr) 12721 return ExprError(); 12722 BuildRecoveryCallExprRAII RCE(SemaRef); 12723 12724 CXXScopeSpec SS; 12725 SS.Adopt(ULE->getQualifierLoc()); 12726 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12727 12728 TemplateArgumentListInfo TABuffer; 12729 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12730 if (ULE->hasExplicitTemplateArgs()) { 12731 ULE->copyTemplateArgumentsInto(TABuffer); 12732 ExplicitTemplateArgs = &TABuffer; 12733 } 12734 12735 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12736 Sema::LookupOrdinaryName); 12737 bool DoDiagnoseEmptyLookup = EmptyLookup; 12738 if (!DiagnoseTwoPhaseLookup( 12739 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12740 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12741 NoTypoCorrectionCCC NoTypoValidator{}; 12742 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12743 ExplicitTemplateArgs != nullptr, 12744 dyn_cast<MemberExpr>(Fn)); 12745 CorrectionCandidateCallback &Validator = 12746 AllowTypoCorrection 12747 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12748 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12749 if (!DoDiagnoseEmptyLookup || 12750 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12751 Args)) 12752 return ExprError(); 12753 } 12754 12755 assert(!R.empty() && "lookup results empty despite recovery"); 12756 12757 // If recovery created an ambiguity, just bail out. 12758 if (R.isAmbiguous()) { 12759 R.suppressDiagnostics(); 12760 return ExprError(); 12761 } 12762 12763 // Build an implicit member call if appropriate. Just drop the 12764 // casts and such from the call, we don't really care. 12765 ExprResult NewFn = ExprError(); 12766 if ((*R.begin())->isCXXClassMember()) 12767 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12768 ExplicitTemplateArgs, S); 12769 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12770 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12771 ExplicitTemplateArgs); 12772 else 12773 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12774 12775 if (NewFn.isInvalid()) 12776 return ExprError(); 12777 12778 // This shouldn't cause an infinite loop because we're giving it 12779 // an expression with viable lookup results, which should never 12780 // end up here. 12781 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12782 MultiExprArg(Args.data(), Args.size()), 12783 RParenLoc); 12784 } 12785 12786 /// Constructs and populates an OverloadedCandidateSet from 12787 /// the given function. 12788 /// \returns true when an the ExprResult output parameter has been set. 12789 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12790 UnresolvedLookupExpr *ULE, 12791 MultiExprArg Args, 12792 SourceLocation RParenLoc, 12793 OverloadCandidateSet *CandidateSet, 12794 ExprResult *Result) { 12795 #ifndef NDEBUG 12796 if (ULE->requiresADL()) { 12797 // To do ADL, we must have found an unqualified name. 12798 assert(!ULE->getQualifier() && "qualified name with ADL"); 12799 12800 // We don't perform ADL for implicit declarations of builtins. 12801 // Verify that this was correctly set up. 12802 FunctionDecl *F; 12803 if (ULE->decls_begin() != ULE->decls_end() && 12804 ULE->decls_begin() + 1 == ULE->decls_end() && 12805 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12806 F->getBuiltinID() && F->isImplicit()) 12807 llvm_unreachable("performing ADL for builtin"); 12808 12809 // We don't perform ADL in C. 12810 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12811 } 12812 #endif 12813 12814 UnbridgedCastsSet UnbridgedCasts; 12815 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12816 *Result = ExprError(); 12817 return true; 12818 } 12819 12820 // Add the functions denoted by the callee to the set of candidate 12821 // functions, including those from argument-dependent lookup. 12822 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12823 12824 if (getLangOpts().MSVCCompat && 12825 CurContext->isDependentContext() && !isSFINAEContext() && 12826 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12827 12828 OverloadCandidateSet::iterator Best; 12829 if (CandidateSet->empty() || 12830 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12831 OR_No_Viable_Function) { 12832 // In Microsoft mode, if we are inside a template class member function 12833 // then create a type dependent CallExpr. The goal is to postpone name 12834 // lookup to instantiation time to be able to search into type dependent 12835 // base classes. 12836 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12837 VK_RValue, RParenLoc); 12838 CE->markDependentForPostponedNameLookup(); 12839 *Result = CE; 12840 return true; 12841 } 12842 } 12843 12844 if (CandidateSet->empty()) 12845 return false; 12846 12847 UnbridgedCasts.restore(); 12848 return false; 12849 } 12850 12851 // Guess at what the return type for an unresolvable overload should be. 12852 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12853 OverloadCandidateSet::iterator *Best) { 12854 llvm::Optional<QualType> Result; 12855 // Adjust Type after seeing a candidate. 12856 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12857 if (!Candidate.Function) 12858 return; 12859 QualType T = Candidate.Function->getCallResultType(); 12860 if (T.isNull()) 12861 return; 12862 if (!Result) 12863 Result = T; 12864 else if (Result != T) 12865 Result = QualType(); 12866 }; 12867 12868 // Look for an unambiguous type from a progressively larger subset. 12869 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12870 // 12871 // First, consider only the best candidate. 12872 if (Best && *Best != CS.end()) 12873 ConsiderCandidate(**Best); 12874 // Next, consider only viable candidates. 12875 if (!Result) 12876 for (const auto &C : CS) 12877 if (C.Viable) 12878 ConsiderCandidate(C); 12879 // Finally, consider all candidates. 12880 if (!Result) 12881 for (const auto &C : CS) 12882 ConsiderCandidate(C); 12883 12884 return Result.getValueOr(QualType()); 12885 } 12886 12887 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12888 /// the completed call expression. If overload resolution fails, emits 12889 /// diagnostics and returns ExprError() 12890 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12891 UnresolvedLookupExpr *ULE, 12892 SourceLocation LParenLoc, 12893 MultiExprArg Args, 12894 SourceLocation RParenLoc, 12895 Expr *ExecConfig, 12896 OverloadCandidateSet *CandidateSet, 12897 OverloadCandidateSet::iterator *Best, 12898 OverloadingResult OverloadResult, 12899 bool AllowTypoCorrection) { 12900 if (CandidateSet->empty()) 12901 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12902 RParenLoc, /*EmptyLookup=*/true, 12903 AllowTypoCorrection); 12904 12905 switch (OverloadResult) { 12906 case OR_Success: { 12907 FunctionDecl *FDecl = (*Best)->Function; 12908 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12909 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12910 return ExprError(); 12911 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12912 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12913 ExecConfig, /*IsExecConfig=*/false, 12914 (*Best)->IsADLCandidate); 12915 } 12916 12917 case OR_No_Viable_Function: { 12918 // Try to recover by looking for viable functions which the user might 12919 // have meant to call. 12920 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12921 Args, RParenLoc, 12922 /*EmptyLookup=*/false, 12923 AllowTypoCorrection); 12924 if (!Recovery.isInvalid()) 12925 return Recovery; 12926 12927 // If the user passes in a function that we can't take the address of, we 12928 // generally end up emitting really bad error messages. Here, we attempt to 12929 // emit better ones. 12930 for (const Expr *Arg : Args) { 12931 if (!Arg->getType()->isFunctionType()) 12932 continue; 12933 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12934 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12935 if (FD && 12936 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12937 Arg->getExprLoc())) 12938 return ExprError(); 12939 } 12940 } 12941 12942 CandidateSet->NoteCandidates( 12943 PartialDiagnosticAt( 12944 Fn->getBeginLoc(), 12945 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12946 << ULE->getName() << Fn->getSourceRange()), 12947 SemaRef, OCD_AllCandidates, Args); 12948 break; 12949 } 12950 12951 case OR_Ambiguous: 12952 CandidateSet->NoteCandidates( 12953 PartialDiagnosticAt(Fn->getBeginLoc(), 12954 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12955 << ULE->getName() << Fn->getSourceRange()), 12956 SemaRef, OCD_AmbiguousCandidates, Args); 12957 break; 12958 12959 case OR_Deleted: { 12960 CandidateSet->NoteCandidates( 12961 PartialDiagnosticAt(Fn->getBeginLoc(), 12962 SemaRef.PDiag(diag::err_ovl_deleted_call) 12963 << ULE->getName() << Fn->getSourceRange()), 12964 SemaRef, OCD_AllCandidates, Args); 12965 12966 // We emitted an error for the unavailable/deleted function call but keep 12967 // the call in the AST. 12968 FunctionDecl *FDecl = (*Best)->Function; 12969 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12970 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12971 ExecConfig, /*IsExecConfig=*/false, 12972 (*Best)->IsADLCandidate); 12973 } 12974 } 12975 12976 // Overload resolution failed, try to recover. 12977 SmallVector<Expr *, 8> SubExprs = {Fn}; 12978 SubExprs.append(Args.begin(), Args.end()); 12979 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 12980 chooseRecoveryType(*CandidateSet, Best)); 12981 } 12982 12983 static void markUnaddressableCandidatesUnviable(Sema &S, 12984 OverloadCandidateSet &CS) { 12985 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12986 if (I->Viable && 12987 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12988 I->Viable = false; 12989 I->FailureKind = ovl_fail_addr_not_available; 12990 } 12991 } 12992 } 12993 12994 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12995 /// (which eventually refers to the declaration Func) and the call 12996 /// arguments Args/NumArgs, attempt to resolve the function call down 12997 /// to a specific function. If overload resolution succeeds, returns 12998 /// the call expression produced by overload resolution. 12999 /// Otherwise, emits diagnostics and returns ExprError. 13000 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13001 UnresolvedLookupExpr *ULE, 13002 SourceLocation LParenLoc, 13003 MultiExprArg Args, 13004 SourceLocation RParenLoc, 13005 Expr *ExecConfig, 13006 bool AllowTypoCorrection, 13007 bool CalleesAddressIsTaken) { 13008 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13009 OverloadCandidateSet::CSK_Normal); 13010 ExprResult result; 13011 13012 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13013 &result)) 13014 return result; 13015 13016 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13017 // functions that aren't addressible are considered unviable. 13018 if (CalleesAddressIsTaken) 13019 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13020 13021 OverloadCandidateSet::iterator Best; 13022 OverloadingResult OverloadResult = 13023 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13024 13025 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13026 ExecConfig, &CandidateSet, &Best, 13027 OverloadResult, AllowTypoCorrection); 13028 } 13029 13030 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13031 return Functions.size() > 1 || 13032 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 13033 } 13034 13035 /// Create a unary operation that may resolve to an overloaded 13036 /// operator. 13037 /// 13038 /// \param OpLoc The location of the operator itself (e.g., '*'). 13039 /// 13040 /// \param Opc The UnaryOperatorKind that describes this operator. 13041 /// 13042 /// \param Fns The set of non-member functions that will be 13043 /// considered by overload resolution. The caller needs to build this 13044 /// set based on the context using, e.g., 13045 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13046 /// set should not contain any member functions; those will be added 13047 /// by CreateOverloadedUnaryOp(). 13048 /// 13049 /// \param Input The input argument. 13050 ExprResult 13051 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13052 const UnresolvedSetImpl &Fns, 13053 Expr *Input, bool PerformADL) { 13054 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13055 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13056 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13057 // TODO: provide better source location info. 13058 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13059 13060 if (checkPlaceholderForOverload(*this, Input)) 13061 return ExprError(); 13062 13063 Expr *Args[2] = { Input, nullptr }; 13064 unsigned NumArgs = 1; 13065 13066 // For post-increment and post-decrement, add the implicit '0' as 13067 // the second argument, so that we know this is a post-increment or 13068 // post-decrement. 13069 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13070 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13071 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13072 SourceLocation()); 13073 NumArgs = 2; 13074 } 13075 13076 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13077 13078 if (Input->isTypeDependent()) { 13079 if (Fns.empty()) 13080 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13081 VK_RValue, OK_Ordinary, OpLoc, false, 13082 CurFPFeatures); 13083 13084 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13085 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13086 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13087 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13088 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 13089 Context.DependentTy, VK_RValue, OpLoc, 13090 CurFPFeatures); 13091 } 13092 13093 // Build an empty overload set. 13094 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13095 13096 // Add the candidates from the given function set. 13097 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13098 13099 // Add operator candidates that are member functions. 13100 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13101 13102 // Add candidates from ADL. 13103 if (PerformADL) { 13104 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13105 /*ExplicitTemplateArgs*/nullptr, 13106 CandidateSet); 13107 } 13108 13109 // Add builtin operator candidates. 13110 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13111 13112 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13113 13114 // Perform overload resolution. 13115 OverloadCandidateSet::iterator Best; 13116 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13117 case OR_Success: { 13118 // We found a built-in operator or an overloaded operator. 13119 FunctionDecl *FnDecl = Best->Function; 13120 13121 if (FnDecl) { 13122 Expr *Base = nullptr; 13123 // We matched an overloaded operator. Build a call to that 13124 // operator. 13125 13126 // Convert the arguments. 13127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13128 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13129 13130 ExprResult InputRes = 13131 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13132 Best->FoundDecl, Method); 13133 if (InputRes.isInvalid()) 13134 return ExprError(); 13135 Base = Input = InputRes.get(); 13136 } else { 13137 // Convert the arguments. 13138 ExprResult InputInit 13139 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13140 Context, 13141 FnDecl->getParamDecl(0)), 13142 SourceLocation(), 13143 Input); 13144 if (InputInit.isInvalid()) 13145 return ExprError(); 13146 Input = InputInit.get(); 13147 } 13148 13149 // Build the actual expression node. 13150 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13151 Base, HadMultipleCandidates, 13152 OpLoc); 13153 if (FnExpr.isInvalid()) 13154 return ExprError(); 13155 13156 // Determine the result type. 13157 QualType ResultTy = FnDecl->getReturnType(); 13158 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13159 ResultTy = ResultTy.getNonLValueExprType(Context); 13160 13161 Args[0] = Input; 13162 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13163 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13164 CurFPFeatures, Best->IsADLCandidate); 13165 13166 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13167 return ExprError(); 13168 13169 if (CheckFunctionCall(FnDecl, TheCall, 13170 FnDecl->getType()->castAs<FunctionProtoType>())) 13171 return ExprError(); 13172 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13173 } else { 13174 // We matched a built-in operator. Convert the arguments, then 13175 // break out so that we will build the appropriate built-in 13176 // operator node. 13177 ExprResult InputRes = PerformImplicitConversion( 13178 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13179 CCK_ForBuiltinOverloadedOp); 13180 if (InputRes.isInvalid()) 13181 return ExprError(); 13182 Input = InputRes.get(); 13183 break; 13184 } 13185 } 13186 13187 case OR_No_Viable_Function: 13188 // This is an erroneous use of an operator which can be overloaded by 13189 // a non-member function. Check for non-member operators which were 13190 // defined too late to be candidates. 13191 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13192 // FIXME: Recover by calling the found function. 13193 return ExprError(); 13194 13195 // No viable function; fall through to handling this as a 13196 // built-in operator, which will produce an error message for us. 13197 break; 13198 13199 case OR_Ambiguous: 13200 CandidateSet.NoteCandidates( 13201 PartialDiagnosticAt(OpLoc, 13202 PDiag(diag::err_ovl_ambiguous_oper_unary) 13203 << UnaryOperator::getOpcodeStr(Opc) 13204 << Input->getType() << Input->getSourceRange()), 13205 *this, OCD_AmbiguousCandidates, ArgsArray, 13206 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13207 return ExprError(); 13208 13209 case OR_Deleted: 13210 CandidateSet.NoteCandidates( 13211 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13212 << UnaryOperator::getOpcodeStr(Opc) 13213 << Input->getSourceRange()), 13214 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13215 OpLoc); 13216 return ExprError(); 13217 } 13218 13219 // Either we found no viable overloaded operator or we matched a 13220 // built-in operator. In either case, fall through to trying to 13221 // build a built-in operation. 13222 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13223 } 13224 13225 /// Perform lookup for an overloaded binary operator. 13226 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13227 OverloadedOperatorKind Op, 13228 const UnresolvedSetImpl &Fns, 13229 ArrayRef<Expr *> Args, bool PerformADL) { 13230 SourceLocation OpLoc = CandidateSet.getLocation(); 13231 13232 OverloadedOperatorKind ExtraOp = 13233 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13234 ? getRewrittenOverloadedOperator(Op) 13235 : OO_None; 13236 13237 // Add the candidates from the given function set. This also adds the 13238 // rewritten candidates using these functions if necessary. 13239 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13240 13241 // Add operator candidates that are member functions. 13242 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13243 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13244 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13245 OverloadCandidateParamOrder::Reversed); 13246 13247 // In C++20, also add any rewritten member candidates. 13248 if (ExtraOp) { 13249 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13250 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13251 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13252 CandidateSet, 13253 OverloadCandidateParamOrder::Reversed); 13254 } 13255 13256 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13257 // performed for an assignment operator (nor for operator[] nor operator->, 13258 // which don't get here). 13259 if (Op != OO_Equal && PerformADL) { 13260 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13261 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13262 /*ExplicitTemplateArgs*/ nullptr, 13263 CandidateSet); 13264 if (ExtraOp) { 13265 DeclarationName ExtraOpName = 13266 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13267 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13268 /*ExplicitTemplateArgs*/ nullptr, 13269 CandidateSet); 13270 } 13271 } 13272 13273 // Add builtin operator candidates. 13274 // 13275 // FIXME: We don't add any rewritten candidates here. This is strictly 13276 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13277 // resulting in our selecting a rewritten builtin candidate. For example: 13278 // 13279 // enum class E { e }; 13280 // bool operator!=(E, E) requires false; 13281 // bool k = E::e != E::e; 13282 // 13283 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13284 // it seems unreasonable to consider rewritten builtin candidates. A core 13285 // issue has been filed proposing to removed this requirement. 13286 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13287 } 13288 13289 /// Create a binary operation that may resolve to an overloaded 13290 /// operator. 13291 /// 13292 /// \param OpLoc The location of the operator itself (e.g., '+'). 13293 /// 13294 /// \param Opc The BinaryOperatorKind that describes this operator. 13295 /// 13296 /// \param Fns The set of non-member functions that will be 13297 /// considered by overload resolution. The caller needs to build this 13298 /// set based on the context using, e.g., 13299 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13300 /// set should not contain any member functions; those will be added 13301 /// by CreateOverloadedBinOp(). 13302 /// 13303 /// \param LHS Left-hand argument. 13304 /// \param RHS Right-hand argument. 13305 /// \param PerformADL Whether to consider operator candidates found by ADL. 13306 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13307 /// C++20 operator rewrites. 13308 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13309 /// the function in question. Such a function is never a candidate in 13310 /// our overload resolution. This also enables synthesizing a three-way 13311 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13312 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13313 BinaryOperatorKind Opc, 13314 const UnresolvedSetImpl &Fns, Expr *LHS, 13315 Expr *RHS, bool PerformADL, 13316 bool AllowRewrittenCandidates, 13317 FunctionDecl *DefaultedFn) { 13318 Expr *Args[2] = { LHS, RHS }; 13319 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13320 13321 if (!getLangOpts().CPlusPlus20) 13322 AllowRewrittenCandidates = false; 13323 13324 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13325 13326 // If either side is type-dependent, create an appropriate dependent 13327 // expression. 13328 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13329 if (Fns.empty()) { 13330 // If there are no functions to store, just build a dependent 13331 // BinaryOperator or CompoundAssignment. 13332 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13333 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13334 Context.DependentTy, VK_RValue, 13335 OK_Ordinary, OpLoc, CurFPFeatures); 13336 return CompoundAssignOperator::Create( 13337 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13338 OK_Ordinary, OpLoc, CurFPFeatures, Context.DependentTy, 13339 Context.DependentTy); 13340 } 13341 13342 // FIXME: save results of ADL from here? 13343 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13344 // TODO: provide better source location info in DNLoc component. 13345 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13346 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13347 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13348 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13349 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13350 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13351 Context.DependentTy, VK_RValue, OpLoc, 13352 CurFPFeatures); 13353 } 13354 13355 // Always do placeholder-like conversions on the RHS. 13356 if (checkPlaceholderForOverload(*this, Args[1])) 13357 return ExprError(); 13358 13359 // Do placeholder-like conversion on the LHS; note that we should 13360 // not get here with a PseudoObject LHS. 13361 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13362 if (checkPlaceholderForOverload(*this, Args[0])) 13363 return ExprError(); 13364 13365 // If this is the assignment operator, we only perform overload resolution 13366 // if the left-hand side is a class or enumeration type. This is actually 13367 // a hack. The standard requires that we do overload resolution between the 13368 // various built-in candidates, but as DR507 points out, this can lead to 13369 // problems. So we do it this way, which pretty much follows what GCC does. 13370 // Note that we go the traditional code path for compound assignment forms. 13371 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13372 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13373 13374 // If this is the .* operator, which is not overloadable, just 13375 // create a built-in binary operator. 13376 if (Opc == BO_PtrMemD) 13377 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13378 13379 // Build the overload set. 13380 OverloadCandidateSet CandidateSet( 13381 OpLoc, OverloadCandidateSet::CSK_Operator, 13382 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13383 if (DefaultedFn) 13384 CandidateSet.exclude(DefaultedFn); 13385 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13386 13387 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13388 13389 // Perform overload resolution. 13390 OverloadCandidateSet::iterator Best; 13391 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13392 case OR_Success: { 13393 // We found a built-in operator or an overloaded operator. 13394 FunctionDecl *FnDecl = Best->Function; 13395 13396 bool IsReversed = Best->isReversed(); 13397 if (IsReversed) 13398 std::swap(Args[0], Args[1]); 13399 13400 if (FnDecl) { 13401 Expr *Base = nullptr; 13402 // We matched an overloaded operator. Build a call to that 13403 // operator. 13404 13405 OverloadedOperatorKind ChosenOp = 13406 FnDecl->getDeclName().getCXXOverloadedOperator(); 13407 13408 // C++2a [over.match.oper]p9: 13409 // If a rewritten operator== candidate is selected by overload 13410 // resolution for an operator@, its return type shall be cv bool 13411 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13412 !FnDecl->getReturnType()->isBooleanType()) { 13413 bool IsExtension = 13414 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13415 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13416 : diag::err_ovl_rewrite_equalequal_not_bool) 13417 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13418 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13419 Diag(FnDecl->getLocation(), diag::note_declared_at); 13420 if (!IsExtension) 13421 return ExprError(); 13422 } 13423 13424 if (AllowRewrittenCandidates && !IsReversed && 13425 CandidateSet.getRewriteInfo().isReversible()) { 13426 // We could have reversed this operator, but didn't. Check if some 13427 // reversed form was a viable candidate, and if so, if it had a 13428 // better conversion for either parameter. If so, this call is 13429 // formally ambiguous, and allowing it is an extension. 13430 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13431 for (OverloadCandidate &Cand : CandidateSet) { 13432 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13433 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13434 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13435 if (CompareImplicitConversionSequences( 13436 *this, OpLoc, Cand.Conversions[ArgIdx], 13437 Best->Conversions[ArgIdx]) == 13438 ImplicitConversionSequence::Better) { 13439 AmbiguousWith.push_back(Cand.Function); 13440 break; 13441 } 13442 } 13443 } 13444 } 13445 13446 if (!AmbiguousWith.empty()) { 13447 bool AmbiguousWithSelf = 13448 AmbiguousWith.size() == 1 && 13449 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13450 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13451 << BinaryOperator::getOpcodeStr(Opc) 13452 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13453 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13454 if (AmbiguousWithSelf) { 13455 Diag(FnDecl->getLocation(), 13456 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13457 } else { 13458 Diag(FnDecl->getLocation(), 13459 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13460 for (auto *F : AmbiguousWith) 13461 Diag(F->getLocation(), 13462 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13463 } 13464 } 13465 } 13466 13467 // Convert the arguments. 13468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13469 // Best->Access is only meaningful for class members. 13470 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13471 13472 ExprResult Arg1 = 13473 PerformCopyInitialization( 13474 InitializedEntity::InitializeParameter(Context, 13475 FnDecl->getParamDecl(0)), 13476 SourceLocation(), Args[1]); 13477 if (Arg1.isInvalid()) 13478 return ExprError(); 13479 13480 ExprResult Arg0 = 13481 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13482 Best->FoundDecl, Method); 13483 if (Arg0.isInvalid()) 13484 return ExprError(); 13485 Base = Args[0] = Arg0.getAs<Expr>(); 13486 Args[1] = RHS = Arg1.getAs<Expr>(); 13487 } else { 13488 // Convert the arguments. 13489 ExprResult Arg0 = PerformCopyInitialization( 13490 InitializedEntity::InitializeParameter(Context, 13491 FnDecl->getParamDecl(0)), 13492 SourceLocation(), Args[0]); 13493 if (Arg0.isInvalid()) 13494 return ExprError(); 13495 13496 ExprResult Arg1 = 13497 PerformCopyInitialization( 13498 InitializedEntity::InitializeParameter(Context, 13499 FnDecl->getParamDecl(1)), 13500 SourceLocation(), Args[1]); 13501 if (Arg1.isInvalid()) 13502 return ExprError(); 13503 Args[0] = LHS = Arg0.getAs<Expr>(); 13504 Args[1] = RHS = Arg1.getAs<Expr>(); 13505 } 13506 13507 // Build the actual expression node. 13508 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13509 Best->FoundDecl, Base, 13510 HadMultipleCandidates, OpLoc); 13511 if (FnExpr.isInvalid()) 13512 return ExprError(); 13513 13514 // Determine the result type. 13515 QualType ResultTy = FnDecl->getReturnType(); 13516 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13517 ResultTy = ResultTy.getNonLValueExprType(Context); 13518 13519 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13520 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13521 CurFPFeatures, Best->IsADLCandidate); 13522 13523 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13524 FnDecl)) 13525 return ExprError(); 13526 13527 ArrayRef<const Expr *> ArgsArray(Args, 2); 13528 const Expr *ImplicitThis = nullptr; 13529 // Cut off the implicit 'this'. 13530 if (isa<CXXMethodDecl>(FnDecl)) { 13531 ImplicitThis = ArgsArray[0]; 13532 ArgsArray = ArgsArray.slice(1); 13533 } 13534 13535 // Check for a self move. 13536 if (Op == OO_Equal) 13537 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13538 13539 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13540 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13541 VariadicDoesNotApply); 13542 13543 ExprResult R = MaybeBindToTemporary(TheCall); 13544 if (R.isInvalid()) 13545 return ExprError(); 13546 13547 // For a rewritten candidate, we've already reversed the arguments 13548 // if needed. Perform the rest of the rewrite now. 13549 if ((Best->RewriteKind & CRK_DifferentOperator) || 13550 (Op == OO_Spaceship && IsReversed)) { 13551 if (Op == OO_ExclaimEqual) { 13552 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13553 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13554 } else { 13555 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13556 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13557 Expr *ZeroLiteral = 13558 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13559 13560 Sema::CodeSynthesisContext Ctx; 13561 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13562 Ctx.Entity = FnDecl; 13563 pushCodeSynthesisContext(Ctx); 13564 13565 R = CreateOverloadedBinOp( 13566 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13567 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13568 /*AllowRewrittenCandidates=*/false); 13569 13570 popCodeSynthesisContext(); 13571 } 13572 if (R.isInvalid()) 13573 return ExprError(); 13574 } else { 13575 assert(ChosenOp == Op && "unexpected operator name"); 13576 } 13577 13578 // Make a note in the AST if we did any rewriting. 13579 if (Best->RewriteKind != CRK_None) 13580 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13581 13582 return CheckForImmediateInvocation(R, FnDecl); 13583 } else { 13584 // We matched a built-in operator. Convert the arguments, then 13585 // break out so that we will build the appropriate built-in 13586 // operator node. 13587 ExprResult ArgsRes0 = PerformImplicitConversion( 13588 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13589 AA_Passing, CCK_ForBuiltinOverloadedOp); 13590 if (ArgsRes0.isInvalid()) 13591 return ExprError(); 13592 Args[0] = ArgsRes0.get(); 13593 13594 ExprResult ArgsRes1 = PerformImplicitConversion( 13595 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13596 AA_Passing, CCK_ForBuiltinOverloadedOp); 13597 if (ArgsRes1.isInvalid()) 13598 return ExprError(); 13599 Args[1] = ArgsRes1.get(); 13600 break; 13601 } 13602 } 13603 13604 case OR_No_Viable_Function: { 13605 // C++ [over.match.oper]p9: 13606 // If the operator is the operator , [...] and there are no 13607 // viable functions, then the operator is assumed to be the 13608 // built-in operator and interpreted according to clause 5. 13609 if (Opc == BO_Comma) 13610 break; 13611 13612 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13613 // compare result using '==' and '<'. 13614 if (DefaultedFn && Opc == BO_Cmp) { 13615 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13616 Args[1], DefaultedFn); 13617 if (E.isInvalid() || E.isUsable()) 13618 return E; 13619 } 13620 13621 // For class as left operand for assignment or compound assignment 13622 // operator do not fall through to handling in built-in, but report that 13623 // no overloaded assignment operator found 13624 ExprResult Result = ExprError(); 13625 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13626 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13627 Args, OpLoc); 13628 if (Args[0]->getType()->isRecordType() && 13629 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13630 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13631 << BinaryOperator::getOpcodeStr(Opc) 13632 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13633 if (Args[0]->getType()->isIncompleteType()) { 13634 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13635 << Args[0]->getType() 13636 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13637 } 13638 } else { 13639 // This is an erroneous use of an operator which can be overloaded by 13640 // a non-member function. Check for non-member operators which were 13641 // defined too late to be candidates. 13642 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13643 // FIXME: Recover by calling the found function. 13644 return ExprError(); 13645 13646 // No viable function; try to create a built-in operation, which will 13647 // produce an error. Then, show the non-viable candidates. 13648 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13649 } 13650 assert(Result.isInvalid() && 13651 "C++ binary operator overloading is missing candidates!"); 13652 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13653 return Result; 13654 } 13655 13656 case OR_Ambiguous: 13657 CandidateSet.NoteCandidates( 13658 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13659 << BinaryOperator::getOpcodeStr(Opc) 13660 << Args[0]->getType() 13661 << Args[1]->getType() 13662 << Args[0]->getSourceRange() 13663 << Args[1]->getSourceRange()), 13664 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13665 OpLoc); 13666 return ExprError(); 13667 13668 case OR_Deleted: 13669 if (isImplicitlyDeleted(Best->Function)) { 13670 FunctionDecl *DeletedFD = Best->Function; 13671 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13672 if (DFK.isSpecialMember()) { 13673 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13674 << Args[0]->getType() << DFK.asSpecialMember(); 13675 } else { 13676 assert(DFK.isComparison()); 13677 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13678 << Args[0]->getType() << DeletedFD; 13679 } 13680 13681 // The user probably meant to call this special member. Just 13682 // explain why it's deleted. 13683 NoteDeletedFunction(DeletedFD); 13684 return ExprError(); 13685 } 13686 CandidateSet.NoteCandidates( 13687 PartialDiagnosticAt( 13688 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13689 << getOperatorSpelling(Best->Function->getDeclName() 13690 .getCXXOverloadedOperator()) 13691 << Args[0]->getSourceRange() 13692 << Args[1]->getSourceRange()), 13693 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13694 OpLoc); 13695 return ExprError(); 13696 } 13697 13698 // We matched a built-in operator; build it. 13699 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13700 } 13701 13702 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13703 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13704 FunctionDecl *DefaultedFn) { 13705 const ComparisonCategoryInfo *Info = 13706 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13707 // If we're not producing a known comparison category type, we can't 13708 // synthesize a three-way comparison. Let the caller diagnose this. 13709 if (!Info) 13710 return ExprResult((Expr*)nullptr); 13711 13712 // If we ever want to perform this synthesis more generally, we will need to 13713 // apply the temporary materialization conversion to the operands. 13714 assert(LHS->isGLValue() && RHS->isGLValue() && 13715 "cannot use prvalue expressions more than once"); 13716 Expr *OrigLHS = LHS; 13717 Expr *OrigRHS = RHS; 13718 13719 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13720 // each of them multiple times below. 13721 LHS = new (Context) 13722 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13723 LHS->getObjectKind(), LHS); 13724 RHS = new (Context) 13725 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13726 RHS->getObjectKind(), RHS); 13727 13728 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13729 DefaultedFn); 13730 if (Eq.isInvalid()) 13731 return ExprError(); 13732 13733 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13734 true, DefaultedFn); 13735 if (Less.isInvalid()) 13736 return ExprError(); 13737 13738 ExprResult Greater; 13739 if (Info->isPartial()) { 13740 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13741 DefaultedFn); 13742 if (Greater.isInvalid()) 13743 return ExprError(); 13744 } 13745 13746 // Form the list of comparisons we're going to perform. 13747 struct Comparison { 13748 ExprResult Cmp; 13749 ComparisonCategoryResult Result; 13750 } Comparisons[4] = 13751 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13752 : ComparisonCategoryResult::Equivalent}, 13753 {Less, ComparisonCategoryResult::Less}, 13754 {Greater, ComparisonCategoryResult::Greater}, 13755 {ExprResult(), ComparisonCategoryResult::Unordered}, 13756 }; 13757 13758 int I = Info->isPartial() ? 3 : 2; 13759 13760 // Combine the comparisons with suitable conditional expressions. 13761 ExprResult Result; 13762 for (; I >= 0; --I) { 13763 // Build a reference to the comparison category constant. 13764 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13765 // FIXME: Missing a constant for a comparison category. Diagnose this? 13766 if (!VI) 13767 return ExprResult((Expr*)nullptr); 13768 ExprResult ThisResult = 13769 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13770 if (ThisResult.isInvalid()) 13771 return ExprError(); 13772 13773 // Build a conditional unless this is the final case. 13774 if (Result.get()) { 13775 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13776 ThisResult.get(), Result.get()); 13777 if (Result.isInvalid()) 13778 return ExprError(); 13779 } else { 13780 Result = ThisResult; 13781 } 13782 } 13783 13784 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13785 // bind the OpaqueValueExprs before they're (repeatedly) used. 13786 Expr *SyntacticForm = BinaryOperator::Create( 13787 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13788 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13789 CurFPFeatures); 13790 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13791 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13792 } 13793 13794 ExprResult 13795 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13796 SourceLocation RLoc, 13797 Expr *Base, Expr *Idx) { 13798 Expr *Args[2] = { Base, Idx }; 13799 DeclarationName OpName = 13800 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13801 13802 // If either side is type-dependent, create an appropriate dependent 13803 // expression. 13804 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13805 13806 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13807 // CHECKME: no 'operator' keyword? 13808 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13809 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13810 UnresolvedLookupExpr *Fn 13811 = UnresolvedLookupExpr::Create(Context, NamingClass, 13812 NestedNameSpecifierLoc(), OpNameInfo, 13813 /*ADL*/ true, /*Overloaded*/ false, 13814 UnresolvedSetIterator(), 13815 UnresolvedSetIterator()); 13816 // Can't add any actual overloads yet 13817 13818 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13819 Context.DependentTy, VK_RValue, RLoc, 13820 CurFPFeatures); 13821 } 13822 13823 // Handle placeholders on both operands. 13824 if (checkPlaceholderForOverload(*this, Args[0])) 13825 return ExprError(); 13826 if (checkPlaceholderForOverload(*this, Args[1])) 13827 return ExprError(); 13828 13829 // Build an empty overload set. 13830 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13831 13832 // Subscript can only be overloaded as a member function. 13833 13834 // Add operator candidates that are member functions. 13835 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13836 13837 // Add builtin operator candidates. 13838 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13839 13840 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13841 13842 // Perform overload resolution. 13843 OverloadCandidateSet::iterator Best; 13844 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13845 case OR_Success: { 13846 // We found a built-in operator or an overloaded operator. 13847 FunctionDecl *FnDecl = Best->Function; 13848 13849 if (FnDecl) { 13850 // We matched an overloaded operator. Build a call to that 13851 // operator. 13852 13853 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13854 13855 // Convert the arguments. 13856 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13857 ExprResult Arg0 = 13858 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13859 Best->FoundDecl, Method); 13860 if (Arg0.isInvalid()) 13861 return ExprError(); 13862 Args[0] = Arg0.get(); 13863 13864 // Convert the arguments. 13865 ExprResult InputInit 13866 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13867 Context, 13868 FnDecl->getParamDecl(0)), 13869 SourceLocation(), 13870 Args[1]); 13871 if (InputInit.isInvalid()) 13872 return ExprError(); 13873 13874 Args[1] = InputInit.getAs<Expr>(); 13875 13876 // Build the actual expression node. 13877 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13878 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13879 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13880 Best->FoundDecl, 13881 Base, 13882 HadMultipleCandidates, 13883 OpLocInfo.getLoc(), 13884 OpLocInfo.getInfo()); 13885 if (FnExpr.isInvalid()) 13886 return ExprError(); 13887 13888 // Determine the result type 13889 QualType ResultTy = FnDecl->getReturnType(); 13890 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13891 ResultTy = ResultTy.getNonLValueExprType(Context); 13892 13893 CXXOperatorCallExpr *TheCall = 13894 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13895 Args, ResultTy, VK, RLoc, CurFPFeatures); 13896 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13897 return ExprError(); 13898 13899 if (CheckFunctionCall(Method, TheCall, 13900 Method->getType()->castAs<FunctionProtoType>())) 13901 return ExprError(); 13902 13903 return MaybeBindToTemporary(TheCall); 13904 } else { 13905 // We matched a built-in operator. Convert the arguments, then 13906 // break out so that we will build the appropriate built-in 13907 // operator node. 13908 ExprResult ArgsRes0 = PerformImplicitConversion( 13909 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13910 AA_Passing, CCK_ForBuiltinOverloadedOp); 13911 if (ArgsRes0.isInvalid()) 13912 return ExprError(); 13913 Args[0] = ArgsRes0.get(); 13914 13915 ExprResult ArgsRes1 = PerformImplicitConversion( 13916 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13917 AA_Passing, CCK_ForBuiltinOverloadedOp); 13918 if (ArgsRes1.isInvalid()) 13919 return ExprError(); 13920 Args[1] = ArgsRes1.get(); 13921 13922 break; 13923 } 13924 } 13925 13926 case OR_No_Viable_Function: { 13927 PartialDiagnostic PD = CandidateSet.empty() 13928 ? (PDiag(diag::err_ovl_no_oper) 13929 << Args[0]->getType() << /*subscript*/ 0 13930 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13931 : (PDiag(diag::err_ovl_no_viable_subscript) 13932 << Args[0]->getType() << Args[0]->getSourceRange() 13933 << Args[1]->getSourceRange()); 13934 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13935 OCD_AllCandidates, Args, "[]", LLoc); 13936 return ExprError(); 13937 } 13938 13939 case OR_Ambiguous: 13940 CandidateSet.NoteCandidates( 13941 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13942 << "[]" << Args[0]->getType() 13943 << Args[1]->getType() 13944 << Args[0]->getSourceRange() 13945 << Args[1]->getSourceRange()), 13946 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13947 return ExprError(); 13948 13949 case OR_Deleted: 13950 CandidateSet.NoteCandidates( 13951 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13952 << "[]" << Args[0]->getSourceRange() 13953 << Args[1]->getSourceRange()), 13954 *this, OCD_AllCandidates, Args, "[]", LLoc); 13955 return ExprError(); 13956 } 13957 13958 // We matched a built-in operator; build it. 13959 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13960 } 13961 13962 /// BuildCallToMemberFunction - Build a call to a member 13963 /// function. MemExpr is the expression that refers to the member 13964 /// function (and includes the object parameter), Args/NumArgs are the 13965 /// arguments to the function call (not including the object 13966 /// parameter). The caller needs to validate that the member 13967 /// expression refers to a non-static member function or an overloaded 13968 /// member function. 13969 ExprResult 13970 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13971 SourceLocation LParenLoc, 13972 MultiExprArg Args, 13973 SourceLocation RParenLoc) { 13974 assert(MemExprE->getType() == Context.BoundMemberTy || 13975 MemExprE->getType() == Context.OverloadTy); 13976 13977 // Dig out the member expression. This holds both the object 13978 // argument and the member function we're referring to. 13979 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13980 13981 // Determine whether this is a call to a pointer-to-member function. 13982 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13983 assert(op->getType() == Context.BoundMemberTy); 13984 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13985 13986 QualType fnType = 13987 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13988 13989 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13990 QualType resultType = proto->getCallResultType(Context); 13991 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13992 13993 // Check that the object type isn't more qualified than the 13994 // member function we're calling. 13995 Qualifiers funcQuals = proto->getMethodQuals(); 13996 13997 QualType objectType = op->getLHS()->getType(); 13998 if (op->getOpcode() == BO_PtrMemI) 13999 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14000 Qualifiers objectQuals = objectType.getQualifiers(); 14001 14002 Qualifiers difference = objectQuals - funcQuals; 14003 difference.removeObjCGCAttr(); 14004 difference.removeAddressSpace(); 14005 if (difference) { 14006 std::string qualsString = difference.getAsString(); 14007 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14008 << fnType.getUnqualifiedType() 14009 << qualsString 14010 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14011 } 14012 14013 CXXMemberCallExpr *call = 14014 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 14015 valueKind, RParenLoc, proto->getNumParams()); 14016 14017 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14018 call, nullptr)) 14019 return ExprError(); 14020 14021 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14022 return ExprError(); 14023 14024 if (CheckOtherCall(call, proto)) 14025 return ExprError(); 14026 14027 return MaybeBindToTemporary(call); 14028 } 14029 14030 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14031 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14032 RParenLoc); 14033 14034 UnbridgedCastsSet UnbridgedCasts; 14035 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14036 return ExprError(); 14037 14038 MemberExpr *MemExpr; 14039 CXXMethodDecl *Method = nullptr; 14040 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14041 NestedNameSpecifier *Qualifier = nullptr; 14042 if (isa<MemberExpr>(NakedMemExpr)) { 14043 MemExpr = cast<MemberExpr>(NakedMemExpr); 14044 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14045 FoundDecl = MemExpr->getFoundDecl(); 14046 Qualifier = MemExpr->getQualifier(); 14047 UnbridgedCasts.restore(); 14048 } else { 14049 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14050 Qualifier = UnresExpr->getQualifier(); 14051 14052 QualType ObjectType = UnresExpr->getBaseType(); 14053 Expr::Classification ObjectClassification 14054 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14055 : UnresExpr->getBase()->Classify(Context); 14056 14057 // Add overload candidates 14058 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14059 OverloadCandidateSet::CSK_Normal); 14060 14061 // FIXME: avoid copy. 14062 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14063 if (UnresExpr->hasExplicitTemplateArgs()) { 14064 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14065 TemplateArgs = &TemplateArgsBuffer; 14066 } 14067 14068 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14069 E = UnresExpr->decls_end(); I != E; ++I) { 14070 14071 NamedDecl *Func = *I; 14072 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14073 if (isa<UsingShadowDecl>(Func)) 14074 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14075 14076 14077 // Microsoft supports direct constructor calls. 14078 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14079 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14080 CandidateSet, 14081 /*SuppressUserConversions*/ false); 14082 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14083 // If explicit template arguments were provided, we can't call a 14084 // non-template member function. 14085 if (TemplateArgs) 14086 continue; 14087 14088 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14089 ObjectClassification, Args, CandidateSet, 14090 /*SuppressUserConversions=*/false); 14091 } else { 14092 AddMethodTemplateCandidate( 14093 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14094 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14095 /*SuppressUserConversions=*/false); 14096 } 14097 } 14098 14099 DeclarationName DeclName = UnresExpr->getMemberName(); 14100 14101 UnbridgedCasts.restore(); 14102 14103 OverloadCandidateSet::iterator Best; 14104 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14105 Best)) { 14106 case OR_Success: 14107 Method = cast<CXXMethodDecl>(Best->Function); 14108 FoundDecl = Best->FoundDecl; 14109 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14110 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14111 return ExprError(); 14112 // If FoundDecl is different from Method (such as if one is a template 14113 // and the other a specialization), make sure DiagnoseUseOfDecl is 14114 // called on both. 14115 // FIXME: This would be more comprehensively addressed by modifying 14116 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14117 // being used. 14118 if (Method != FoundDecl.getDecl() && 14119 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14120 return ExprError(); 14121 break; 14122 14123 case OR_No_Viable_Function: 14124 CandidateSet.NoteCandidates( 14125 PartialDiagnosticAt( 14126 UnresExpr->getMemberLoc(), 14127 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14128 << DeclName << MemExprE->getSourceRange()), 14129 *this, OCD_AllCandidates, Args); 14130 // FIXME: Leaking incoming expressions! 14131 return ExprError(); 14132 14133 case OR_Ambiguous: 14134 CandidateSet.NoteCandidates( 14135 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14136 PDiag(diag::err_ovl_ambiguous_member_call) 14137 << DeclName << MemExprE->getSourceRange()), 14138 *this, OCD_AmbiguousCandidates, Args); 14139 // FIXME: Leaking incoming expressions! 14140 return ExprError(); 14141 14142 case OR_Deleted: 14143 CandidateSet.NoteCandidates( 14144 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14145 PDiag(diag::err_ovl_deleted_member_call) 14146 << DeclName << MemExprE->getSourceRange()), 14147 *this, OCD_AllCandidates, Args); 14148 // FIXME: Leaking incoming expressions! 14149 return ExprError(); 14150 } 14151 14152 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14153 14154 // If overload resolution picked a static member, build a 14155 // non-member call based on that function. 14156 if (Method->isStatic()) { 14157 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14158 RParenLoc); 14159 } 14160 14161 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14162 } 14163 14164 QualType ResultType = Method->getReturnType(); 14165 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14166 ResultType = ResultType.getNonLValueExprType(Context); 14167 14168 assert(Method && "Member call to something that isn't a method?"); 14169 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14170 CXXMemberCallExpr *TheCall = 14171 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 14172 RParenLoc, Proto->getNumParams()); 14173 14174 // Check for a valid return type. 14175 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14176 TheCall, Method)) 14177 return ExprError(); 14178 14179 // Convert the object argument (for a non-static member function call). 14180 // We only need to do this if there was actually an overload; otherwise 14181 // it was done at lookup. 14182 if (!Method->isStatic()) { 14183 ExprResult ObjectArg = 14184 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14185 FoundDecl, Method); 14186 if (ObjectArg.isInvalid()) 14187 return ExprError(); 14188 MemExpr->setBase(ObjectArg.get()); 14189 } 14190 14191 // Convert the rest of the arguments 14192 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14193 RParenLoc)) 14194 return ExprError(); 14195 14196 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14197 14198 if (CheckFunctionCall(Method, TheCall, Proto)) 14199 return ExprError(); 14200 14201 // In the case the method to call was not selected by the overloading 14202 // resolution process, we still need to handle the enable_if attribute. Do 14203 // that here, so it will not hide previous -- and more relevant -- errors. 14204 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14205 if (const EnableIfAttr *Attr = 14206 CheckEnableIf(Method, LParenLoc, Args, true)) { 14207 Diag(MemE->getMemberLoc(), 14208 diag::err_ovl_no_viable_member_function_in_call) 14209 << Method << Method->getSourceRange(); 14210 Diag(Method->getLocation(), 14211 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14212 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14213 return ExprError(); 14214 } 14215 } 14216 14217 if ((isa<CXXConstructorDecl>(CurContext) || 14218 isa<CXXDestructorDecl>(CurContext)) && 14219 TheCall->getMethodDecl()->isPure()) { 14220 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14221 14222 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14223 MemExpr->performsVirtualDispatch(getLangOpts())) { 14224 Diag(MemExpr->getBeginLoc(), 14225 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14226 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14227 << MD->getParent()->getDeclName(); 14228 14229 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14230 if (getLangOpts().AppleKext) 14231 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14232 << MD->getParent()->getDeclName() << MD->getDeclName(); 14233 } 14234 } 14235 14236 if (CXXDestructorDecl *DD = 14237 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14238 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14239 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14240 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14241 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14242 MemExpr->getMemberLoc()); 14243 } 14244 14245 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14246 TheCall->getMethodDecl()); 14247 } 14248 14249 /// BuildCallToObjectOfClassType - Build a call to an object of class 14250 /// type (C++ [over.call.object]), which can end up invoking an 14251 /// overloaded function call operator (@c operator()) or performing a 14252 /// user-defined conversion on the object argument. 14253 ExprResult 14254 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14255 SourceLocation LParenLoc, 14256 MultiExprArg Args, 14257 SourceLocation RParenLoc) { 14258 if (checkPlaceholderForOverload(*this, Obj)) 14259 return ExprError(); 14260 ExprResult Object = Obj; 14261 14262 UnbridgedCastsSet UnbridgedCasts; 14263 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14264 return ExprError(); 14265 14266 assert(Object.get()->getType()->isRecordType() && 14267 "Requires object type argument"); 14268 14269 // C++ [over.call.object]p1: 14270 // If the primary-expression E in the function call syntax 14271 // evaluates to a class object of type "cv T", then the set of 14272 // candidate functions includes at least the function call 14273 // operators of T. The function call operators of T are obtained by 14274 // ordinary lookup of the name operator() in the context of 14275 // (E).operator(). 14276 OverloadCandidateSet CandidateSet(LParenLoc, 14277 OverloadCandidateSet::CSK_Operator); 14278 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14279 14280 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14281 diag::err_incomplete_object_call, Object.get())) 14282 return true; 14283 14284 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14285 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14286 LookupQualifiedName(R, Record->getDecl()); 14287 R.suppressDiagnostics(); 14288 14289 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14290 Oper != OperEnd; ++Oper) { 14291 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14292 Object.get()->Classify(Context), Args, CandidateSet, 14293 /*SuppressUserConversion=*/false); 14294 } 14295 14296 // C++ [over.call.object]p2: 14297 // In addition, for each (non-explicit in C++0x) conversion function 14298 // declared in T of the form 14299 // 14300 // operator conversion-type-id () cv-qualifier; 14301 // 14302 // where cv-qualifier is the same cv-qualification as, or a 14303 // greater cv-qualification than, cv, and where conversion-type-id 14304 // denotes the type "pointer to function of (P1,...,Pn) returning 14305 // R", or the type "reference to pointer to function of 14306 // (P1,...,Pn) returning R", or the type "reference to function 14307 // of (P1,...,Pn) returning R", a surrogate call function [...] 14308 // is also considered as a candidate function. Similarly, 14309 // surrogate call functions are added to the set of candidate 14310 // functions for each conversion function declared in an 14311 // accessible base class provided the function is not hidden 14312 // within T by another intervening declaration. 14313 const auto &Conversions = 14314 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14315 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14316 NamedDecl *D = *I; 14317 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14318 if (isa<UsingShadowDecl>(D)) 14319 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14320 14321 // Skip over templated conversion functions; they aren't 14322 // surrogates. 14323 if (isa<FunctionTemplateDecl>(D)) 14324 continue; 14325 14326 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14327 if (!Conv->isExplicit()) { 14328 // Strip the reference type (if any) and then the pointer type (if 14329 // any) to get down to what might be a function type. 14330 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14331 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14332 ConvType = ConvPtrType->getPointeeType(); 14333 14334 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14335 { 14336 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14337 Object.get(), Args, CandidateSet); 14338 } 14339 } 14340 } 14341 14342 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14343 14344 // Perform overload resolution. 14345 OverloadCandidateSet::iterator Best; 14346 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14347 Best)) { 14348 case OR_Success: 14349 // Overload resolution succeeded; we'll build the appropriate call 14350 // below. 14351 break; 14352 14353 case OR_No_Viable_Function: { 14354 PartialDiagnostic PD = 14355 CandidateSet.empty() 14356 ? (PDiag(diag::err_ovl_no_oper) 14357 << Object.get()->getType() << /*call*/ 1 14358 << Object.get()->getSourceRange()) 14359 : (PDiag(diag::err_ovl_no_viable_object_call) 14360 << Object.get()->getType() << Object.get()->getSourceRange()); 14361 CandidateSet.NoteCandidates( 14362 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14363 OCD_AllCandidates, Args); 14364 break; 14365 } 14366 case OR_Ambiguous: 14367 CandidateSet.NoteCandidates( 14368 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14369 PDiag(diag::err_ovl_ambiguous_object_call) 14370 << Object.get()->getType() 14371 << Object.get()->getSourceRange()), 14372 *this, OCD_AmbiguousCandidates, Args); 14373 break; 14374 14375 case OR_Deleted: 14376 CandidateSet.NoteCandidates( 14377 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14378 PDiag(diag::err_ovl_deleted_object_call) 14379 << Object.get()->getType() 14380 << Object.get()->getSourceRange()), 14381 *this, OCD_AllCandidates, Args); 14382 break; 14383 } 14384 14385 if (Best == CandidateSet.end()) 14386 return true; 14387 14388 UnbridgedCasts.restore(); 14389 14390 if (Best->Function == nullptr) { 14391 // Since there is no function declaration, this is one of the 14392 // surrogate candidates. Dig out the conversion function. 14393 CXXConversionDecl *Conv 14394 = cast<CXXConversionDecl>( 14395 Best->Conversions[0].UserDefined.ConversionFunction); 14396 14397 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14398 Best->FoundDecl); 14399 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14400 return ExprError(); 14401 assert(Conv == Best->FoundDecl.getDecl() && 14402 "Found Decl & conversion-to-functionptr should be same, right?!"); 14403 // We selected one of the surrogate functions that converts the 14404 // object parameter to a function pointer. Perform the conversion 14405 // on the object argument, then let BuildCallExpr finish the job. 14406 14407 // Create an implicit member expr to refer to the conversion operator. 14408 // and then call it. 14409 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14410 Conv, HadMultipleCandidates); 14411 if (Call.isInvalid()) 14412 return ExprError(); 14413 // Record usage of conversion in an implicit cast. 14414 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14415 CK_UserDefinedConversion, Call.get(), 14416 nullptr, VK_RValue); 14417 14418 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14419 } 14420 14421 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14422 14423 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14424 // that calls this method, using Object for the implicit object 14425 // parameter and passing along the remaining arguments. 14426 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14427 14428 // An error diagnostic has already been printed when parsing the declaration. 14429 if (Method->isInvalidDecl()) 14430 return ExprError(); 14431 14432 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14433 unsigned NumParams = Proto->getNumParams(); 14434 14435 DeclarationNameInfo OpLocInfo( 14436 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14437 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14438 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14439 Obj, HadMultipleCandidates, 14440 OpLocInfo.getLoc(), 14441 OpLocInfo.getInfo()); 14442 if (NewFn.isInvalid()) 14443 return true; 14444 14445 // The number of argument slots to allocate in the call. If we have default 14446 // arguments we need to allocate space for them as well. We additionally 14447 // need one more slot for the object parameter. 14448 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14449 14450 // Build the full argument list for the method call (the implicit object 14451 // parameter is placed at the beginning of the list). 14452 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14453 14454 bool IsError = false; 14455 14456 // Initialize the implicit object parameter. 14457 ExprResult ObjRes = 14458 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14459 Best->FoundDecl, Method); 14460 if (ObjRes.isInvalid()) 14461 IsError = true; 14462 else 14463 Object = ObjRes; 14464 MethodArgs[0] = Object.get(); 14465 14466 // Check the argument types. 14467 for (unsigned i = 0; i != NumParams; i++) { 14468 Expr *Arg; 14469 if (i < Args.size()) { 14470 Arg = Args[i]; 14471 14472 // Pass the argument. 14473 14474 ExprResult InputInit 14475 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14476 Context, 14477 Method->getParamDecl(i)), 14478 SourceLocation(), Arg); 14479 14480 IsError |= InputInit.isInvalid(); 14481 Arg = InputInit.getAs<Expr>(); 14482 } else { 14483 ExprResult DefArg 14484 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14485 if (DefArg.isInvalid()) { 14486 IsError = true; 14487 break; 14488 } 14489 14490 Arg = DefArg.getAs<Expr>(); 14491 } 14492 14493 MethodArgs[i + 1] = Arg; 14494 } 14495 14496 // If this is a variadic call, handle args passed through "...". 14497 if (Proto->isVariadic()) { 14498 // Promote the arguments (C99 6.5.2.2p7). 14499 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14500 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14501 nullptr); 14502 IsError |= Arg.isInvalid(); 14503 MethodArgs[i + 1] = Arg.get(); 14504 } 14505 } 14506 14507 if (IsError) 14508 return true; 14509 14510 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14511 14512 // Once we've built TheCall, all of the expressions are properly owned. 14513 QualType ResultTy = Method->getReturnType(); 14514 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14515 ResultTy = ResultTy.getNonLValueExprType(Context); 14516 14517 CXXOperatorCallExpr *TheCall = 14518 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14519 ResultTy, VK, RParenLoc, CurFPFeatures); 14520 14521 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14522 return true; 14523 14524 if (CheckFunctionCall(Method, TheCall, Proto)) 14525 return true; 14526 14527 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14528 } 14529 14530 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14531 /// (if one exists), where @c Base is an expression of class type and 14532 /// @c Member is the name of the member we're trying to find. 14533 ExprResult 14534 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14535 bool *NoArrowOperatorFound) { 14536 assert(Base->getType()->isRecordType() && 14537 "left-hand side must have class type"); 14538 14539 if (checkPlaceholderForOverload(*this, Base)) 14540 return ExprError(); 14541 14542 SourceLocation Loc = Base->getExprLoc(); 14543 14544 // C++ [over.ref]p1: 14545 // 14546 // [...] An expression x->m is interpreted as (x.operator->())->m 14547 // for a class object x of type T if T::operator->() exists and if 14548 // the operator is selected as the best match function by the 14549 // overload resolution mechanism (13.3). 14550 DeclarationName OpName = 14551 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14552 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14553 14554 if (RequireCompleteType(Loc, Base->getType(), 14555 diag::err_typecheck_incomplete_tag, Base)) 14556 return ExprError(); 14557 14558 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14559 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14560 R.suppressDiagnostics(); 14561 14562 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14563 Oper != OperEnd; ++Oper) { 14564 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14565 None, CandidateSet, /*SuppressUserConversion=*/false); 14566 } 14567 14568 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14569 14570 // Perform overload resolution. 14571 OverloadCandidateSet::iterator Best; 14572 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14573 case OR_Success: 14574 // Overload resolution succeeded; we'll build the call below. 14575 break; 14576 14577 case OR_No_Viable_Function: { 14578 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14579 if (CandidateSet.empty()) { 14580 QualType BaseType = Base->getType(); 14581 if (NoArrowOperatorFound) { 14582 // Report this specific error to the caller instead of emitting a 14583 // diagnostic, as requested. 14584 *NoArrowOperatorFound = true; 14585 return ExprError(); 14586 } 14587 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14588 << BaseType << Base->getSourceRange(); 14589 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14590 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14591 << FixItHint::CreateReplacement(OpLoc, "."); 14592 } 14593 } else 14594 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14595 << "operator->" << Base->getSourceRange(); 14596 CandidateSet.NoteCandidates(*this, Base, Cands); 14597 return ExprError(); 14598 } 14599 case OR_Ambiguous: 14600 CandidateSet.NoteCandidates( 14601 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14602 << "->" << Base->getType() 14603 << Base->getSourceRange()), 14604 *this, OCD_AmbiguousCandidates, Base); 14605 return ExprError(); 14606 14607 case OR_Deleted: 14608 CandidateSet.NoteCandidates( 14609 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14610 << "->" << Base->getSourceRange()), 14611 *this, OCD_AllCandidates, Base); 14612 return ExprError(); 14613 } 14614 14615 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14616 14617 // Convert the object parameter. 14618 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14619 ExprResult BaseResult = 14620 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14621 Best->FoundDecl, Method); 14622 if (BaseResult.isInvalid()) 14623 return ExprError(); 14624 Base = BaseResult.get(); 14625 14626 // Build the operator call. 14627 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14628 Base, HadMultipleCandidates, OpLoc); 14629 if (FnExpr.isInvalid()) 14630 return ExprError(); 14631 14632 QualType ResultTy = Method->getReturnType(); 14633 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14634 ResultTy = ResultTy.getNonLValueExprType(Context); 14635 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14636 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, CurFPFeatures); 14637 14638 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14639 return ExprError(); 14640 14641 if (CheckFunctionCall(Method, TheCall, 14642 Method->getType()->castAs<FunctionProtoType>())) 14643 return ExprError(); 14644 14645 return MaybeBindToTemporary(TheCall); 14646 } 14647 14648 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14649 /// a literal operator described by the provided lookup results. 14650 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14651 DeclarationNameInfo &SuffixInfo, 14652 ArrayRef<Expr*> Args, 14653 SourceLocation LitEndLoc, 14654 TemplateArgumentListInfo *TemplateArgs) { 14655 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14656 14657 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14658 OverloadCandidateSet::CSK_Normal); 14659 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14660 TemplateArgs); 14661 14662 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14663 14664 // Perform overload resolution. This will usually be trivial, but might need 14665 // to perform substitutions for a literal operator template. 14666 OverloadCandidateSet::iterator Best; 14667 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14668 case OR_Success: 14669 case OR_Deleted: 14670 break; 14671 14672 case OR_No_Viable_Function: 14673 CandidateSet.NoteCandidates( 14674 PartialDiagnosticAt(UDSuffixLoc, 14675 PDiag(diag::err_ovl_no_viable_function_in_call) 14676 << R.getLookupName()), 14677 *this, OCD_AllCandidates, Args); 14678 return ExprError(); 14679 14680 case OR_Ambiguous: 14681 CandidateSet.NoteCandidates( 14682 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14683 << R.getLookupName()), 14684 *this, OCD_AmbiguousCandidates, Args); 14685 return ExprError(); 14686 } 14687 14688 FunctionDecl *FD = Best->Function; 14689 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14690 nullptr, HadMultipleCandidates, 14691 SuffixInfo.getLoc(), 14692 SuffixInfo.getInfo()); 14693 if (Fn.isInvalid()) 14694 return true; 14695 14696 // Check the argument types. This should almost always be a no-op, except 14697 // that array-to-pointer decay is applied to string literals. 14698 Expr *ConvArgs[2]; 14699 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14700 ExprResult InputInit = PerformCopyInitialization( 14701 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14702 SourceLocation(), Args[ArgIdx]); 14703 if (InputInit.isInvalid()) 14704 return true; 14705 ConvArgs[ArgIdx] = InputInit.get(); 14706 } 14707 14708 QualType ResultTy = FD->getReturnType(); 14709 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14710 ResultTy = ResultTy.getNonLValueExprType(Context); 14711 14712 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14713 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14714 VK, LitEndLoc, UDSuffixLoc); 14715 14716 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14717 return ExprError(); 14718 14719 if (CheckFunctionCall(FD, UDL, nullptr)) 14720 return ExprError(); 14721 14722 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14723 } 14724 14725 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14726 /// given LookupResult is non-empty, it is assumed to describe a member which 14727 /// will be invoked. Otherwise, the function will be found via argument 14728 /// dependent lookup. 14729 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14730 /// otherwise CallExpr is set to ExprError() and some non-success value 14731 /// is returned. 14732 Sema::ForRangeStatus 14733 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14734 SourceLocation RangeLoc, 14735 const DeclarationNameInfo &NameInfo, 14736 LookupResult &MemberLookup, 14737 OverloadCandidateSet *CandidateSet, 14738 Expr *Range, ExprResult *CallExpr) { 14739 Scope *S = nullptr; 14740 14741 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14742 if (!MemberLookup.empty()) { 14743 ExprResult MemberRef = 14744 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14745 /*IsPtr=*/false, CXXScopeSpec(), 14746 /*TemplateKWLoc=*/SourceLocation(), 14747 /*FirstQualifierInScope=*/nullptr, 14748 MemberLookup, 14749 /*TemplateArgs=*/nullptr, S); 14750 if (MemberRef.isInvalid()) { 14751 *CallExpr = ExprError(); 14752 return FRS_DiagnosticIssued; 14753 } 14754 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14755 if (CallExpr->isInvalid()) { 14756 *CallExpr = ExprError(); 14757 return FRS_DiagnosticIssued; 14758 } 14759 } else { 14760 UnresolvedSet<0> FoundNames; 14761 UnresolvedLookupExpr *Fn = 14762 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14763 NestedNameSpecifierLoc(), NameInfo, 14764 /*NeedsADL=*/true, /*Overloaded=*/false, 14765 FoundNames.begin(), FoundNames.end()); 14766 14767 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14768 CandidateSet, CallExpr); 14769 if (CandidateSet->empty() || CandidateSetError) { 14770 *CallExpr = ExprError(); 14771 return FRS_NoViableFunction; 14772 } 14773 OverloadCandidateSet::iterator Best; 14774 OverloadingResult OverloadResult = 14775 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14776 14777 if (OverloadResult == OR_No_Viable_Function) { 14778 *CallExpr = ExprError(); 14779 return FRS_NoViableFunction; 14780 } 14781 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14782 Loc, nullptr, CandidateSet, &Best, 14783 OverloadResult, 14784 /*AllowTypoCorrection=*/false); 14785 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14786 *CallExpr = ExprError(); 14787 return FRS_DiagnosticIssued; 14788 } 14789 } 14790 return FRS_Success; 14791 } 14792 14793 14794 /// FixOverloadedFunctionReference - E is an expression that refers to 14795 /// a C++ overloaded function (possibly with some parentheses and 14796 /// perhaps a '&' around it). We have resolved the overloaded function 14797 /// to the function declaration Fn, so patch up the expression E to 14798 /// refer (possibly indirectly) to Fn. Returns the new expr. 14799 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14800 FunctionDecl *Fn) { 14801 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14802 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14803 Found, Fn); 14804 if (SubExpr == PE->getSubExpr()) 14805 return PE; 14806 14807 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14808 } 14809 14810 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14811 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14812 Found, Fn); 14813 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14814 SubExpr->getType()) && 14815 "Implicit cast type cannot be determined from overload"); 14816 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14817 if (SubExpr == ICE->getSubExpr()) 14818 return ICE; 14819 14820 return ImplicitCastExpr::Create(Context, ICE->getType(), 14821 ICE->getCastKind(), 14822 SubExpr, nullptr, 14823 ICE->getValueKind()); 14824 } 14825 14826 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14827 if (!GSE->isResultDependent()) { 14828 Expr *SubExpr = 14829 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14830 if (SubExpr == GSE->getResultExpr()) 14831 return GSE; 14832 14833 // Replace the resulting type information before rebuilding the generic 14834 // selection expression. 14835 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14836 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14837 unsigned ResultIdx = GSE->getResultIndex(); 14838 AssocExprs[ResultIdx] = SubExpr; 14839 14840 return GenericSelectionExpr::Create( 14841 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14842 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14843 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14844 ResultIdx); 14845 } 14846 // Rather than fall through to the unreachable, return the original generic 14847 // selection expression. 14848 return GSE; 14849 } 14850 14851 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14852 assert(UnOp->getOpcode() == UO_AddrOf && 14853 "Can only take the address of an overloaded function"); 14854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14855 if (Method->isStatic()) { 14856 // Do nothing: static member functions aren't any different 14857 // from non-member functions. 14858 } else { 14859 // Fix the subexpression, which really has to be an 14860 // UnresolvedLookupExpr holding an overloaded member function 14861 // or template. 14862 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14863 Found, Fn); 14864 if (SubExpr == UnOp->getSubExpr()) 14865 return UnOp; 14866 14867 assert(isa<DeclRefExpr>(SubExpr) 14868 && "fixed to something other than a decl ref"); 14869 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14870 && "fixed to a member ref with no nested name qualifier"); 14871 14872 // We have taken the address of a pointer to member 14873 // function. Perform the computation here so that we get the 14874 // appropriate pointer to member type. 14875 QualType ClassType 14876 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14877 QualType MemPtrType 14878 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14879 // Under the MS ABI, lock down the inheritance model now. 14880 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14881 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14882 14883 return UnaryOperator::Create( 14884 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 14885 UnOp->getOperatorLoc(), false, CurFPFeatures); 14886 } 14887 } 14888 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14889 Found, Fn); 14890 if (SubExpr == UnOp->getSubExpr()) 14891 return UnOp; 14892 14893 return UnaryOperator::Create( 14894 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()), 14895 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), false, CurFPFeatures); 14896 } 14897 14898 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14899 // FIXME: avoid copy. 14900 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14901 if (ULE->hasExplicitTemplateArgs()) { 14902 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14903 TemplateArgs = &TemplateArgsBuffer; 14904 } 14905 14906 DeclRefExpr *DRE = 14907 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14908 ULE->getQualifierLoc(), Found.getDecl(), 14909 ULE->getTemplateKeywordLoc(), TemplateArgs); 14910 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14911 return DRE; 14912 } 14913 14914 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14915 // FIXME: avoid copy. 14916 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14917 if (MemExpr->hasExplicitTemplateArgs()) { 14918 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14919 TemplateArgs = &TemplateArgsBuffer; 14920 } 14921 14922 Expr *Base; 14923 14924 // If we're filling in a static method where we used to have an 14925 // implicit member access, rewrite to a simple decl ref. 14926 if (MemExpr->isImplicitAccess()) { 14927 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14928 DeclRefExpr *DRE = BuildDeclRefExpr( 14929 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14930 MemExpr->getQualifierLoc(), Found.getDecl(), 14931 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14932 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14933 return DRE; 14934 } else { 14935 SourceLocation Loc = MemExpr->getMemberLoc(); 14936 if (MemExpr->getQualifier()) 14937 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14938 Base = 14939 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14940 } 14941 } else 14942 Base = MemExpr->getBase(); 14943 14944 ExprValueKind valueKind; 14945 QualType type; 14946 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14947 valueKind = VK_LValue; 14948 type = Fn->getType(); 14949 } else { 14950 valueKind = VK_RValue; 14951 type = Context.BoundMemberTy; 14952 } 14953 14954 return BuildMemberExpr( 14955 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14956 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14957 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14958 type, valueKind, OK_Ordinary, TemplateArgs); 14959 } 14960 14961 llvm_unreachable("Invalid reference to overloaded function"); 14962 } 14963 14964 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14965 DeclAccessPair Found, 14966 FunctionDecl *Fn) { 14967 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14968 } 14969