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 CreateFunctionRefExpr( 53 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 54 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 55 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 56 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 57 return ExprError(); 58 // If FoundDecl is different from Fn (such as if one is a template 59 // and the other a specialization), make sure DiagnoseUseOfDecl is 60 // called on both. 61 // FIXME: This would be more comprehensively addressed by modifying 62 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 63 // being used. 64 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 65 return ExprError(); 66 DeclRefExpr *DRE = new (S.Context) 67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 73 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 74 S.ResolveExceptionSpec(Loc, FPT); 75 DRE->setType(Fn->getType()); 76 } 77 } 78 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 79 CK_FunctionToPointerDecay); 80 } 81 82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle, 86 bool AllowObjCWritebackConversion); 87 88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 89 QualType &ToType, 90 bool InOverloadResolution, 91 StandardConversionSequence &SCS, 92 bool CStyle); 93 static OverloadingResult 94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 95 UserDefinedConversionSequence& User, 96 OverloadCandidateSet& Conversions, 97 AllowedExplicit AllowExplicit, 98 bool AllowObjCConversionOnExplicit); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareQualificationConversions(Sema &S, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 static ImplicitConversionSequence::CompareKind 111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 112 const StandardConversionSequence& SCS1, 113 const StandardConversionSequence& SCS2); 114 115 /// GetConversionRank - Retrieve the implicit conversion rank 116 /// corresponding to the given implicit conversion kind. 117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 118 static const ImplicitConversionRank 119 Rank[(int)ICK_Num_Conversion_Kinds] = { 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Promotion, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Conversion, 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 "SVE Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion", 182 "Writeback conversion", 183 "OpenCL Zero Event Conversion", 184 "C specific type conversion", 185 "Incompatible pointer conversion" 186 }; 187 return Name[Kind]; 188 } 189 190 /// StandardConversionSequence - Set the standard conversion 191 /// sequence to the identity conversion. 192 void StandardConversionSequence::setAsIdentityConversion() { 193 First = ICK_Identity; 194 Second = ICK_Identity; 195 Third = ICK_Identity; 196 DeprecatedStringLiteralToCharPtr = false; 197 QualificationIncludesObjCLifetime = false; 198 ReferenceBinding = false; 199 DirectBinding = false; 200 IsLvalueReference = true; 201 BindsToFunctionLvalue = false; 202 BindsToRvalue = false; 203 BindsImplicitObjectArgumentWithoutRefQualifier = false; 204 ObjCLifetimeConversionBinding = false; 205 CopyConstructor = nullptr; 206 } 207 208 /// getRank - Retrieve the rank of this standard conversion sequence 209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 210 /// implicit conversions. 211 ImplicitConversionRank StandardConversionSequence::getRank() const { 212 ImplicitConversionRank Rank = ICR_Exact_Match; 213 if (GetConversionRank(First) > Rank) 214 Rank = GetConversionRank(First); 215 if (GetConversionRank(Second) > Rank) 216 Rank = GetConversionRank(Second); 217 if (GetConversionRank(Third) > Rank) 218 Rank = GetConversionRank(Third); 219 return Rank; 220 } 221 222 /// isPointerConversionToBool - Determines whether this conversion is 223 /// a conversion of a pointer or pointer-to-member to bool. This is 224 /// used as part of the ranking of standard conversion sequences 225 /// (C++ 13.3.3.2p4). 226 bool StandardConversionSequence::isPointerConversionToBool() const { 227 // Note that FromType has not necessarily been transformed by the 228 // array-to-pointer or function-to-pointer implicit conversions, so 229 // check for their presence as well as checking whether FromType is 230 // a pointer. 231 if (getToType(1)->isBooleanType() && 232 (getFromType()->isPointerType() || 233 getFromType()->isMemberPointerType() || 234 getFromType()->isObjCObjectPointerType() || 235 getFromType()->isBlockPointerType() || 236 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 237 return true; 238 239 return false; 240 } 241 242 /// isPointerConversionToVoidPointer - Determines whether this 243 /// conversion is a conversion of a pointer to a void pointer. This is 244 /// used as part of the ranking of standard conversion sequences (C++ 245 /// 13.3.3.2p4). 246 bool 247 StandardConversionSequence:: 248 isPointerConversionToVoidPointer(ASTContext& Context) const { 249 QualType FromType = getFromType(); 250 QualType ToType = getToType(1); 251 252 // Note that FromType has not necessarily been transformed by the 253 // array-to-pointer implicit conversion, so check for its presence 254 // and redo the conversion to get a pointer. 255 if (First == ICK_Array_To_Pointer) 256 FromType = Context.getArrayDecayedType(FromType); 257 258 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 259 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 260 return ToPtrType->getPointeeType()->isVoidType(); 261 262 return false; 263 } 264 265 /// Skip any implicit casts which could be either part of a narrowing conversion 266 /// or after one in an implicit conversion. 267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 268 const Expr *Converted) { 269 // We can have cleanups wrapping the converted expression; these need to be 270 // preserved so that destructors run if necessary. 271 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 272 Expr *Inner = 273 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 274 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 275 EWC->getObjects()); 276 } 277 278 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 279 switch (ICE->getCastKind()) { 280 case CK_NoOp: 281 case CK_IntegralCast: 282 case CK_IntegralToBoolean: 283 case CK_IntegralToFloating: 284 case CK_BooleanToSignedIntegral: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297 } 298 299 /// Check if this standard conversion sequence represents a narrowing 300 /// conversion, according to C++11 [dcl.init.list]p7. 301 /// 302 /// \param Ctx The AST context. 303 /// \param Converted The result of applying this standard conversion sequence. 304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305 /// value of the expression prior to the narrowing conversion. 306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307 /// type of the expression prior to the narrowing conversion. 308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 309 /// from floating point types to integral types should be ignored. 310 NarrowingKind StandardConversionSequence::getNarrowingKind( 311 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 312 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 320 // A conversion to an enumeration type is narrowing if the conversion to 321 // the underlying type is narrowing. This only arises for expressions of 322 // the form 'Enum{init}'. 323 if (auto *ET = ToType->getAs<EnumType>()) 324 ToType = ET->getDecl()->getIntegerType(); 325 326 switch (Second) { 327 // 'bool' is an integral type; dispatch to the right place to handle it. 328 case ICK_Boolean_Conversion: 329 if (FromType->isRealFloatingType()) 330 goto FloatingIntegralConversion; 331 if (FromType->isIntegralOrUnscopedEnumerationType()) 332 goto IntegralConversion; 333 // -- from a pointer type or pointer-to-member type to bool, or 334 return NK_Type_Narrowing; 335 336 // -- from a floating-point type to an integer type, or 337 // 338 // -- from an integer type or unscoped enumeration type to a floating-point 339 // type, except where the source is a constant expression and the actual 340 // value after conversion will fit into the target type and will produce 341 // the original value when converted back to the original type, or 342 case ICK_Floating_Integral: 343 FloatingIntegralConversion: 344 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 345 return NK_Type_Narrowing; 346 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 347 ToType->isRealFloatingType()) { 348 if (IgnoreFloatToIntegralConversion) 349 return NK_Not_Narrowing; 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 (Optional<llvm::APSInt> IntConstantValue = 358 Initializer->getIntegerConstantExpr(Ctx)) { 359 // Convert the integer to the floating type. 360 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 361 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 362 llvm::APFloat::rmNearestTiesToEven); 363 // And back. 364 llvm::APSInt ConvertedValue = *IntConstantValue; 365 bool ignored; 366 Result.convertToInteger(ConvertedValue, 367 llvm::APFloat::rmTowardZero, &ignored); 368 // If the resulting value is different, this was a narrowing conversion. 369 if (*IntConstantValue != ConvertedValue) { 370 ConstantValue = APValue(*IntConstantValue); 371 ConstantType = Initializer->getType(); 372 return NK_Constant_Narrowing; 373 } 374 } else { 375 // Variables are always narrowings. 376 return NK_Variable_Narrowing; 377 } 378 } 379 return NK_Not_Narrowing; 380 381 // -- from long double to double or float, or from double to float, except 382 // where the source is a constant expression and the actual value after 383 // conversion is within the range of values that can be represented (even 384 // if it cannot be represented exactly), or 385 case ICK_Floating_Conversion: 386 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 387 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 388 // FromType is larger than ToType. 389 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 390 391 // If it's value-dependent, we can't tell whether it's narrowing. 392 if (Initializer->isValueDependent()) 393 return NK_Dependent_Narrowing; 394 395 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 396 // Constant! 397 assert(ConstantValue.isFloat()); 398 llvm::APFloat FloatVal = ConstantValue.getFloat(); 399 // Convert the source value into the target type. 400 bool ignored; 401 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 402 Ctx.getFloatTypeSemantics(ToType), 403 llvm::APFloat::rmNearestTiesToEven, &ignored); 404 // If there was no overflow, the source value is within the range of 405 // values that can be represented. 406 if (ConvertStatus & llvm::APFloat::opOverflow) { 407 ConstantType = Initializer->getType(); 408 return NK_Constant_Narrowing; 409 } 410 } else { 411 return NK_Variable_Narrowing; 412 } 413 } 414 return NK_Not_Narrowing; 415 416 // -- from an integer type or unscoped enumeration type to an integer type 417 // that cannot represent all the values of the original type, except where 418 // the source is a constant expression and the actual value after 419 // conversion will fit into the target type and will produce the original 420 // value when converted back to the original type. 421 case ICK_Integral_Conversion: 422 IntegralConversion: { 423 assert(FromType->isIntegralOrUnscopedEnumerationType()); 424 assert(ToType->isIntegralOrUnscopedEnumerationType()); 425 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 426 const unsigned FromWidth = Ctx.getIntWidth(FromType); 427 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 428 const unsigned ToWidth = Ctx.getIntWidth(ToType); 429 430 if (FromWidth > ToWidth || 431 (FromWidth == ToWidth && FromSigned != ToSigned) || 432 (FromSigned && !ToSigned)) { 433 // Not all values of FromType can be represented in ToType. 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 Optional<llvm::APSInt> OptInitializerValue; 441 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 442 // Such conversions on variables are always narrowing. 443 return NK_Variable_Narrowing; 444 } 445 llvm::APSInt &InitializerValue = *OptInitializerValue; 446 bool Narrowing = false; 447 if (FromWidth < ToWidth) { 448 // Negative -> unsigned is narrowing. Otherwise, more bits is never 449 // narrowing. 450 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 451 Narrowing = true; 452 } else { 453 // Add a bit to the InitializerValue so we don't have to worry about 454 // signed vs. unsigned comparisons. 455 InitializerValue = InitializerValue.extend( 456 InitializerValue.getBitWidth() + 1); 457 // Convert the initializer to and from the target width and signed-ness. 458 llvm::APSInt ConvertedValue = InitializerValue; 459 ConvertedValue = ConvertedValue.trunc(ToWidth); 460 ConvertedValue.setIsSigned(ToSigned); 461 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 462 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 463 // If the result is different, this was a narrowing conversion. 464 if (ConvertedValue != InitializerValue) 465 Narrowing = true; 466 } 467 if (Narrowing) { 468 ConstantType = Initializer->getType(); 469 ConstantValue = APValue(InitializerValue); 470 return NK_Constant_Narrowing; 471 } 472 } 473 return NK_Not_Narrowing; 474 } 475 476 default: 477 // Other kinds of conversions are not narrowings. 478 return NK_Not_Narrowing; 479 } 480 } 481 482 /// dump - Print this standard conversion sequence to standard 483 /// error. Useful for debugging overloading issues. 484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 485 raw_ostream &OS = llvm::errs(); 486 bool PrintedSomething = false; 487 if (First != ICK_Identity) { 488 OS << GetImplicitConversionName(First); 489 PrintedSomething = true; 490 } 491 492 if (Second != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Second); 497 498 if (CopyConstructor) { 499 OS << " (by copy constructor)"; 500 } else if (DirectBinding) { 501 OS << " (direct reference binding)"; 502 } else if (ReferenceBinding) { 503 OS << " (reference binding)"; 504 } 505 PrintedSomething = true; 506 } 507 508 if (Third != ICK_Identity) { 509 if (PrintedSomething) { 510 OS << " -> "; 511 } 512 OS << GetImplicitConversionName(Third); 513 PrintedSomething = true; 514 } 515 516 if (!PrintedSomething) { 517 OS << "No conversions required"; 518 } 519 } 520 521 /// dump - Print this user-defined conversion sequence to standard 522 /// error. Useful for debugging overloading issues. 523 void UserDefinedConversionSequence::dump() const { 524 raw_ostream &OS = llvm::errs(); 525 if (Before.First || Before.Second || Before.Third) { 526 Before.dump(); 527 OS << " -> "; 528 } 529 if (ConversionFunction) 530 OS << '\'' << *ConversionFunction << '\''; 531 else 532 OS << "aggregate initialization"; 533 if (After.First || After.Second || After.Third) { 534 OS << " -> "; 535 After.dump(); 536 } 537 } 538 539 /// dump - Print this implicit conversion sequence to standard 540 /// error. Useful for debugging overloading issues. 541 void ImplicitConversionSequence::dump() const { 542 raw_ostream &OS = llvm::errs(); 543 if (hasInitializerListContainerType()) 544 OS << "Worst list element conversion: "; 545 switch (ConversionKind) { 546 case StandardConversion: 547 OS << "Standard conversion: "; 548 Standard.dump(); 549 break; 550 case UserDefinedConversion: 551 OS << "User-defined conversion: "; 552 UserDefined.dump(); 553 break; 554 case EllipsisConversion: 555 OS << "Ellipsis conversion"; 556 break; 557 case AmbiguousConversion: 558 OS << "Ambiguous conversion"; 559 break; 560 case BadConversion: 561 OS << "Bad conversion"; 562 break; 563 } 564 565 OS << "\n"; 566 } 567 568 void AmbiguousConversionSequence::construct() { 569 new (&conversions()) ConversionSet(); 570 } 571 572 void AmbiguousConversionSequence::destruct() { 573 conversions().~ConversionSet(); 574 } 575 576 void 577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 578 FromTypePtr = O.FromTypePtr; 579 ToTypePtr = O.ToTypePtr; 580 new (&conversions()) ConversionSet(O.conversions()); 581 } 582 583 namespace { 584 // Structure used by DeductionFailureInfo to store 585 // template argument information. 586 struct DFIArguments { 587 TemplateArgument FirstArg; 588 TemplateArgument SecondArg; 589 }; 590 // Structure used by DeductionFailureInfo to store 591 // template parameter and template argument information. 592 struct DFIParamWithArguments : DFIArguments { 593 TemplateParameter Param; 594 }; 595 // Structure used by DeductionFailureInfo to store template argument 596 // information and the index of the problematic call argument. 597 struct DFIDeducedMismatchArgs : DFIArguments { 598 TemplateArgumentList *TemplateArgs; 599 unsigned CallArgIndex; 600 }; 601 // Structure used by DeductionFailureInfo to store information about 602 // unsatisfied constraints. 603 struct CNSInfo { 604 TemplateArgumentList *TemplateArgs; 605 ConstraintSatisfaction Satisfaction; 606 }; 607 } 608 609 /// Convert from Sema's representation of template deduction information 610 /// to the form used in overload-candidate information. 611 DeductionFailureInfo 612 clang::MakeDeductionFailureInfo(ASTContext &Context, 613 Sema::TemplateDeductionResult TDK, 614 TemplateDeductionInfo &Info) { 615 DeductionFailureInfo Result; 616 Result.Result = static_cast<unsigned>(TDK); 617 Result.HasDiagnostic = false; 618 switch (TDK) { 619 case Sema::TDK_Invalid: 620 case Sema::TDK_InstantiationDepth: 621 case Sema::TDK_TooManyArguments: 622 case Sema::TDK_TooFewArguments: 623 case Sema::TDK_MiscellaneousDeductionFailure: 624 case Sema::TDK_CUDATargetMismatch: 625 Result.Data = nullptr; 626 break; 627 628 case Sema::TDK_Incomplete: 629 case Sema::TDK_InvalidExplicitArguments: 630 Result.Data = Info.Param.getOpaqueValue(); 631 break; 632 633 case Sema::TDK_DeducedMismatch: 634 case Sema::TDK_DeducedMismatchNested: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 auto *Saved = new (Context) DFIDeducedMismatchArgs; 637 Saved->FirstArg = Info.FirstArg; 638 Saved->SecondArg = Info.SecondArg; 639 Saved->TemplateArgs = Info.take(); 640 Saved->CallArgIndex = Info.CallArgIndex; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_NonDeducedMismatch: { 646 // FIXME: Should allocate from normal heap so that we can free this later. 647 DFIArguments *Saved = new (Context) DFIArguments; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_IncompletePack: 655 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 656 case Sema::TDK_Inconsistent: 657 case Sema::TDK_Underqualified: { 658 // FIXME: Should allocate from normal heap so that we can free this later. 659 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 660 Saved->Param = Info.Param; 661 Saved->FirstArg = Info.FirstArg; 662 Saved->SecondArg = Info.SecondArg; 663 Result.Data = Saved; 664 break; 665 } 666 667 case Sema::TDK_SubstitutionFailure: 668 Result.Data = Info.take(); 669 if (Info.hasSFINAEDiagnostic()) { 670 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 671 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 672 Info.takeSFINAEDiagnostic(*Diag); 673 Result.HasDiagnostic = true; 674 } 675 break; 676 677 case Sema::TDK_ConstraintsNotSatisfied: { 678 CNSInfo *Saved = new (Context) CNSInfo; 679 Saved->TemplateArgs = Info.take(); 680 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 681 Result.Data = Saved; 682 break; 683 } 684 685 case Sema::TDK_Success: 686 case Sema::TDK_NonDependentConversionFailure: 687 llvm_unreachable("not a deduction failure"); 688 } 689 690 return Result; 691 } 692 693 void DeductionFailureInfo::Destroy() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_CUDATargetMismatch: 703 case Sema::TDK_NonDependentConversionFailure: 704 break; 705 706 case Sema::TDK_IncompletePack: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_DeducedMismatch: 710 case Sema::TDK_DeducedMismatchNested: 711 case Sema::TDK_NonDeducedMismatch: 712 // FIXME: Destroy the data? 713 Data = nullptr; 714 break; 715 716 case Sema::TDK_SubstitutionFailure: 717 // FIXME: Destroy the template argument list? 718 Data = nullptr; 719 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 720 Diag->~PartialDiagnosticAt(); 721 HasDiagnostic = false; 722 } 723 break; 724 725 case Sema::TDK_ConstraintsNotSatisfied: 726 // FIXME: Destroy the template argument list? 727 Data = nullptr; 728 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 729 Diag->~PartialDiagnosticAt(); 730 HasDiagnostic = false; 731 } 732 break; 733 734 // Unhandled 735 case Sema::TDK_MiscellaneousDeductionFailure: 736 break; 737 } 738 } 739 740 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 741 if (HasDiagnostic) 742 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 743 return nullptr; 744 } 745 746 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 747 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 748 case Sema::TDK_Success: 749 case Sema::TDK_Invalid: 750 case Sema::TDK_InstantiationDepth: 751 case Sema::TDK_TooManyArguments: 752 case Sema::TDK_TooFewArguments: 753 case Sema::TDK_SubstitutionFailure: 754 case Sema::TDK_DeducedMismatch: 755 case Sema::TDK_DeducedMismatchNested: 756 case Sema::TDK_NonDeducedMismatch: 757 case Sema::TDK_CUDATargetMismatch: 758 case Sema::TDK_NonDependentConversionFailure: 759 case Sema::TDK_ConstraintsNotSatisfied: 760 return TemplateParameter(); 761 762 case Sema::TDK_Incomplete: 763 case Sema::TDK_InvalidExplicitArguments: 764 return TemplateParameter::getFromOpaqueValue(Data); 765 766 case Sema::TDK_IncompletePack: 767 case Sema::TDK_Inconsistent: 768 case Sema::TDK_Underqualified: 769 return static_cast<DFIParamWithArguments*>(Data)->Param; 770 771 // Unhandled 772 case Sema::TDK_MiscellaneousDeductionFailure: 773 break; 774 } 775 776 return TemplateParameter(); 777 } 778 779 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 780 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 781 case Sema::TDK_Success: 782 case Sema::TDK_Invalid: 783 case Sema::TDK_InstantiationDepth: 784 case Sema::TDK_TooManyArguments: 785 case Sema::TDK_TooFewArguments: 786 case Sema::TDK_Incomplete: 787 case Sema::TDK_IncompletePack: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_Inconsistent: 790 case Sema::TDK_Underqualified: 791 case Sema::TDK_NonDeducedMismatch: 792 case Sema::TDK_CUDATargetMismatch: 793 case Sema::TDK_NonDependentConversionFailure: 794 return nullptr; 795 796 case Sema::TDK_DeducedMismatch: 797 case Sema::TDK_DeducedMismatchNested: 798 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 799 800 case Sema::TDK_SubstitutionFailure: 801 return static_cast<TemplateArgumentList*>(Data); 802 803 case Sema::TDK_ConstraintsNotSatisfied: 804 return static_cast<CNSInfo*>(Data)->TemplateArgs; 805 806 // Unhandled 807 case Sema::TDK_MiscellaneousDeductionFailure: 808 break; 809 } 810 811 return nullptr; 812 } 813 814 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 815 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 816 case Sema::TDK_Success: 817 case Sema::TDK_Invalid: 818 case Sema::TDK_InstantiationDepth: 819 case Sema::TDK_Incomplete: 820 case Sema::TDK_TooManyArguments: 821 case Sema::TDK_TooFewArguments: 822 case Sema::TDK_InvalidExplicitArguments: 823 case Sema::TDK_SubstitutionFailure: 824 case Sema::TDK_CUDATargetMismatch: 825 case Sema::TDK_NonDependentConversionFailure: 826 case Sema::TDK_ConstraintsNotSatisfied: 827 return nullptr; 828 829 case Sema::TDK_IncompletePack: 830 case Sema::TDK_Inconsistent: 831 case Sema::TDK_Underqualified: 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 case Sema::TDK_NonDeducedMismatch: 835 return &static_cast<DFIArguments*>(Data)->FirstArg; 836 837 // Unhandled 838 case Sema::TDK_MiscellaneousDeductionFailure: 839 break; 840 } 841 842 return nullptr; 843 } 844 845 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 846 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 847 case Sema::TDK_Success: 848 case Sema::TDK_Invalid: 849 case Sema::TDK_InstantiationDepth: 850 case Sema::TDK_Incomplete: 851 case Sema::TDK_IncompletePack: 852 case Sema::TDK_TooManyArguments: 853 case Sema::TDK_TooFewArguments: 854 case Sema::TDK_InvalidExplicitArguments: 855 case Sema::TDK_SubstitutionFailure: 856 case Sema::TDK_CUDATargetMismatch: 857 case Sema::TDK_NonDependentConversionFailure: 858 case Sema::TDK_ConstraintsNotSatisfied: 859 return nullptr; 860 861 case Sema::TDK_Inconsistent: 862 case Sema::TDK_Underqualified: 863 case Sema::TDK_DeducedMismatch: 864 case Sema::TDK_DeducedMismatchNested: 865 case Sema::TDK_NonDeducedMismatch: 866 return &static_cast<DFIArguments*>(Data)->SecondArg; 867 868 // Unhandled 869 case Sema::TDK_MiscellaneousDeductionFailure: 870 break; 871 } 872 873 return nullptr; 874 } 875 876 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 877 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 878 case Sema::TDK_DeducedMismatch: 879 case Sema::TDK_DeducedMismatchNested: 880 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 881 882 default: 883 return llvm::None; 884 } 885 } 886 887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 888 OverloadedOperatorKind Op) { 889 if (!AllowRewrittenCandidates) 890 return false; 891 return Op == OO_EqualEqual || Op == OO_Spaceship; 892 } 893 894 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 895 ASTContext &Ctx, const FunctionDecl *FD) { 896 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 897 return false; 898 // Don't bother adding a reversed candidate that can never be a better 899 // match than the non-reversed version. 900 return FD->getNumParams() != 2 || 901 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 902 FD->getParamDecl(1)->getType()) || 903 FD->hasAttr<EnableIfAttr>(); 904 } 905 906 void OverloadCandidateSet::destroyCandidates() { 907 for (iterator i = begin(), e = end(); i != e; ++i) { 908 for (auto &C : i->Conversions) 909 C.~ImplicitConversionSequence(); 910 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 911 i->DeductionFailure.Destroy(); 912 } 913 } 914 915 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 916 destroyCandidates(); 917 SlabAllocator.Reset(); 918 NumInlineBytesUsed = 0; 919 Candidates.clear(); 920 Functions.clear(); 921 Kind = CSK; 922 } 923 924 namespace { 925 class UnbridgedCastsSet { 926 struct Entry { 927 Expr **Addr; 928 Expr *Saved; 929 }; 930 SmallVector<Entry, 2> Entries; 931 932 public: 933 void save(Sema &S, Expr *&E) { 934 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 935 Entry entry = { &E, E }; 936 Entries.push_back(entry); 937 E = S.stripARCUnbridgedCast(E); 938 } 939 940 void restore() { 941 for (SmallVectorImpl<Entry>::iterator 942 i = Entries.begin(), e = Entries.end(); i != e; ++i) 943 *i->Addr = i->Saved; 944 } 945 }; 946 } 947 948 /// checkPlaceholderForOverload - Do any interesting placeholder-like 949 /// preprocessing on the given expression. 950 /// 951 /// \param unbridgedCasts a collection to which to add unbridged casts; 952 /// without this, they will be immediately diagnosed as errors 953 /// 954 /// Return true on unrecoverable error. 955 static bool 956 checkPlaceholderForOverload(Sema &S, Expr *&E, 957 UnbridgedCastsSet *unbridgedCasts = nullptr) { 958 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 959 // We can't handle overloaded expressions here because overload 960 // resolution might reasonably tweak them. 961 if (placeholder->getKind() == BuiltinType::Overload) return false; 962 963 // If the context potentially accepts unbridged ARC casts, strip 964 // the unbridged cast and add it to the collection for later restoration. 965 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 966 unbridgedCasts) { 967 unbridgedCasts->save(S, E); 968 return false; 969 } 970 971 // Go ahead and check everything else. 972 ExprResult result = S.CheckPlaceholderExpr(E); 973 if (result.isInvalid()) 974 return true; 975 976 E = result.get(); 977 return false; 978 } 979 980 // Nothing to do. 981 return false; 982 } 983 984 /// checkArgPlaceholdersForOverload - Check a set of call operands for 985 /// placeholders. 986 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 987 UnbridgedCastsSet &unbridged) { 988 for (unsigned i = 0, e = Args.size(); i != e; ++i) 989 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 990 return true; 991 992 return false; 993 } 994 995 // Figure out the to-translation-unit depth for this function declaration for 996 // the purpose of seeing if they differ by constraints. This isn't the same as 997 // getTemplateDepth, because it includes already instantiated parents. 998 static unsigned CalculateTemplateDepthForConstraints(Sema &S, 999 FunctionDecl *FD) { 1000 MultiLevelTemplateArgumentList MLTAL = 1001 S.getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary*/ true, 1002 /*Pattern*/ nullptr, 1003 /*LookBeyondLambda*/ true); 1004 return MLTAL.getNumSubstitutedLevels(); 1005 } 1006 1007 // Friend definitions can appear identical but be different declarations based 1008 // on the last sentence of the rule below (others included for clarification): 1009 // C++20 [temp.friend] p9: A non-template friend declaration 1010 // with a requires-clause shall be a definition. A friend function template 1011 // with a constraint that depends on a template parameter from an enclosing 1012 // template shall be a definition. Such a constrained friend function or 1013 // function template declaration does not declare the same function or function 1014 // template as a declaration in any other scope. 1015 static bool FriendsDifferByConstraints(Sema &S, DeclContext *CurContext, 1016 FunctionDecl *Old, FunctionDecl *New, 1017 Scope *Scope) { 1018 // If these aren't friends, than they aren't friends that differe by 1019 // constraints. 1020 if (!Old->getFriendObjectKind() || !New->getFriendObjectKind()) 1021 return false; 1022 1023 // If the the two functions share lexical declaration context, they are not in 1024 // separate instantations, and thus in the same scope. 1025 if (New->getLexicalDeclContext() == Old->getLexicalDeclContext()) 1026 return false; 1027 1028 if (!Old->getDescribedFunctionTemplate()) { 1029 assert(!New->getDescribedFunctionTemplate() && 1030 "How would these be the same if they aren't both templates?"); 1031 1032 // If these friends don't have constraints, they aren't constrained, and 1033 // thus don't fall under temp.friend p9. Else the simple presence of a 1034 // constraint makes them unique. 1035 return Old->getTrailingRequiresClause(); 1036 } 1037 1038 SmallVector<const Expr *, 3> OldAC; 1039 Old->getDescribedFunctionTemplate()->getAssociatedConstraints(OldAC); 1040 1041 #ifndef NDEBUG 1042 SmallVector<const Expr *, 3> NewAC; 1043 New->getDescribedFunctionTemplate()->getAssociatedConstraints(NewAC); 1044 assert(OldAC.size() == NewAC.size() && 1045 "Difference should have been noticed earlier if sizes of constraints " 1046 "aren't the same"); 1047 #endif 1048 // If there are no constraints, these are not constrained friend function or 1049 // friend function templates. 1050 if (OldAC.size() == 0) 1051 return false; 1052 1053 unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(S, Old); 1054 1055 // At this point, if the constrained function template declaration depends on 1056 // a template parameter from an enclosing template, they are not the same 1057 // function. Since these were deemed identical before we got here, we only 1058 // have to look into 1 side to see if they refer to a containing template. 1059 for (const Expr *Constraint : OldAC) 1060 if (S.ConstraintExpressionDependsOnEnclosingTemplate(OldTemplateDepth, 1061 Constraint)) 1062 return true; 1063 1064 return false; 1065 } 1066 1067 /// Determine whether the given New declaration is an overload of the 1068 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 1069 /// New and Old cannot be overloaded, e.g., if New has the same signature as 1070 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 1071 /// functions (or function templates) at all. When it does return Ovl_Match or 1072 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1073 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1074 /// declaration. 1075 /// 1076 /// Example: Given the following input: 1077 /// 1078 /// void f(int, float); // #1 1079 /// void f(int, int); // #2 1080 /// int f(int, int); // #3 1081 /// 1082 /// When we process #1, there is no previous declaration of "f", so IsOverload 1083 /// will not be used. 1084 /// 1085 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1086 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1087 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1088 /// unchanged. 1089 /// 1090 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1091 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1092 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1093 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1094 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1095 /// 1096 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1097 /// by a using declaration. The rules for whether to hide shadow declarations 1098 /// ignore some properties which otherwise figure into a function template's 1099 /// signature. 1100 Sema::OverloadKind 1101 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1102 NamedDecl *&Match, bool NewIsUsingDecl) { 1103 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1104 I != E; ++I) { 1105 NamedDecl *OldD = *I; 1106 1107 bool OldIsUsingDecl = false; 1108 if (isa<UsingShadowDecl>(OldD)) { 1109 OldIsUsingDecl = true; 1110 1111 // We can always introduce two using declarations into the same 1112 // context, even if they have identical signatures. 1113 if (NewIsUsingDecl) continue; 1114 1115 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1116 } 1117 1118 // A using-declaration does not conflict with another declaration 1119 // if one of them is hidden. 1120 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1121 continue; 1122 1123 // If either declaration was introduced by a using declaration, 1124 // we'll need to use slightly different rules for matching. 1125 // Essentially, these rules are the normal rules, except that 1126 // function templates hide function templates with different 1127 // return types or template parameter lists. 1128 bool UseMemberUsingDeclRules = 1129 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1130 !New->getFriendObjectKind(); 1131 1132 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1133 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1134 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1135 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1136 continue; 1137 } 1138 1139 if (!isa<FunctionTemplateDecl>(OldD) && 1140 !shouldLinkPossiblyHiddenDecl(*I, New)) 1141 continue; 1142 1143 // C++20 [temp.friend] p9: A non-template friend declaration with a 1144 // requires-clause shall be a definition. A friend function template 1145 // with a constraint that depends on a template parameter from an 1146 // enclosing template shall be a definition. Such a constrained friend 1147 // function or function template declaration does not declare the same 1148 // function or function template as a declaration in any other scope. 1149 if (FriendsDifferByConstraints(*this, CurContext, OldF, New, S)) 1150 continue; 1151 1152 Match = *I; 1153 return Ovl_Match; 1154 } 1155 1156 // Builtins that have custom typechecking or have a reference should 1157 // not be overloadable or redeclarable. 1158 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1159 Match = *I; 1160 return Ovl_NonFunction; 1161 } 1162 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1163 // We can overload with these, which can show up when doing 1164 // redeclaration checks for UsingDecls. 1165 assert(Old.getLookupKind() == LookupUsingDeclName); 1166 } else if (isa<TagDecl>(OldD)) { 1167 // We can always overload with tags by hiding them. 1168 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1169 // Optimistically assume that an unresolved using decl will 1170 // overload; if it doesn't, we'll have to diagnose during 1171 // template instantiation. 1172 // 1173 // Exception: if the scope is dependent and this is not a class 1174 // member, the using declaration can only introduce an enumerator. 1175 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1176 Match = *I; 1177 return Ovl_NonFunction; 1178 } 1179 } else { 1180 // (C++ 13p1): 1181 // Only function declarations can be overloaded; object and type 1182 // declarations cannot be overloaded. 1183 Match = *I; 1184 return Ovl_NonFunction; 1185 } 1186 } 1187 1188 // C++ [temp.friend]p1: 1189 // For a friend function declaration that is not a template declaration: 1190 // -- if the name of the friend is a qualified or unqualified template-id, 1191 // [...], otherwise 1192 // -- if the name of the friend is a qualified-id and a matching 1193 // non-template function is found in the specified class or namespace, 1194 // the friend declaration refers to that function, otherwise, 1195 // -- if the name of the friend is a qualified-id and a matching function 1196 // template is found in the specified class or namespace, the friend 1197 // declaration refers to the deduced specialization of that function 1198 // template, otherwise 1199 // -- the name shall be an unqualified-id [...] 1200 // If we get here for a qualified friend declaration, we've just reached the 1201 // third bullet. If the type of the friend is dependent, skip this lookup 1202 // until instantiation. 1203 if (New->getFriendObjectKind() && New->getQualifier() && 1204 !New->getDescribedFunctionTemplate() && 1205 !New->getDependentSpecializationInfo() && 1206 !New->getType()->isDependentType()) { 1207 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1208 TemplateSpecResult.addAllDecls(Old); 1209 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1210 /*QualifiedFriend*/true)) { 1211 New->setInvalidDecl(); 1212 return Ovl_Overload; 1213 } 1214 1215 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1216 return Ovl_Match; 1217 } 1218 1219 return Ovl_Overload; 1220 } 1221 1222 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1223 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1224 bool ConsiderRequiresClauses) { 1225 // C++ [basic.start.main]p2: This function shall not be overloaded. 1226 if (New->isMain()) 1227 return false; 1228 1229 // MSVCRT user defined entry points cannot be overloaded. 1230 if (New->isMSVCRTEntryPoint()) 1231 return false; 1232 1233 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1234 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1235 1236 // C++ [temp.fct]p2: 1237 // A function template can be overloaded with other function templates 1238 // and with normal (non-template) functions. 1239 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1240 return true; 1241 1242 // Is the function New an overload of the function Old? 1243 QualType OldQType = Context.getCanonicalType(Old->getType()); 1244 QualType NewQType = Context.getCanonicalType(New->getType()); 1245 1246 // Compare the signatures (C++ 1.3.10) of the two functions to 1247 // determine whether they are overloads. If we find any mismatch 1248 // in the signature, they are overloads. 1249 1250 // If either of these functions is a K&R-style function (no 1251 // prototype), then we consider them to have matching signatures. 1252 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1253 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1254 return false; 1255 1256 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1257 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1258 1259 // The signature of a function includes the types of its 1260 // parameters (C++ 1.3.10), which includes the presence or absence 1261 // of the ellipsis; see C++ DR 357). 1262 if (OldQType != NewQType && 1263 (OldType->getNumParams() != NewType->getNumParams() || 1264 OldType->isVariadic() != NewType->isVariadic() || 1265 !FunctionParamTypesAreEqual(OldType, NewType))) 1266 return true; 1267 1268 // C++ [temp.over.link]p4: 1269 // The signature of a function template consists of its function 1270 // signature, its return type and its template parameter list. The names 1271 // of the template parameters are significant only for establishing the 1272 // relationship between the template parameters and the rest of the 1273 // signature. 1274 // 1275 // We check the return type and template parameter lists for function 1276 // templates first; the remaining checks follow. 1277 // 1278 // However, we don't consider either of these when deciding whether 1279 // a member introduced by a shadow declaration is hidden. 1280 if (!UseMemberUsingDeclRules && NewTemplate && 1281 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1282 OldTemplate->getTemplateParameters(), 1283 false, TPL_TemplateMatch) || 1284 !Context.hasSameType(Old->getDeclaredReturnType(), 1285 New->getDeclaredReturnType()))) 1286 return true; 1287 1288 // If the function is a class member, its signature includes the 1289 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1290 // 1291 // As part of this, also check whether one of the member functions 1292 // is static, in which case they are not overloads (C++ 1293 // 13.1p2). While not part of the definition of the signature, 1294 // this check is important to determine whether these functions 1295 // can be overloaded. 1296 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1297 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1298 if (OldMethod && NewMethod && 1299 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1300 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1301 if (!UseMemberUsingDeclRules && 1302 (OldMethod->getRefQualifier() == RQ_None || 1303 NewMethod->getRefQualifier() == RQ_None)) { 1304 // C++0x [over.load]p2: 1305 // - Member function declarations with the same name and the same 1306 // parameter-type-list as well as member function template 1307 // declarations with the same name, the same parameter-type-list, and 1308 // the same template parameter lists cannot be overloaded if any of 1309 // them, but not all, have a ref-qualifier (8.3.5). 1310 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1311 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1312 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1313 } 1314 return true; 1315 } 1316 1317 // We may not have applied the implicit const for a constexpr member 1318 // function yet (because we haven't yet resolved whether this is a static 1319 // or non-static member function). Add it now, on the assumption that this 1320 // is a redeclaration of OldMethod. 1321 auto OldQuals = OldMethod->getMethodQualifiers(); 1322 auto NewQuals = NewMethod->getMethodQualifiers(); 1323 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1324 !isa<CXXConstructorDecl>(NewMethod)) 1325 NewQuals.addConst(); 1326 // We do not allow overloading based off of '__restrict'. 1327 OldQuals.removeRestrict(); 1328 NewQuals.removeRestrict(); 1329 if (OldQuals != NewQuals) 1330 return true; 1331 } 1332 1333 // Though pass_object_size is placed on parameters and takes an argument, we 1334 // consider it to be a function-level modifier for the sake of function 1335 // identity. Either the function has one or more parameters with 1336 // pass_object_size or it doesn't. 1337 if (functionHasPassObjectSizeParams(New) != 1338 functionHasPassObjectSizeParams(Old)) 1339 return true; 1340 1341 // enable_if attributes are an order-sensitive part of the signature. 1342 for (specific_attr_iterator<EnableIfAttr> 1343 NewI = New->specific_attr_begin<EnableIfAttr>(), 1344 NewE = New->specific_attr_end<EnableIfAttr>(), 1345 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1346 OldE = Old->specific_attr_end<EnableIfAttr>(); 1347 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1348 if (NewI == NewE || OldI == OldE) 1349 return true; 1350 llvm::FoldingSetNodeID NewID, OldID; 1351 NewI->getCond()->Profile(NewID, Context, true); 1352 OldI->getCond()->Profile(OldID, Context, true); 1353 if (NewID != OldID) 1354 return true; 1355 } 1356 1357 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1358 // Don't allow overloading of destructors. (In theory we could, but it 1359 // would be a giant change to clang.) 1360 if (!isa<CXXDestructorDecl>(New)) { 1361 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1362 OldTarget = IdentifyCUDATarget(Old); 1363 if (NewTarget != CFT_InvalidTarget) { 1364 assert((OldTarget != CFT_InvalidTarget) && 1365 "Unexpected invalid target."); 1366 1367 // Allow overloading of functions with same signature and different CUDA 1368 // target attributes. 1369 if (NewTarget != OldTarget) 1370 return true; 1371 } 1372 } 1373 } 1374 1375 if (ConsiderRequiresClauses) { 1376 Expr *NewRC = New->getTrailingRequiresClause(), 1377 *OldRC = Old->getTrailingRequiresClause(); 1378 if ((NewRC != nullptr) != (OldRC != nullptr)) 1379 // RC are most certainly different - these are overloads. 1380 return true; 1381 1382 if (NewRC) { 1383 llvm::FoldingSetNodeID NewID, OldID; 1384 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1385 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1386 if (NewID != OldID) 1387 // RCs are not equivalent - these are overloads. 1388 return true; 1389 } 1390 } 1391 1392 // The signatures match; this is not an overload. 1393 return false; 1394 } 1395 1396 /// Tries a user-defined conversion from From to ToType. 1397 /// 1398 /// Produces an implicit conversion sequence for when a standard conversion 1399 /// is not an option. See TryImplicitConversion for more information. 1400 static ImplicitConversionSequence 1401 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1402 bool SuppressUserConversions, 1403 AllowedExplicit AllowExplicit, 1404 bool InOverloadResolution, 1405 bool CStyle, 1406 bool AllowObjCWritebackConversion, 1407 bool AllowObjCConversionOnExplicit) { 1408 ImplicitConversionSequence ICS; 1409 1410 if (SuppressUserConversions) { 1411 // We're not in the case above, so there is no conversion that 1412 // we can perform. 1413 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1414 return ICS; 1415 } 1416 1417 // Attempt user-defined conversion. 1418 OverloadCandidateSet Conversions(From->getExprLoc(), 1419 OverloadCandidateSet::CSK_Normal); 1420 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1421 Conversions, AllowExplicit, 1422 AllowObjCConversionOnExplicit)) { 1423 case OR_Success: 1424 case OR_Deleted: 1425 ICS.setUserDefined(); 1426 // C++ [over.ics.user]p4: 1427 // A conversion of an expression of class type to the same class 1428 // type is given Exact Match rank, and a conversion of an 1429 // expression of class type to a base class of that type is 1430 // given Conversion rank, in spite of the fact that a copy 1431 // constructor (i.e., a user-defined conversion function) is 1432 // called for those cases. 1433 if (CXXConstructorDecl *Constructor 1434 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1435 QualType FromCanon 1436 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1437 QualType ToCanon 1438 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1439 if (Constructor->isCopyConstructor() && 1440 (FromCanon == ToCanon || 1441 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1442 // Turn this into a "standard" conversion sequence, so that it 1443 // gets ranked with standard conversion sequences. 1444 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1445 ICS.setStandard(); 1446 ICS.Standard.setAsIdentityConversion(); 1447 ICS.Standard.setFromType(From->getType()); 1448 ICS.Standard.setAllToTypes(ToType); 1449 ICS.Standard.CopyConstructor = Constructor; 1450 ICS.Standard.FoundCopyConstructor = Found; 1451 if (ToCanon != FromCanon) 1452 ICS.Standard.Second = ICK_Derived_To_Base; 1453 } 1454 } 1455 break; 1456 1457 case OR_Ambiguous: 1458 ICS.setAmbiguous(); 1459 ICS.Ambiguous.setFromType(From->getType()); 1460 ICS.Ambiguous.setToType(ToType); 1461 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1462 Cand != Conversions.end(); ++Cand) 1463 if (Cand->Best) 1464 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1465 break; 1466 1467 // Fall through. 1468 case OR_No_Viable_Function: 1469 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1470 break; 1471 } 1472 1473 return ICS; 1474 } 1475 1476 /// TryImplicitConversion - Attempt to perform an implicit conversion 1477 /// from the given expression (Expr) to the given type (ToType). This 1478 /// function returns an implicit conversion sequence that can be used 1479 /// to perform the initialization. Given 1480 /// 1481 /// void f(float f); 1482 /// void g(int i) { f(i); } 1483 /// 1484 /// this routine would produce an implicit conversion sequence to 1485 /// describe the initialization of f from i, which will be a standard 1486 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1487 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1488 // 1489 /// Note that this routine only determines how the conversion can be 1490 /// performed; it does not actually perform the conversion. As such, 1491 /// it will not produce any diagnostics if no conversion is available, 1492 /// but will instead return an implicit conversion sequence of kind 1493 /// "BadConversion". 1494 /// 1495 /// If @p SuppressUserConversions, then user-defined conversions are 1496 /// not permitted. 1497 /// If @p AllowExplicit, then explicit user-defined conversions are 1498 /// permitted. 1499 /// 1500 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1501 /// writeback conversion, which allows __autoreleasing id* parameters to 1502 /// be initialized with __strong id* or __weak id* arguments. 1503 static ImplicitConversionSequence 1504 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1505 bool SuppressUserConversions, 1506 AllowedExplicit AllowExplicit, 1507 bool InOverloadResolution, 1508 bool CStyle, 1509 bool AllowObjCWritebackConversion, 1510 bool AllowObjCConversionOnExplicit) { 1511 ImplicitConversionSequence ICS; 1512 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1513 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1514 ICS.setStandard(); 1515 return ICS; 1516 } 1517 1518 if (!S.getLangOpts().CPlusPlus) { 1519 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1520 return ICS; 1521 } 1522 1523 // C++ [over.ics.user]p4: 1524 // A conversion of an expression of class type to the same class 1525 // type is given Exact Match rank, and a conversion of an 1526 // expression of class type to a base class of that type is 1527 // given Conversion rank, in spite of the fact that a copy/move 1528 // constructor (i.e., a user-defined conversion function) is 1529 // called for those cases. 1530 QualType FromType = From->getType(); 1531 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1532 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1533 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1534 ICS.setStandard(); 1535 ICS.Standard.setAsIdentityConversion(); 1536 ICS.Standard.setFromType(FromType); 1537 ICS.Standard.setAllToTypes(ToType); 1538 1539 // We don't actually check at this point whether there is a valid 1540 // copy/move constructor, since overloading just assumes that it 1541 // exists. When we actually perform initialization, we'll find the 1542 // appropriate constructor to copy the returned object, if needed. 1543 ICS.Standard.CopyConstructor = nullptr; 1544 1545 // Determine whether this is considered a derived-to-base conversion. 1546 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1547 ICS.Standard.Second = ICK_Derived_To_Base; 1548 1549 return ICS; 1550 } 1551 1552 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1553 AllowExplicit, InOverloadResolution, CStyle, 1554 AllowObjCWritebackConversion, 1555 AllowObjCConversionOnExplicit); 1556 } 1557 1558 ImplicitConversionSequence 1559 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1560 bool SuppressUserConversions, 1561 AllowedExplicit AllowExplicit, 1562 bool InOverloadResolution, 1563 bool CStyle, 1564 bool AllowObjCWritebackConversion) { 1565 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1566 AllowExplicit, InOverloadResolution, CStyle, 1567 AllowObjCWritebackConversion, 1568 /*AllowObjCConversionOnExplicit=*/false); 1569 } 1570 1571 /// PerformImplicitConversion - Perform an implicit conversion of the 1572 /// expression From to the type ToType. Returns the 1573 /// converted expression. Flavor is the kind of conversion we're 1574 /// performing, used in the error message. If @p AllowExplicit, 1575 /// explicit user-defined conversions are permitted. 1576 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1577 AssignmentAction Action, 1578 bool AllowExplicit) { 1579 if (checkPlaceholderForOverload(*this, From)) 1580 return ExprError(); 1581 1582 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1583 bool AllowObjCWritebackConversion 1584 = getLangOpts().ObjCAutoRefCount && 1585 (Action == AA_Passing || Action == AA_Sending); 1586 if (getLangOpts().ObjC) 1587 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1588 From->getType(), From); 1589 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1590 *this, From, ToType, 1591 /*SuppressUserConversions=*/false, 1592 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1593 /*InOverloadResolution=*/false, 1594 /*CStyle=*/false, AllowObjCWritebackConversion, 1595 /*AllowObjCConversionOnExplicit=*/false); 1596 return PerformImplicitConversion(From, ToType, ICS, Action); 1597 } 1598 1599 /// Determine whether the conversion from FromType to ToType is a valid 1600 /// conversion that strips "noexcept" or "noreturn" off the nested function 1601 /// type. 1602 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1603 QualType &ResultTy) { 1604 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1605 return false; 1606 1607 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1608 // or F(t noexcept) -> F(t) 1609 // where F adds one of the following at most once: 1610 // - a pointer 1611 // - a member pointer 1612 // - a block pointer 1613 // Changes here need matching changes in FindCompositePointerType. 1614 CanQualType CanTo = Context.getCanonicalType(ToType); 1615 CanQualType CanFrom = Context.getCanonicalType(FromType); 1616 Type::TypeClass TyClass = CanTo->getTypeClass(); 1617 if (TyClass != CanFrom->getTypeClass()) return false; 1618 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1619 if (TyClass == Type::Pointer) { 1620 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1621 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1622 } else if (TyClass == Type::BlockPointer) { 1623 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1624 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1625 } else if (TyClass == Type::MemberPointer) { 1626 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1627 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1628 // A function pointer conversion cannot change the class of the function. 1629 if (ToMPT->getClass() != FromMPT->getClass()) 1630 return false; 1631 CanTo = ToMPT->getPointeeType(); 1632 CanFrom = FromMPT->getPointeeType(); 1633 } else { 1634 return false; 1635 } 1636 1637 TyClass = CanTo->getTypeClass(); 1638 if (TyClass != CanFrom->getTypeClass()) return false; 1639 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1640 return false; 1641 } 1642 1643 const auto *FromFn = cast<FunctionType>(CanFrom); 1644 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1645 1646 const auto *ToFn = cast<FunctionType>(CanTo); 1647 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1648 1649 bool Changed = false; 1650 1651 // Drop 'noreturn' if not present in target type. 1652 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1653 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1654 Changed = true; 1655 } 1656 1657 // Drop 'noexcept' if not present in target type. 1658 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1659 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1660 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1661 FromFn = cast<FunctionType>( 1662 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1663 EST_None) 1664 .getTypePtr()); 1665 Changed = true; 1666 } 1667 1668 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1669 // only if the ExtParameterInfo lists of the two function prototypes can be 1670 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1671 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1672 bool CanUseToFPT, CanUseFromFPT; 1673 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1674 CanUseFromFPT, NewParamInfos) && 1675 CanUseToFPT && !CanUseFromFPT) { 1676 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1677 ExtInfo.ExtParameterInfos = 1678 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1679 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1680 FromFPT->getParamTypes(), ExtInfo); 1681 FromFn = QT->getAs<FunctionType>(); 1682 Changed = true; 1683 } 1684 } 1685 1686 if (!Changed) 1687 return false; 1688 1689 assert(QualType(FromFn, 0).isCanonical()); 1690 if (QualType(FromFn, 0) != CanTo) return false; 1691 1692 ResultTy = ToType; 1693 return true; 1694 } 1695 1696 /// Determine whether the conversion from FromType to ToType is a valid 1697 /// vector conversion. 1698 /// 1699 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1700 /// conversion. 1701 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, 1702 ImplicitConversionKind &ICK, Expr *From, 1703 bool InOverloadResolution) { 1704 // We need at least one of these types to be a vector type to have a vector 1705 // conversion. 1706 if (!ToType->isVectorType() && !FromType->isVectorType()) 1707 return false; 1708 1709 // Identical types require no conversions. 1710 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1711 return false; 1712 1713 // There are no conversions between extended vector types, only identity. 1714 if (ToType->isExtVectorType()) { 1715 // There are no conversions between extended vector types other than the 1716 // identity conversion. 1717 if (FromType->isExtVectorType()) 1718 return false; 1719 1720 // Vector splat from any arithmetic type to a vector. 1721 if (FromType->isArithmeticType()) { 1722 ICK = ICK_Vector_Splat; 1723 return true; 1724 } 1725 } 1726 1727 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1728 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1729 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1730 ICK = ICK_SVE_Vector_Conversion; 1731 return true; 1732 } 1733 1734 // We can perform the conversion between vector types in the following cases: 1735 // 1)vector types are equivalent AltiVec and GCC vector types 1736 // 2)lax vector conversions are permitted and the vector types are of the 1737 // same size 1738 // 3)the destination type does not have the ARM MVE strict-polymorphism 1739 // attribute, which inhibits lax vector conversion for overload resolution 1740 // only 1741 if (ToType->isVectorType() && FromType->isVectorType()) { 1742 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1743 (S.isLaxVectorConversion(FromType, ToType) && 1744 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1745 if (S.isLaxVectorConversion(FromType, ToType) && 1746 S.anyAltivecTypes(FromType, ToType) && 1747 !S.areSameVectorElemTypes(FromType, ToType) && 1748 !InOverloadResolution) { 1749 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) 1750 << FromType << ToType; 1751 } 1752 ICK = ICK_Vector_Conversion; 1753 return true; 1754 } 1755 } 1756 1757 return false; 1758 } 1759 1760 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1761 bool InOverloadResolution, 1762 StandardConversionSequence &SCS, 1763 bool CStyle); 1764 1765 /// IsStandardConversion - Determines whether there is a standard 1766 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1767 /// expression From to the type ToType. Standard conversion sequences 1768 /// only consider non-class types; for conversions that involve class 1769 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1770 /// contain the standard conversion sequence required to perform this 1771 /// conversion and this routine will return true. Otherwise, this 1772 /// routine will return false and the value of SCS is unspecified. 1773 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1774 bool InOverloadResolution, 1775 StandardConversionSequence &SCS, 1776 bool CStyle, 1777 bool AllowObjCWritebackConversion) { 1778 QualType FromType = From->getType(); 1779 1780 // Standard conversions (C++ [conv]) 1781 SCS.setAsIdentityConversion(); 1782 SCS.IncompatibleObjC = false; 1783 SCS.setFromType(FromType); 1784 SCS.CopyConstructor = nullptr; 1785 1786 // There are no standard conversions for class types in C++, so 1787 // abort early. When overloading in C, however, we do permit them. 1788 if (S.getLangOpts().CPlusPlus && 1789 (FromType->isRecordType() || ToType->isRecordType())) 1790 return false; 1791 1792 // The first conversion can be an lvalue-to-rvalue conversion, 1793 // array-to-pointer conversion, or function-to-pointer conversion 1794 // (C++ 4p1). 1795 1796 if (FromType == S.Context.OverloadTy) { 1797 DeclAccessPair AccessPair; 1798 if (FunctionDecl *Fn 1799 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1800 AccessPair)) { 1801 // We were able to resolve the address of the overloaded function, 1802 // so we can convert to the type of that function. 1803 FromType = Fn->getType(); 1804 SCS.setFromType(FromType); 1805 1806 // we can sometimes resolve &foo<int> regardless of ToType, so check 1807 // if the type matches (identity) or we are converting to bool 1808 if (!S.Context.hasSameUnqualifiedType( 1809 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1810 QualType resultTy; 1811 // if the function type matches except for [[noreturn]], it's ok 1812 if (!S.IsFunctionConversion(FromType, 1813 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1814 // otherwise, only a boolean conversion is standard 1815 if (!ToType->isBooleanType()) 1816 return false; 1817 } 1818 1819 // Check if the "from" expression is taking the address of an overloaded 1820 // function and recompute the FromType accordingly. Take advantage of the 1821 // fact that non-static member functions *must* have such an address-of 1822 // expression. 1823 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1824 if (Method && !Method->isStatic()) { 1825 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1826 "Non-unary operator on non-static member address"); 1827 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1828 == UO_AddrOf && 1829 "Non-address-of operator on non-static member address"); 1830 const Type *ClassType 1831 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1832 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1833 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1834 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1835 UO_AddrOf && 1836 "Non-address-of operator for overloaded function expression"); 1837 FromType = S.Context.getPointerType(FromType); 1838 } 1839 } else { 1840 return false; 1841 } 1842 } 1843 // Lvalue-to-rvalue conversion (C++11 4.1): 1844 // A glvalue (3.10) of a non-function, non-array type T can 1845 // be converted to a prvalue. 1846 bool argIsLValue = From->isGLValue(); 1847 if (argIsLValue && 1848 !FromType->isFunctionType() && !FromType->isArrayType() && 1849 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1850 SCS.First = ICK_Lvalue_To_Rvalue; 1851 1852 // C11 6.3.2.1p2: 1853 // ... if the lvalue has atomic type, the value has the non-atomic version 1854 // of the type of the lvalue ... 1855 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1856 FromType = Atomic->getValueType(); 1857 1858 // If T is a non-class type, the type of the rvalue is the 1859 // cv-unqualified version of T. Otherwise, the type of the rvalue 1860 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1861 // just strip the qualifiers because they don't matter. 1862 FromType = FromType.getUnqualifiedType(); 1863 } else if (FromType->isArrayType()) { 1864 // Array-to-pointer conversion (C++ 4.2) 1865 SCS.First = ICK_Array_To_Pointer; 1866 1867 // An lvalue or rvalue of type "array of N T" or "array of unknown 1868 // bound of T" can be converted to an rvalue of type "pointer to 1869 // T" (C++ 4.2p1). 1870 FromType = S.Context.getArrayDecayedType(FromType); 1871 1872 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1873 // This conversion is deprecated in C++03 (D.4) 1874 SCS.DeprecatedStringLiteralToCharPtr = true; 1875 1876 // For the purpose of ranking in overload resolution 1877 // (13.3.3.1.1), this conversion is considered an 1878 // array-to-pointer conversion followed by a qualification 1879 // conversion (4.4). (C++ 4.2p2) 1880 SCS.Second = ICK_Identity; 1881 SCS.Third = ICK_Qualification; 1882 SCS.QualificationIncludesObjCLifetime = false; 1883 SCS.setAllToTypes(FromType); 1884 return true; 1885 } 1886 } else if (FromType->isFunctionType() && argIsLValue) { 1887 // Function-to-pointer conversion (C++ 4.3). 1888 SCS.First = ICK_Function_To_Pointer; 1889 1890 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1891 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1892 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1893 return false; 1894 1895 // An lvalue of function type T can be converted to an rvalue of 1896 // type "pointer to T." The result is a pointer to the 1897 // function. (C++ 4.3p1). 1898 FromType = S.Context.getPointerType(FromType); 1899 } else { 1900 // We don't require any conversions for the first step. 1901 SCS.First = ICK_Identity; 1902 } 1903 SCS.setToType(0, FromType); 1904 1905 // The second conversion can be an integral promotion, floating 1906 // point promotion, integral conversion, floating point conversion, 1907 // floating-integral conversion, pointer conversion, 1908 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1909 // For overloading in C, this can also be a "compatible-type" 1910 // conversion. 1911 bool IncompatibleObjC = false; 1912 ImplicitConversionKind SecondICK = ICK_Identity; 1913 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1914 // The unqualified versions of the types are the same: there's no 1915 // conversion to do. 1916 SCS.Second = ICK_Identity; 1917 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1918 // Integral promotion (C++ 4.5). 1919 SCS.Second = ICK_Integral_Promotion; 1920 FromType = ToType.getUnqualifiedType(); 1921 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1922 // Floating point promotion (C++ 4.6). 1923 SCS.Second = ICK_Floating_Promotion; 1924 FromType = ToType.getUnqualifiedType(); 1925 } else if (S.IsComplexPromotion(FromType, ToType)) { 1926 // Complex promotion (Clang extension) 1927 SCS.Second = ICK_Complex_Promotion; 1928 FromType = ToType.getUnqualifiedType(); 1929 } else if (ToType->isBooleanType() && 1930 (FromType->isArithmeticType() || 1931 FromType->isAnyPointerType() || 1932 FromType->isBlockPointerType() || 1933 FromType->isMemberPointerType())) { 1934 // Boolean conversions (C++ 4.12). 1935 SCS.Second = ICK_Boolean_Conversion; 1936 FromType = S.Context.BoolTy; 1937 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1938 ToType->isIntegralType(S.Context)) { 1939 // Integral conversions (C++ 4.7). 1940 SCS.Second = ICK_Integral_Conversion; 1941 FromType = ToType.getUnqualifiedType(); 1942 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1943 // Complex conversions (C99 6.3.1.6) 1944 SCS.Second = ICK_Complex_Conversion; 1945 FromType = ToType.getUnqualifiedType(); 1946 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1947 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1948 // Complex-real conversions (C99 6.3.1.7) 1949 SCS.Second = ICK_Complex_Real; 1950 FromType = ToType.getUnqualifiedType(); 1951 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1952 // FIXME: disable conversions between long double, __ibm128 and __float128 1953 // if their representation is different until there is back end support 1954 // We of course allow this conversion if long double is really double. 1955 1956 // Conversions between bfloat and other floats are not permitted. 1957 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1958 return false; 1959 1960 // Conversions between IEEE-quad and IBM-extended semantics are not 1961 // permitted. 1962 const llvm::fltSemantics &FromSem = 1963 S.Context.getFloatTypeSemantics(FromType); 1964 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 1965 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 1966 &ToSem == &llvm::APFloat::IEEEquad()) || 1967 (&FromSem == &llvm::APFloat::IEEEquad() && 1968 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 1969 return false; 1970 1971 // Floating point conversions (C++ 4.8). 1972 SCS.Second = ICK_Floating_Conversion; 1973 FromType = ToType.getUnqualifiedType(); 1974 } else if ((FromType->isRealFloatingType() && 1975 ToType->isIntegralType(S.Context)) || 1976 (FromType->isIntegralOrUnscopedEnumerationType() && 1977 ToType->isRealFloatingType())) { 1978 // Conversions between bfloat and int are not permitted. 1979 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1980 return false; 1981 1982 // Floating-integral conversions (C++ 4.9). 1983 SCS.Second = ICK_Floating_Integral; 1984 FromType = ToType.getUnqualifiedType(); 1985 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1986 SCS.Second = ICK_Block_Pointer_Conversion; 1987 } else if (AllowObjCWritebackConversion && 1988 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1989 SCS.Second = ICK_Writeback_Conversion; 1990 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1991 FromType, IncompatibleObjC)) { 1992 // Pointer conversions (C++ 4.10). 1993 SCS.Second = ICK_Pointer_Conversion; 1994 SCS.IncompatibleObjC = IncompatibleObjC; 1995 FromType = FromType.getUnqualifiedType(); 1996 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1997 InOverloadResolution, FromType)) { 1998 // Pointer to member conversions (4.11). 1999 SCS.Second = ICK_Pointer_Member; 2000 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, 2001 InOverloadResolution)) { 2002 SCS.Second = SecondICK; 2003 FromType = ToType.getUnqualifiedType(); 2004 } else if (!S.getLangOpts().CPlusPlus && 2005 S.Context.typesAreCompatible(ToType, FromType)) { 2006 // Compatible conversions (Clang extension for C function overloading) 2007 SCS.Second = ICK_Compatible_Conversion; 2008 FromType = ToType.getUnqualifiedType(); 2009 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 2010 InOverloadResolution, 2011 SCS, CStyle)) { 2012 SCS.Second = ICK_TransparentUnionConversion; 2013 FromType = ToType; 2014 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 2015 CStyle)) { 2016 // tryAtomicConversion has updated the standard conversion sequence 2017 // appropriately. 2018 return true; 2019 } else if (ToType->isEventT() && 2020 From->isIntegerConstantExpr(S.getASTContext()) && 2021 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 2022 SCS.Second = ICK_Zero_Event_Conversion; 2023 FromType = ToType; 2024 } else if (ToType->isQueueT() && 2025 From->isIntegerConstantExpr(S.getASTContext()) && 2026 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 2027 SCS.Second = ICK_Zero_Queue_Conversion; 2028 FromType = ToType; 2029 } else if (ToType->isSamplerT() && 2030 From->isIntegerConstantExpr(S.getASTContext())) { 2031 SCS.Second = ICK_Compatible_Conversion; 2032 FromType = ToType; 2033 } else { 2034 // No second conversion required. 2035 SCS.Second = ICK_Identity; 2036 } 2037 SCS.setToType(1, FromType); 2038 2039 // The third conversion can be a function pointer conversion or a 2040 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 2041 bool ObjCLifetimeConversion; 2042 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 2043 // Function pointer conversions (removing 'noexcept') including removal of 2044 // 'noreturn' (Clang extension). 2045 SCS.Third = ICK_Function_Conversion; 2046 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 2047 ObjCLifetimeConversion)) { 2048 SCS.Third = ICK_Qualification; 2049 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 2050 FromType = ToType; 2051 } else { 2052 // No conversion required 2053 SCS.Third = ICK_Identity; 2054 } 2055 2056 // C++ [over.best.ics]p6: 2057 // [...] Any difference in top-level cv-qualification is 2058 // subsumed by the initialization itself and does not constitute 2059 // a conversion. [...] 2060 QualType CanonFrom = S.Context.getCanonicalType(FromType); 2061 QualType CanonTo = S.Context.getCanonicalType(ToType); 2062 if (CanonFrom.getLocalUnqualifiedType() 2063 == CanonTo.getLocalUnqualifiedType() && 2064 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 2065 FromType = ToType; 2066 CanonFrom = CanonTo; 2067 } 2068 2069 SCS.setToType(2, FromType); 2070 2071 if (CanonFrom == CanonTo) 2072 return true; 2073 2074 // If we have not converted the argument type to the parameter type, 2075 // this is a bad conversion sequence, unless we're resolving an overload in C. 2076 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 2077 return false; 2078 2079 ExprResult ER = ExprResult{From}; 2080 Sema::AssignConvertType Conv = 2081 S.CheckSingleAssignmentConstraints(ToType, ER, 2082 /*Diagnose=*/false, 2083 /*DiagnoseCFAudited=*/false, 2084 /*ConvertRHS=*/false); 2085 ImplicitConversionKind SecondConv; 2086 switch (Conv) { 2087 case Sema::Compatible: 2088 SecondConv = ICK_C_Only_Conversion; 2089 break; 2090 // For our purposes, discarding qualifiers is just as bad as using an 2091 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2092 // qualifiers, as well. 2093 case Sema::CompatiblePointerDiscardsQualifiers: 2094 case Sema::IncompatiblePointer: 2095 case Sema::IncompatiblePointerSign: 2096 SecondConv = ICK_Incompatible_Pointer_Conversion; 2097 break; 2098 default: 2099 return false; 2100 } 2101 2102 // First can only be an lvalue conversion, so we pretend that this was the 2103 // second conversion. First should already be valid from earlier in the 2104 // function. 2105 SCS.Second = SecondConv; 2106 SCS.setToType(1, ToType); 2107 2108 // Third is Identity, because Second should rank us worse than any other 2109 // conversion. This could also be ICK_Qualification, but it's simpler to just 2110 // lump everything in with the second conversion, and we don't gain anything 2111 // from making this ICK_Qualification. 2112 SCS.Third = ICK_Identity; 2113 SCS.setToType(2, ToType); 2114 return true; 2115 } 2116 2117 static bool 2118 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2119 QualType &ToType, 2120 bool InOverloadResolution, 2121 StandardConversionSequence &SCS, 2122 bool CStyle) { 2123 2124 const RecordType *UT = ToType->getAsUnionType(); 2125 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2126 return false; 2127 // The field to initialize within the transparent union. 2128 RecordDecl *UD = UT->getDecl(); 2129 // It's compatible if the expression matches any of the fields. 2130 for (const auto *it : UD->fields()) { 2131 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2132 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2133 ToType = it->getType(); 2134 return true; 2135 } 2136 } 2137 return false; 2138 } 2139 2140 /// IsIntegralPromotion - Determines whether the conversion from the 2141 /// expression From (whose potentially-adjusted type is FromType) to 2142 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2143 /// sets PromotedType to the promoted type. 2144 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2145 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2146 // All integers are built-in. 2147 if (!To) { 2148 return false; 2149 } 2150 2151 // An rvalue of type char, signed char, unsigned char, short int, or 2152 // unsigned short int can be converted to an rvalue of type int if 2153 // int can represent all the values of the source type; otherwise, 2154 // the source rvalue can be converted to an rvalue of type unsigned 2155 // int (C++ 4.5p1). 2156 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2157 !FromType->isEnumeralType()) { 2158 if (// We can promote any signed, promotable integer type to an int 2159 (FromType->isSignedIntegerType() || 2160 // We can promote any unsigned integer type whose size is 2161 // less than int to an int. 2162 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2163 return To->getKind() == BuiltinType::Int; 2164 } 2165 2166 return To->getKind() == BuiltinType::UInt; 2167 } 2168 2169 // C++11 [conv.prom]p3: 2170 // A prvalue of an unscoped enumeration type whose underlying type is not 2171 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2172 // following types that can represent all the values of the enumeration 2173 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2174 // unsigned int, long int, unsigned long int, long long int, or unsigned 2175 // long long int. If none of the types in that list can represent all the 2176 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2177 // type can be converted to an rvalue a prvalue of the extended integer type 2178 // with lowest integer conversion rank (4.13) greater than the rank of long 2179 // long in which all the values of the enumeration can be represented. If 2180 // there are two such extended types, the signed one is chosen. 2181 // C++11 [conv.prom]p4: 2182 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2183 // can be converted to a prvalue of its underlying type. Moreover, if 2184 // integral promotion can be applied to its underlying type, a prvalue of an 2185 // unscoped enumeration type whose underlying type is fixed can also be 2186 // converted to a prvalue of the promoted underlying type. 2187 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2188 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2189 // provided for a scoped enumeration. 2190 if (FromEnumType->getDecl()->isScoped()) 2191 return false; 2192 2193 // We can perform an integral promotion to the underlying type of the enum, 2194 // even if that's not the promoted type. Note that the check for promoting 2195 // the underlying type is based on the type alone, and does not consider 2196 // the bitfield-ness of the actual source expression. 2197 if (FromEnumType->getDecl()->isFixed()) { 2198 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2199 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2200 IsIntegralPromotion(nullptr, Underlying, ToType); 2201 } 2202 2203 // We have already pre-calculated the promotion type, so this is trivial. 2204 if (ToType->isIntegerType() && 2205 isCompleteType(From->getBeginLoc(), FromType)) 2206 return Context.hasSameUnqualifiedType( 2207 ToType, FromEnumType->getDecl()->getPromotionType()); 2208 2209 // C++ [conv.prom]p5: 2210 // If the bit-field has an enumerated type, it is treated as any other 2211 // value of that type for promotion purposes. 2212 // 2213 // ... so do not fall through into the bit-field checks below in C++. 2214 if (getLangOpts().CPlusPlus) 2215 return false; 2216 } 2217 2218 // C++0x [conv.prom]p2: 2219 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2220 // to an rvalue a prvalue of the first of the following types that can 2221 // represent all the values of its underlying type: int, unsigned int, 2222 // long int, unsigned long int, long long int, or unsigned long long int. 2223 // If none of the types in that list can represent all the values of its 2224 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2225 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2226 // type. 2227 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2228 ToType->isIntegerType()) { 2229 // Determine whether the type we're converting from is signed or 2230 // unsigned. 2231 bool FromIsSigned = FromType->isSignedIntegerType(); 2232 uint64_t FromSize = Context.getTypeSize(FromType); 2233 2234 // The types we'll try to promote to, in the appropriate 2235 // order. Try each of these types. 2236 QualType PromoteTypes[6] = { 2237 Context.IntTy, Context.UnsignedIntTy, 2238 Context.LongTy, Context.UnsignedLongTy , 2239 Context.LongLongTy, Context.UnsignedLongLongTy 2240 }; 2241 for (int Idx = 0; Idx < 6; ++Idx) { 2242 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2243 if (FromSize < ToSize || 2244 (FromSize == ToSize && 2245 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2246 // We found the type that we can promote to. If this is the 2247 // type we wanted, we have a promotion. Otherwise, no 2248 // promotion. 2249 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2250 } 2251 } 2252 } 2253 2254 // An rvalue for an integral bit-field (9.6) can be converted to an 2255 // rvalue of type int if int can represent all the values of the 2256 // bit-field; otherwise, it can be converted to unsigned int if 2257 // unsigned int can represent all the values of the bit-field. If 2258 // the bit-field is larger yet, no integral promotion applies to 2259 // it. If the bit-field has an enumerated type, it is treated as any 2260 // other value of that type for promotion purposes (C++ 4.5p3). 2261 // FIXME: We should delay checking of bit-fields until we actually perform the 2262 // conversion. 2263 // 2264 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2265 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2266 // bit-fields and those whose underlying type is larger than int) for GCC 2267 // compatibility. 2268 if (From) { 2269 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2270 Optional<llvm::APSInt> BitWidth; 2271 if (FromType->isIntegralType(Context) && 2272 (BitWidth = 2273 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2274 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2275 ToSize = Context.getTypeSize(ToType); 2276 2277 // Are we promoting to an int from a bitfield that fits in an int? 2278 if (*BitWidth < ToSize || 2279 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2280 return To->getKind() == BuiltinType::Int; 2281 } 2282 2283 // Are we promoting to an unsigned int from an unsigned bitfield 2284 // that fits into an unsigned int? 2285 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2286 return To->getKind() == BuiltinType::UInt; 2287 } 2288 2289 return false; 2290 } 2291 } 2292 } 2293 2294 // An rvalue of type bool can be converted to an rvalue of type int, 2295 // with false becoming zero and true becoming one (C++ 4.5p4). 2296 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2297 return true; 2298 } 2299 2300 return false; 2301 } 2302 2303 /// IsFloatingPointPromotion - Determines whether the conversion from 2304 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2305 /// returns true and sets PromotedType to the promoted type. 2306 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2307 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2308 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2309 /// An rvalue of type float can be converted to an rvalue of type 2310 /// double. (C++ 4.6p1). 2311 if (FromBuiltin->getKind() == BuiltinType::Float && 2312 ToBuiltin->getKind() == BuiltinType::Double) 2313 return true; 2314 2315 // C99 6.3.1.5p1: 2316 // When a float is promoted to double or long double, or a 2317 // double is promoted to long double [...]. 2318 if (!getLangOpts().CPlusPlus && 2319 (FromBuiltin->getKind() == BuiltinType::Float || 2320 FromBuiltin->getKind() == BuiltinType::Double) && 2321 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2322 ToBuiltin->getKind() == BuiltinType::Float128 || 2323 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2324 return true; 2325 2326 // Half can be promoted to float. 2327 if (!getLangOpts().NativeHalfType && 2328 FromBuiltin->getKind() == BuiltinType::Half && 2329 ToBuiltin->getKind() == BuiltinType::Float) 2330 return true; 2331 } 2332 2333 return false; 2334 } 2335 2336 /// Determine if a conversion is a complex promotion. 2337 /// 2338 /// A complex promotion is defined as a complex -> complex conversion 2339 /// where the conversion between the underlying real types is a 2340 /// floating-point or integral promotion. 2341 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2342 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2343 if (!FromComplex) 2344 return false; 2345 2346 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2347 if (!ToComplex) 2348 return false; 2349 2350 return IsFloatingPointPromotion(FromComplex->getElementType(), 2351 ToComplex->getElementType()) || 2352 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2353 ToComplex->getElementType()); 2354 } 2355 2356 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2357 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2358 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2359 /// if non-empty, will be a pointer to ToType that may or may not have 2360 /// the right set of qualifiers on its pointee. 2361 /// 2362 static QualType 2363 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2364 QualType ToPointee, QualType ToType, 2365 ASTContext &Context, 2366 bool StripObjCLifetime = false) { 2367 assert((FromPtr->getTypeClass() == Type::Pointer || 2368 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2369 "Invalid similarly-qualified pointer type"); 2370 2371 /// Conversions to 'id' subsume cv-qualifier conversions. 2372 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2373 return ToType.getUnqualifiedType(); 2374 2375 QualType CanonFromPointee 2376 = Context.getCanonicalType(FromPtr->getPointeeType()); 2377 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2378 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2379 2380 if (StripObjCLifetime) 2381 Quals.removeObjCLifetime(); 2382 2383 // Exact qualifier match -> return the pointer type we're converting to. 2384 if (CanonToPointee.getLocalQualifiers() == Quals) { 2385 // ToType is exactly what we need. Return it. 2386 if (!ToType.isNull()) 2387 return ToType.getUnqualifiedType(); 2388 2389 // Build a pointer to ToPointee. It has the right qualifiers 2390 // already. 2391 if (isa<ObjCObjectPointerType>(ToType)) 2392 return Context.getObjCObjectPointerType(ToPointee); 2393 return Context.getPointerType(ToPointee); 2394 } 2395 2396 // Just build a canonical type that has the right qualifiers. 2397 QualType QualifiedCanonToPointee 2398 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2399 2400 if (isa<ObjCObjectPointerType>(ToType)) 2401 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2402 return Context.getPointerType(QualifiedCanonToPointee); 2403 } 2404 2405 static bool isNullPointerConstantForConversion(Expr *Expr, 2406 bool InOverloadResolution, 2407 ASTContext &Context) { 2408 // Handle value-dependent integral null pointer constants correctly. 2409 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2410 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2411 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2412 return !InOverloadResolution; 2413 2414 return Expr->isNullPointerConstant(Context, 2415 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2416 : Expr::NPC_ValueDependentIsNull); 2417 } 2418 2419 /// IsPointerConversion - Determines whether the conversion of the 2420 /// expression From, which has the (possibly adjusted) type FromType, 2421 /// can be converted to the type ToType via a pointer conversion (C++ 2422 /// 4.10). If so, returns true and places the converted type (that 2423 /// might differ from ToType in its cv-qualifiers at some level) into 2424 /// ConvertedType. 2425 /// 2426 /// This routine also supports conversions to and from block pointers 2427 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2428 /// pointers to interfaces. FIXME: Once we've determined the 2429 /// appropriate overloading rules for Objective-C, we may want to 2430 /// split the Objective-C checks into a different routine; however, 2431 /// GCC seems to consider all of these conversions to be pointer 2432 /// conversions, so for now they live here. IncompatibleObjC will be 2433 /// set if the conversion is an allowed Objective-C conversion that 2434 /// should result in a warning. 2435 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2436 bool InOverloadResolution, 2437 QualType& ConvertedType, 2438 bool &IncompatibleObjC) { 2439 IncompatibleObjC = false; 2440 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2441 IncompatibleObjC)) 2442 return true; 2443 2444 // Conversion from a null pointer constant to any Objective-C pointer type. 2445 if (ToType->isObjCObjectPointerType() && 2446 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2447 ConvertedType = ToType; 2448 return true; 2449 } 2450 2451 // Blocks: Block pointers can be converted to void*. 2452 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2453 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2454 ConvertedType = ToType; 2455 return true; 2456 } 2457 // Blocks: A null pointer constant can be converted to a block 2458 // pointer type. 2459 if (ToType->isBlockPointerType() && 2460 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2461 ConvertedType = ToType; 2462 return true; 2463 } 2464 2465 // If the left-hand-side is nullptr_t, the right side can be a null 2466 // pointer constant. 2467 if (ToType->isNullPtrType() && 2468 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2469 ConvertedType = ToType; 2470 return true; 2471 } 2472 2473 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2474 if (!ToTypePtr) 2475 return false; 2476 2477 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2478 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2479 ConvertedType = ToType; 2480 return true; 2481 } 2482 2483 // Beyond this point, both types need to be pointers 2484 // , including objective-c pointers. 2485 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2486 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2487 !getLangOpts().ObjCAutoRefCount) { 2488 ConvertedType = BuildSimilarlyQualifiedPointerType( 2489 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2490 Context); 2491 return true; 2492 } 2493 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2494 if (!FromTypePtr) 2495 return false; 2496 2497 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2498 2499 // If the unqualified pointee types are the same, this can't be a 2500 // pointer conversion, so don't do all of the work below. 2501 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2502 return false; 2503 2504 // An rvalue of type "pointer to cv T," where T is an object type, 2505 // can be converted to an rvalue of type "pointer to cv void" (C++ 2506 // 4.10p2). 2507 if (FromPointeeType->isIncompleteOrObjectType() && 2508 ToPointeeType->isVoidType()) { 2509 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2510 ToPointeeType, 2511 ToType, Context, 2512 /*StripObjCLifetime=*/true); 2513 return true; 2514 } 2515 2516 // MSVC allows implicit function to void* type conversion. 2517 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2518 ToPointeeType->isVoidType()) { 2519 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2520 ToPointeeType, 2521 ToType, Context); 2522 return true; 2523 } 2524 2525 // When we're overloading in C, we allow a special kind of pointer 2526 // conversion for compatible-but-not-identical pointee types. 2527 if (!getLangOpts().CPlusPlus && 2528 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2529 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2530 ToPointeeType, 2531 ToType, Context); 2532 return true; 2533 } 2534 2535 // C++ [conv.ptr]p3: 2536 // 2537 // An rvalue of type "pointer to cv D," where D is a class type, 2538 // can be converted to an rvalue of type "pointer to cv B," where 2539 // B is a base class (clause 10) of D. If B is an inaccessible 2540 // (clause 11) or ambiguous (10.2) base class of D, a program that 2541 // necessitates this conversion is ill-formed. The result of the 2542 // conversion is a pointer to the base class sub-object of the 2543 // derived class object. The null pointer value is converted to 2544 // the null pointer value of the destination type. 2545 // 2546 // Note that we do not check for ambiguity or inaccessibility 2547 // here. That is handled by CheckPointerConversion. 2548 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2549 ToPointeeType->isRecordType() && 2550 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2551 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2552 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2553 ToPointeeType, 2554 ToType, Context); 2555 return true; 2556 } 2557 2558 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2559 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2560 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2561 ToPointeeType, 2562 ToType, Context); 2563 return true; 2564 } 2565 2566 return false; 2567 } 2568 2569 /// Adopt the given qualifiers for the given type. 2570 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2571 Qualifiers TQs = T.getQualifiers(); 2572 2573 // Check whether qualifiers already match. 2574 if (TQs == Qs) 2575 return T; 2576 2577 if (Qs.compatiblyIncludes(TQs)) 2578 return Context.getQualifiedType(T, Qs); 2579 2580 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2581 } 2582 2583 /// isObjCPointerConversion - Determines whether this is an 2584 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2585 /// with the same arguments and return values. 2586 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2587 QualType& ConvertedType, 2588 bool &IncompatibleObjC) { 2589 if (!getLangOpts().ObjC) 2590 return false; 2591 2592 // The set of qualifiers on the type we're converting from. 2593 Qualifiers FromQualifiers = FromType.getQualifiers(); 2594 2595 // First, we handle all conversions on ObjC object pointer types. 2596 const ObjCObjectPointerType* ToObjCPtr = 2597 ToType->getAs<ObjCObjectPointerType>(); 2598 const ObjCObjectPointerType *FromObjCPtr = 2599 FromType->getAs<ObjCObjectPointerType>(); 2600 2601 if (ToObjCPtr && FromObjCPtr) { 2602 // If the pointee types are the same (ignoring qualifications), 2603 // then this is not a pointer conversion. 2604 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2605 FromObjCPtr->getPointeeType())) 2606 return false; 2607 2608 // Conversion between Objective-C pointers. 2609 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2610 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2611 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2612 if (getLangOpts().CPlusPlus && LHS && RHS && 2613 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2614 FromObjCPtr->getPointeeType())) 2615 return false; 2616 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2617 ToObjCPtr->getPointeeType(), 2618 ToType, Context); 2619 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2620 return true; 2621 } 2622 2623 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2624 // Okay: this is some kind of implicit downcast of Objective-C 2625 // interfaces, which is permitted. However, we're going to 2626 // complain about it. 2627 IncompatibleObjC = true; 2628 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2629 ToObjCPtr->getPointeeType(), 2630 ToType, Context); 2631 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2632 return true; 2633 } 2634 } 2635 // Beyond this point, both types need to be C pointers or block pointers. 2636 QualType ToPointeeType; 2637 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2638 ToPointeeType = ToCPtr->getPointeeType(); 2639 else if (const BlockPointerType *ToBlockPtr = 2640 ToType->getAs<BlockPointerType>()) { 2641 // Objective C++: We're able to convert from a pointer to any object 2642 // to a block pointer type. 2643 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2644 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2645 return true; 2646 } 2647 ToPointeeType = ToBlockPtr->getPointeeType(); 2648 } 2649 else if (FromType->getAs<BlockPointerType>() && 2650 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2651 // Objective C++: We're able to convert from a block pointer type to a 2652 // pointer to any object. 2653 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2654 return true; 2655 } 2656 else 2657 return false; 2658 2659 QualType FromPointeeType; 2660 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2661 FromPointeeType = FromCPtr->getPointeeType(); 2662 else if (const BlockPointerType *FromBlockPtr = 2663 FromType->getAs<BlockPointerType>()) 2664 FromPointeeType = FromBlockPtr->getPointeeType(); 2665 else 2666 return false; 2667 2668 // If we have pointers to pointers, recursively check whether this 2669 // is an Objective-C conversion. 2670 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2671 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2672 IncompatibleObjC)) { 2673 // We always complain about this conversion. 2674 IncompatibleObjC = true; 2675 ConvertedType = Context.getPointerType(ConvertedType); 2676 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2677 return true; 2678 } 2679 // Allow conversion of pointee being objective-c pointer to another one; 2680 // as in I* to id. 2681 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2682 ToPointeeType->getAs<ObjCObjectPointerType>() && 2683 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2684 IncompatibleObjC)) { 2685 2686 ConvertedType = Context.getPointerType(ConvertedType); 2687 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2688 return true; 2689 } 2690 2691 // If we have pointers to functions or blocks, check whether the only 2692 // differences in the argument and result types are in Objective-C 2693 // pointer conversions. If so, we permit the conversion (but 2694 // complain about it). 2695 const FunctionProtoType *FromFunctionType 2696 = FromPointeeType->getAs<FunctionProtoType>(); 2697 const FunctionProtoType *ToFunctionType 2698 = ToPointeeType->getAs<FunctionProtoType>(); 2699 if (FromFunctionType && ToFunctionType) { 2700 // If the function types are exactly the same, this isn't an 2701 // Objective-C pointer conversion. 2702 if (Context.getCanonicalType(FromPointeeType) 2703 == Context.getCanonicalType(ToPointeeType)) 2704 return false; 2705 2706 // Perform the quick checks that will tell us whether these 2707 // function types are obviously different. 2708 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2709 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2710 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2711 return false; 2712 2713 bool HasObjCConversion = false; 2714 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2715 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2716 // Okay, the types match exactly. Nothing to do. 2717 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2718 ToFunctionType->getReturnType(), 2719 ConvertedType, IncompatibleObjC)) { 2720 // Okay, we have an Objective-C pointer conversion. 2721 HasObjCConversion = true; 2722 } else { 2723 // Function types are too different. Abort. 2724 return false; 2725 } 2726 2727 // Check argument types. 2728 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2729 ArgIdx != NumArgs; ++ArgIdx) { 2730 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2731 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2732 if (Context.getCanonicalType(FromArgType) 2733 == Context.getCanonicalType(ToArgType)) { 2734 // Okay, the types match exactly. Nothing to do. 2735 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2736 ConvertedType, IncompatibleObjC)) { 2737 // Okay, we have an Objective-C pointer conversion. 2738 HasObjCConversion = true; 2739 } else { 2740 // Argument types are too different. Abort. 2741 return false; 2742 } 2743 } 2744 2745 if (HasObjCConversion) { 2746 // We had an Objective-C conversion. Allow this pointer 2747 // conversion, but complain about it. 2748 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2749 IncompatibleObjC = true; 2750 return true; 2751 } 2752 } 2753 2754 return false; 2755 } 2756 2757 /// Determine whether this is an Objective-C writeback conversion, 2758 /// used for parameter passing when performing automatic reference counting. 2759 /// 2760 /// \param FromType The type we're converting form. 2761 /// 2762 /// \param ToType The type we're converting to. 2763 /// 2764 /// \param ConvertedType The type that will be produced after applying 2765 /// this conversion. 2766 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2767 QualType &ConvertedType) { 2768 if (!getLangOpts().ObjCAutoRefCount || 2769 Context.hasSameUnqualifiedType(FromType, ToType)) 2770 return false; 2771 2772 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2773 QualType ToPointee; 2774 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2775 ToPointee = ToPointer->getPointeeType(); 2776 else 2777 return false; 2778 2779 Qualifiers ToQuals = ToPointee.getQualifiers(); 2780 if (!ToPointee->isObjCLifetimeType() || 2781 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2782 !ToQuals.withoutObjCLifetime().empty()) 2783 return false; 2784 2785 // Argument must be a pointer to __strong to __weak. 2786 QualType FromPointee; 2787 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2788 FromPointee = FromPointer->getPointeeType(); 2789 else 2790 return false; 2791 2792 Qualifiers FromQuals = FromPointee.getQualifiers(); 2793 if (!FromPointee->isObjCLifetimeType() || 2794 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2795 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2796 return false; 2797 2798 // Make sure that we have compatible qualifiers. 2799 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2800 if (!ToQuals.compatiblyIncludes(FromQuals)) 2801 return false; 2802 2803 // Remove qualifiers from the pointee type we're converting from; they 2804 // aren't used in the compatibility check belong, and we'll be adding back 2805 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2806 FromPointee = FromPointee.getUnqualifiedType(); 2807 2808 // The unqualified form of the pointee types must be compatible. 2809 ToPointee = ToPointee.getUnqualifiedType(); 2810 bool IncompatibleObjC; 2811 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2812 FromPointee = ToPointee; 2813 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2814 IncompatibleObjC)) 2815 return false; 2816 2817 /// Construct the type we're converting to, which is a pointer to 2818 /// __autoreleasing pointee. 2819 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2820 ConvertedType = Context.getPointerType(FromPointee); 2821 return true; 2822 } 2823 2824 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2825 QualType& ConvertedType) { 2826 QualType ToPointeeType; 2827 if (const BlockPointerType *ToBlockPtr = 2828 ToType->getAs<BlockPointerType>()) 2829 ToPointeeType = ToBlockPtr->getPointeeType(); 2830 else 2831 return false; 2832 2833 QualType FromPointeeType; 2834 if (const BlockPointerType *FromBlockPtr = 2835 FromType->getAs<BlockPointerType>()) 2836 FromPointeeType = FromBlockPtr->getPointeeType(); 2837 else 2838 return false; 2839 // We have pointer to blocks, check whether the only 2840 // differences in the argument and result types are in Objective-C 2841 // pointer conversions. If so, we permit the conversion. 2842 2843 const FunctionProtoType *FromFunctionType 2844 = FromPointeeType->getAs<FunctionProtoType>(); 2845 const FunctionProtoType *ToFunctionType 2846 = ToPointeeType->getAs<FunctionProtoType>(); 2847 2848 if (!FromFunctionType || !ToFunctionType) 2849 return false; 2850 2851 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2852 return true; 2853 2854 // Perform the quick checks that will tell us whether these 2855 // function types are obviously different. 2856 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2857 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2858 return false; 2859 2860 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2861 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2862 if (FromEInfo != ToEInfo) 2863 return false; 2864 2865 bool IncompatibleObjC = false; 2866 if (Context.hasSameType(FromFunctionType->getReturnType(), 2867 ToFunctionType->getReturnType())) { 2868 // Okay, the types match exactly. Nothing to do. 2869 } else { 2870 QualType RHS = FromFunctionType->getReturnType(); 2871 QualType LHS = ToFunctionType->getReturnType(); 2872 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2873 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2874 LHS = LHS.getUnqualifiedType(); 2875 2876 if (Context.hasSameType(RHS,LHS)) { 2877 // OK exact match. 2878 } else if (isObjCPointerConversion(RHS, LHS, 2879 ConvertedType, IncompatibleObjC)) { 2880 if (IncompatibleObjC) 2881 return false; 2882 // Okay, we have an Objective-C pointer conversion. 2883 } 2884 else 2885 return false; 2886 } 2887 2888 // Check argument types. 2889 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2890 ArgIdx != NumArgs; ++ArgIdx) { 2891 IncompatibleObjC = false; 2892 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2893 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2894 if (Context.hasSameType(FromArgType, ToArgType)) { 2895 // Okay, the types match exactly. Nothing to do. 2896 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2897 ConvertedType, IncompatibleObjC)) { 2898 if (IncompatibleObjC) 2899 return false; 2900 // Okay, we have an Objective-C pointer conversion. 2901 } else 2902 // Argument types are too different. Abort. 2903 return false; 2904 } 2905 2906 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2907 bool CanUseToFPT, CanUseFromFPT; 2908 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2909 CanUseToFPT, CanUseFromFPT, 2910 NewParamInfos)) 2911 return false; 2912 2913 ConvertedType = ToType; 2914 return true; 2915 } 2916 2917 enum { 2918 ft_default, 2919 ft_different_class, 2920 ft_parameter_arity, 2921 ft_parameter_mismatch, 2922 ft_return_type, 2923 ft_qualifer_mismatch, 2924 ft_noexcept 2925 }; 2926 2927 /// Attempts to get the FunctionProtoType from a Type. Handles 2928 /// MemberFunctionPointers properly. 2929 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2930 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2931 return FPT; 2932 2933 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2934 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2935 2936 return nullptr; 2937 } 2938 2939 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2940 /// function types. Catches different number of parameter, mismatch in 2941 /// parameter types, and different return types. 2942 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2943 QualType FromType, QualType ToType) { 2944 // If either type is not valid, include no extra info. 2945 if (FromType.isNull() || ToType.isNull()) { 2946 PDiag << ft_default; 2947 return; 2948 } 2949 2950 // Get the function type from the pointers. 2951 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2952 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2953 *ToMember = ToType->castAs<MemberPointerType>(); 2954 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2955 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2956 << QualType(FromMember->getClass(), 0); 2957 return; 2958 } 2959 FromType = FromMember->getPointeeType(); 2960 ToType = ToMember->getPointeeType(); 2961 } 2962 2963 if (FromType->isPointerType()) 2964 FromType = FromType->getPointeeType(); 2965 if (ToType->isPointerType()) 2966 ToType = ToType->getPointeeType(); 2967 2968 // Remove references. 2969 FromType = FromType.getNonReferenceType(); 2970 ToType = ToType.getNonReferenceType(); 2971 2972 // Don't print extra info for non-specialized template functions. 2973 if (FromType->isInstantiationDependentType() && 2974 !FromType->getAs<TemplateSpecializationType>()) { 2975 PDiag << ft_default; 2976 return; 2977 } 2978 2979 // No extra info for same types. 2980 if (Context.hasSameType(FromType, ToType)) { 2981 PDiag << ft_default; 2982 return; 2983 } 2984 2985 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2986 *ToFunction = tryGetFunctionProtoType(ToType); 2987 2988 // Both types need to be function types. 2989 if (!FromFunction || !ToFunction) { 2990 PDiag << ft_default; 2991 return; 2992 } 2993 2994 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2995 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2996 << FromFunction->getNumParams(); 2997 return; 2998 } 2999 3000 // Handle different parameter types. 3001 unsigned ArgPos; 3002 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 3003 PDiag << ft_parameter_mismatch << ArgPos + 1 3004 << ToFunction->getParamType(ArgPos) 3005 << FromFunction->getParamType(ArgPos); 3006 return; 3007 } 3008 3009 // Handle different return type. 3010 if (!Context.hasSameType(FromFunction->getReturnType(), 3011 ToFunction->getReturnType())) { 3012 PDiag << ft_return_type << ToFunction->getReturnType() 3013 << FromFunction->getReturnType(); 3014 return; 3015 } 3016 3017 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 3018 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 3019 << FromFunction->getMethodQuals(); 3020 return; 3021 } 3022 3023 // Handle exception specification differences on canonical type (in C++17 3024 // onwards). 3025 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 3026 ->isNothrow() != 3027 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 3028 ->isNothrow()) { 3029 PDiag << ft_noexcept; 3030 return; 3031 } 3032 3033 // Unable to find a difference, so add no extra info. 3034 PDiag << ft_default; 3035 } 3036 3037 /// FunctionParamTypesAreEqual - This routine checks two function proto types 3038 /// for equality of their parameter types. Caller has already checked that 3039 /// they have same number of parameters. If the parameters are different, 3040 /// ArgPos will have the parameter index of the first different parameter. 3041 /// If `Reversed` is true, the parameters of `NewType` will be compared in 3042 /// reverse order. That's useful if one of the functions is being used as a C++20 3043 /// synthesized operator overload with a reversed parameter order. 3044 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3045 const FunctionProtoType *NewType, 3046 unsigned *ArgPos, bool Reversed) { 3047 assert(OldType->getNumParams() == NewType->getNumParams() && 3048 "Can't compare parameters of functions with different number of " 3049 "parameters!"); 3050 for (size_t I = 0; I < OldType->getNumParams(); I++) { 3051 // Reverse iterate over the parameters of `OldType` if `Reversed` is true. 3052 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I; 3053 3054 // Ignore address spaces in pointee type. This is to disallow overloading 3055 // on __ptr32/__ptr64 address spaces. 3056 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType()); 3057 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType()); 3058 3059 if (!Context.hasSameType(Old, New)) { 3060 if (ArgPos) 3061 *ArgPos = I; 3062 return false; 3063 } 3064 } 3065 return true; 3066 } 3067 3068 /// CheckPointerConversion - Check the pointer conversion from the 3069 /// expression From to the type ToType. This routine checks for 3070 /// ambiguous or inaccessible derived-to-base pointer 3071 /// conversions for which IsPointerConversion has already returned 3072 /// true. It returns true and produces a diagnostic if there was an 3073 /// error, or returns false otherwise. 3074 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 3075 CastKind &Kind, 3076 CXXCastPath& BasePath, 3077 bool IgnoreBaseAccess, 3078 bool Diagnose) { 3079 QualType FromType = From->getType(); 3080 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3081 3082 Kind = CK_BitCast; 3083 3084 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3085 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3086 Expr::NPCK_ZeroExpression) { 3087 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3088 DiagRuntimeBehavior(From->getExprLoc(), From, 3089 PDiag(diag::warn_impcast_bool_to_null_pointer) 3090 << ToType << From->getSourceRange()); 3091 else if (!isUnevaluatedContext()) 3092 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3093 << ToType << From->getSourceRange(); 3094 } 3095 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3096 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3097 QualType FromPointeeType = FromPtrType->getPointeeType(), 3098 ToPointeeType = ToPtrType->getPointeeType(); 3099 3100 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3101 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3102 // We must have a derived-to-base conversion. Check an 3103 // ambiguous or inaccessible conversion. 3104 unsigned InaccessibleID = 0; 3105 unsigned AmbiguousID = 0; 3106 if (Diagnose) { 3107 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3108 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3109 } 3110 if (CheckDerivedToBaseConversion( 3111 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3112 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3113 &BasePath, IgnoreBaseAccess)) 3114 return true; 3115 3116 // The conversion was successful. 3117 Kind = CK_DerivedToBase; 3118 } 3119 3120 if (Diagnose && !IsCStyleOrFunctionalCast && 3121 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3122 assert(getLangOpts().MSVCCompat && 3123 "this should only be possible with MSVCCompat!"); 3124 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3125 << From->getSourceRange(); 3126 } 3127 } 3128 } else if (const ObjCObjectPointerType *ToPtrType = 3129 ToType->getAs<ObjCObjectPointerType>()) { 3130 if (const ObjCObjectPointerType *FromPtrType = 3131 FromType->getAs<ObjCObjectPointerType>()) { 3132 // Objective-C++ conversions are always okay. 3133 // FIXME: We should have a different class of conversions for the 3134 // Objective-C++ implicit conversions. 3135 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3136 return false; 3137 } else if (FromType->isBlockPointerType()) { 3138 Kind = CK_BlockPointerToObjCPointerCast; 3139 } else { 3140 Kind = CK_CPointerToObjCPointerCast; 3141 } 3142 } else if (ToType->isBlockPointerType()) { 3143 if (!FromType->isBlockPointerType()) 3144 Kind = CK_AnyPointerToBlockPointerCast; 3145 } 3146 3147 // We shouldn't fall into this case unless it's valid for other 3148 // reasons. 3149 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3150 Kind = CK_NullToPointer; 3151 3152 return false; 3153 } 3154 3155 /// IsMemberPointerConversion - Determines whether the conversion of the 3156 /// expression From, which has the (possibly adjusted) type FromType, can be 3157 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3158 /// If so, returns true and places the converted type (that might differ from 3159 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3160 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3161 QualType ToType, 3162 bool InOverloadResolution, 3163 QualType &ConvertedType) { 3164 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3165 if (!ToTypePtr) 3166 return false; 3167 3168 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3169 if (From->isNullPointerConstant(Context, 3170 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3171 : Expr::NPC_ValueDependentIsNull)) { 3172 ConvertedType = ToType; 3173 return true; 3174 } 3175 3176 // Otherwise, both types have to be member pointers. 3177 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3178 if (!FromTypePtr) 3179 return false; 3180 3181 // A pointer to member of B can be converted to a pointer to member of D, 3182 // where D is derived from B (C++ 4.11p2). 3183 QualType FromClass(FromTypePtr->getClass(), 0); 3184 QualType ToClass(ToTypePtr->getClass(), 0); 3185 3186 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3187 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3188 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3189 ToClass.getTypePtr()); 3190 return true; 3191 } 3192 3193 return false; 3194 } 3195 3196 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3197 /// expression From to the type ToType. This routine checks for ambiguous or 3198 /// virtual or inaccessible base-to-derived member pointer conversions 3199 /// for which IsMemberPointerConversion has already returned true. It returns 3200 /// true and produces a diagnostic if there was an error, or returns false 3201 /// otherwise. 3202 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3203 CastKind &Kind, 3204 CXXCastPath &BasePath, 3205 bool IgnoreBaseAccess) { 3206 QualType FromType = From->getType(); 3207 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3208 if (!FromPtrType) { 3209 // This must be a null pointer to member pointer conversion 3210 assert(From->isNullPointerConstant(Context, 3211 Expr::NPC_ValueDependentIsNull) && 3212 "Expr must be null pointer constant!"); 3213 Kind = CK_NullToMemberPointer; 3214 return false; 3215 } 3216 3217 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3218 assert(ToPtrType && "No member pointer cast has a target type " 3219 "that is not a member pointer."); 3220 3221 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3222 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3223 3224 // FIXME: What about dependent types? 3225 assert(FromClass->isRecordType() && "Pointer into non-class."); 3226 assert(ToClass->isRecordType() && "Pointer into non-class."); 3227 3228 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3229 /*DetectVirtual=*/true); 3230 bool DerivationOkay = 3231 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3232 assert(DerivationOkay && 3233 "Should not have been called if derivation isn't OK."); 3234 (void)DerivationOkay; 3235 3236 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3237 getUnqualifiedType())) { 3238 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3239 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3240 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3241 return true; 3242 } 3243 3244 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3245 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3246 << FromClass << ToClass << QualType(VBase, 0) 3247 << From->getSourceRange(); 3248 return true; 3249 } 3250 3251 if (!IgnoreBaseAccess) 3252 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3253 Paths.front(), 3254 diag::err_downcast_from_inaccessible_base); 3255 3256 // Must be a base to derived member conversion. 3257 BuildBasePathArray(Paths, BasePath); 3258 Kind = CK_BaseToDerivedMemberPointer; 3259 return false; 3260 } 3261 3262 /// Determine whether the lifetime conversion between the two given 3263 /// qualifiers sets is nontrivial. 3264 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3265 Qualifiers ToQuals) { 3266 // Converting anything to const __unsafe_unretained is trivial. 3267 if (ToQuals.hasConst() && 3268 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3269 return false; 3270 3271 return true; 3272 } 3273 3274 /// Perform a single iteration of the loop for checking if a qualification 3275 /// conversion is valid. 3276 /// 3277 /// Specifically, check whether any change between the qualifiers of \p 3278 /// FromType and \p ToType is permissible, given knowledge about whether every 3279 /// outer layer is const-qualified. 3280 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3281 bool CStyle, bool IsTopLevel, 3282 bool &PreviousToQualsIncludeConst, 3283 bool &ObjCLifetimeConversion) { 3284 Qualifiers FromQuals = FromType.getQualifiers(); 3285 Qualifiers ToQuals = ToType.getQualifiers(); 3286 3287 // Ignore __unaligned qualifier. 3288 FromQuals.removeUnaligned(); 3289 3290 // Objective-C ARC: 3291 // Check Objective-C lifetime conversions. 3292 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3293 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3294 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3295 ObjCLifetimeConversion = true; 3296 FromQuals.removeObjCLifetime(); 3297 ToQuals.removeObjCLifetime(); 3298 } else { 3299 // Qualification conversions cannot cast between different 3300 // Objective-C lifetime qualifiers. 3301 return false; 3302 } 3303 } 3304 3305 // Allow addition/removal of GC attributes but not changing GC attributes. 3306 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3307 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3308 FromQuals.removeObjCGCAttr(); 3309 ToQuals.removeObjCGCAttr(); 3310 } 3311 3312 // -- for every j > 0, if const is in cv 1,j then const is in cv 3313 // 2,j, and similarly for volatile. 3314 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3315 return false; 3316 3317 // If address spaces mismatch: 3318 // - in top level it is only valid to convert to addr space that is a 3319 // superset in all cases apart from C-style casts where we allow 3320 // conversions between overlapping address spaces. 3321 // - in non-top levels it is not a valid conversion. 3322 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3323 (!IsTopLevel || 3324 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3325 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3326 return false; 3327 3328 // -- if the cv 1,j and cv 2,j are different, then const is in 3329 // every cv for 0 < k < j. 3330 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3331 !PreviousToQualsIncludeConst) 3332 return false; 3333 3334 // The following wording is from C++20, where the result of the conversion 3335 // is T3, not T2. 3336 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3337 // "array of unknown bound of" 3338 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3339 return false; 3340 3341 // -- if the resulting P3,i is different from P1,i [...], then const is 3342 // added to every cv 3_k for 0 < k < i. 3343 if (!CStyle && FromType->isConstantArrayType() && 3344 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3345 return false; 3346 3347 // Keep track of whether all prior cv-qualifiers in the "to" type 3348 // include const. 3349 PreviousToQualsIncludeConst = 3350 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3351 return true; 3352 } 3353 3354 /// IsQualificationConversion - Determines whether the conversion from 3355 /// an rvalue of type FromType to ToType is a qualification conversion 3356 /// (C++ 4.4). 3357 /// 3358 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3359 /// when the qualification conversion involves a change in the Objective-C 3360 /// object lifetime. 3361 bool 3362 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3363 bool CStyle, bool &ObjCLifetimeConversion) { 3364 FromType = Context.getCanonicalType(FromType); 3365 ToType = Context.getCanonicalType(ToType); 3366 ObjCLifetimeConversion = false; 3367 3368 // If FromType and ToType are the same type, this is not a 3369 // qualification conversion. 3370 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3371 return false; 3372 3373 // (C++ 4.4p4): 3374 // A conversion can add cv-qualifiers at levels other than the first 3375 // in multi-level pointers, subject to the following rules: [...] 3376 bool PreviousToQualsIncludeConst = true; 3377 bool UnwrappedAnyPointer = false; 3378 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3379 if (!isQualificationConversionStep( 3380 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3381 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3382 return false; 3383 UnwrappedAnyPointer = true; 3384 } 3385 3386 // We are left with FromType and ToType being the pointee types 3387 // after unwrapping the original FromType and ToType the same number 3388 // of times. If we unwrapped any pointers, and if FromType and 3389 // ToType have the same unqualified type (since we checked 3390 // qualifiers above), then this is a qualification conversion. 3391 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3392 } 3393 3394 /// - Determine whether this is a conversion from a scalar type to an 3395 /// atomic type. 3396 /// 3397 /// If successful, updates \c SCS's second and third steps in the conversion 3398 /// sequence to finish the conversion. 3399 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3400 bool InOverloadResolution, 3401 StandardConversionSequence &SCS, 3402 bool CStyle) { 3403 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3404 if (!ToAtomic) 3405 return false; 3406 3407 StandardConversionSequence InnerSCS; 3408 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3409 InOverloadResolution, InnerSCS, 3410 CStyle, /*AllowObjCWritebackConversion=*/false)) 3411 return false; 3412 3413 SCS.Second = InnerSCS.Second; 3414 SCS.setToType(1, InnerSCS.getToType(1)); 3415 SCS.Third = InnerSCS.Third; 3416 SCS.QualificationIncludesObjCLifetime 3417 = InnerSCS.QualificationIncludesObjCLifetime; 3418 SCS.setToType(2, InnerSCS.getToType(2)); 3419 return true; 3420 } 3421 3422 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3423 CXXConstructorDecl *Constructor, 3424 QualType Type) { 3425 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3426 if (CtorType->getNumParams() > 0) { 3427 QualType FirstArg = CtorType->getParamType(0); 3428 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3429 return true; 3430 } 3431 return false; 3432 } 3433 3434 static OverloadingResult 3435 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3436 CXXRecordDecl *To, 3437 UserDefinedConversionSequence &User, 3438 OverloadCandidateSet &CandidateSet, 3439 bool AllowExplicit) { 3440 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3441 for (auto *D : S.LookupConstructors(To)) { 3442 auto Info = getConstructorInfo(D); 3443 if (!Info) 3444 continue; 3445 3446 bool Usable = !Info.Constructor->isInvalidDecl() && 3447 S.isInitListConstructor(Info.Constructor); 3448 if (Usable) { 3449 bool SuppressUserConversions = false; 3450 if (Info.ConstructorTmpl) 3451 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3452 /*ExplicitArgs*/ nullptr, From, 3453 CandidateSet, SuppressUserConversions, 3454 /*PartialOverloading*/ false, 3455 AllowExplicit); 3456 else 3457 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3458 CandidateSet, SuppressUserConversions, 3459 /*PartialOverloading*/ false, AllowExplicit); 3460 } 3461 } 3462 3463 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3464 3465 OverloadCandidateSet::iterator Best; 3466 switch (auto Result = 3467 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3468 case OR_Deleted: 3469 case OR_Success: { 3470 // Record the standard conversion we used and the conversion function. 3471 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3472 QualType ThisType = Constructor->getThisType(); 3473 // Initializer lists don't have conversions as such. 3474 User.Before.setAsIdentityConversion(); 3475 User.HadMultipleCandidates = HadMultipleCandidates; 3476 User.ConversionFunction = Constructor; 3477 User.FoundConversionFunction = Best->FoundDecl; 3478 User.After.setAsIdentityConversion(); 3479 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3480 User.After.setAllToTypes(ToType); 3481 return Result; 3482 } 3483 3484 case OR_No_Viable_Function: 3485 return OR_No_Viable_Function; 3486 case OR_Ambiguous: 3487 return OR_Ambiguous; 3488 } 3489 3490 llvm_unreachable("Invalid OverloadResult!"); 3491 } 3492 3493 /// Determines whether there is a user-defined conversion sequence 3494 /// (C++ [over.ics.user]) that converts expression From to the type 3495 /// ToType. If such a conversion exists, User will contain the 3496 /// user-defined conversion sequence that performs such a conversion 3497 /// and this routine will return true. Otherwise, this routine returns 3498 /// false and User is unspecified. 3499 /// 3500 /// \param AllowExplicit true if the conversion should consider C++0x 3501 /// "explicit" conversion functions as well as non-explicit conversion 3502 /// functions (C++0x [class.conv.fct]p2). 3503 /// 3504 /// \param AllowObjCConversionOnExplicit true if the conversion should 3505 /// allow an extra Objective-C pointer conversion on uses of explicit 3506 /// constructors. Requires \c AllowExplicit to also be set. 3507 static OverloadingResult 3508 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3509 UserDefinedConversionSequence &User, 3510 OverloadCandidateSet &CandidateSet, 3511 AllowedExplicit AllowExplicit, 3512 bool AllowObjCConversionOnExplicit) { 3513 assert(AllowExplicit != AllowedExplicit::None || 3514 !AllowObjCConversionOnExplicit); 3515 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3516 3517 // Whether we will only visit constructors. 3518 bool ConstructorsOnly = false; 3519 3520 // If the type we are conversion to is a class type, enumerate its 3521 // constructors. 3522 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3523 // C++ [over.match.ctor]p1: 3524 // When objects of class type are direct-initialized (8.5), or 3525 // copy-initialized from an expression of the same or a 3526 // derived class type (8.5), overload resolution selects the 3527 // constructor. [...] For copy-initialization, the candidate 3528 // functions are all the converting constructors (12.3.1) of 3529 // that class. The argument list is the expression-list within 3530 // the parentheses of the initializer. 3531 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3532 (From->getType()->getAs<RecordType>() && 3533 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3534 ConstructorsOnly = true; 3535 3536 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3537 // We're not going to find any constructors. 3538 } else if (CXXRecordDecl *ToRecordDecl 3539 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3540 3541 Expr **Args = &From; 3542 unsigned NumArgs = 1; 3543 bool ListInitializing = false; 3544 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3545 // But first, see if there is an init-list-constructor that will work. 3546 OverloadingResult Result = IsInitializerListConstructorConversion( 3547 S, From, ToType, ToRecordDecl, User, CandidateSet, 3548 AllowExplicit == AllowedExplicit::All); 3549 if (Result != OR_No_Viable_Function) 3550 return Result; 3551 // Never mind. 3552 CandidateSet.clear( 3553 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3554 3555 // If we're list-initializing, we pass the individual elements as 3556 // arguments, not the entire list. 3557 Args = InitList->getInits(); 3558 NumArgs = InitList->getNumInits(); 3559 ListInitializing = true; 3560 } 3561 3562 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3563 auto Info = getConstructorInfo(D); 3564 if (!Info) 3565 continue; 3566 3567 bool Usable = !Info.Constructor->isInvalidDecl(); 3568 if (!ListInitializing) 3569 Usable = Usable && Info.Constructor->isConvertingConstructor( 3570 /*AllowExplicit*/ true); 3571 if (Usable) { 3572 bool SuppressUserConversions = !ConstructorsOnly; 3573 // C++20 [over.best.ics.general]/4.5: 3574 // if the target is the first parameter of a constructor [of class 3575 // X] and the constructor [...] is a candidate by [...] the second 3576 // phase of [over.match.list] when the initializer list has exactly 3577 // one element that is itself an initializer list, [...] and the 3578 // conversion is to X or reference to cv X, user-defined conversion 3579 // sequences are not cnosidered. 3580 if (SuppressUserConversions && ListInitializing) { 3581 SuppressUserConversions = 3582 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3583 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3584 ToType); 3585 } 3586 if (Info.ConstructorTmpl) 3587 S.AddTemplateOverloadCandidate( 3588 Info.ConstructorTmpl, Info.FoundDecl, 3589 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3590 CandidateSet, SuppressUserConversions, 3591 /*PartialOverloading*/ false, 3592 AllowExplicit == AllowedExplicit::All); 3593 else 3594 // Allow one user-defined conversion when user specifies a 3595 // From->ToType conversion via an static cast (c-style, etc). 3596 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3597 llvm::makeArrayRef(Args, NumArgs), 3598 CandidateSet, SuppressUserConversions, 3599 /*PartialOverloading*/ false, 3600 AllowExplicit == AllowedExplicit::All); 3601 } 3602 } 3603 } 3604 } 3605 3606 // Enumerate conversion functions, if we're allowed to. 3607 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3608 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3609 // No conversion functions from incomplete types. 3610 } else if (const RecordType *FromRecordType = 3611 From->getType()->getAs<RecordType>()) { 3612 if (CXXRecordDecl *FromRecordDecl 3613 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3614 // Add all of the conversion functions as candidates. 3615 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3616 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3617 DeclAccessPair FoundDecl = I.getPair(); 3618 NamedDecl *D = FoundDecl.getDecl(); 3619 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3620 if (isa<UsingShadowDecl>(D)) 3621 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3622 3623 CXXConversionDecl *Conv; 3624 FunctionTemplateDecl *ConvTemplate; 3625 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3626 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3627 else 3628 Conv = cast<CXXConversionDecl>(D); 3629 3630 if (ConvTemplate) 3631 S.AddTemplateConversionCandidate( 3632 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3633 CandidateSet, AllowObjCConversionOnExplicit, 3634 AllowExplicit != AllowedExplicit::None); 3635 else 3636 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3637 CandidateSet, AllowObjCConversionOnExplicit, 3638 AllowExplicit != AllowedExplicit::None); 3639 } 3640 } 3641 } 3642 3643 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3644 3645 OverloadCandidateSet::iterator Best; 3646 switch (auto Result = 3647 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3648 case OR_Success: 3649 case OR_Deleted: 3650 // Record the standard conversion we used and the conversion function. 3651 if (CXXConstructorDecl *Constructor 3652 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3653 // C++ [over.ics.user]p1: 3654 // If the user-defined conversion is specified by a 3655 // constructor (12.3.1), the initial standard conversion 3656 // sequence converts the source type to the type required by 3657 // the argument of the constructor. 3658 // 3659 QualType ThisType = Constructor->getThisType(); 3660 if (isa<InitListExpr>(From)) { 3661 // Initializer lists don't have conversions as such. 3662 User.Before.setAsIdentityConversion(); 3663 } else { 3664 if (Best->Conversions[0].isEllipsis()) 3665 User.EllipsisConversion = true; 3666 else { 3667 User.Before = Best->Conversions[0].Standard; 3668 User.EllipsisConversion = false; 3669 } 3670 } 3671 User.HadMultipleCandidates = HadMultipleCandidates; 3672 User.ConversionFunction = Constructor; 3673 User.FoundConversionFunction = Best->FoundDecl; 3674 User.After.setAsIdentityConversion(); 3675 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3676 User.After.setAllToTypes(ToType); 3677 return Result; 3678 } 3679 if (CXXConversionDecl *Conversion 3680 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3681 // C++ [over.ics.user]p1: 3682 // 3683 // [...] If the user-defined conversion is specified by a 3684 // conversion function (12.3.2), the initial standard 3685 // conversion sequence converts the source type to the 3686 // implicit object parameter of the conversion function. 3687 User.Before = Best->Conversions[0].Standard; 3688 User.HadMultipleCandidates = HadMultipleCandidates; 3689 User.ConversionFunction = Conversion; 3690 User.FoundConversionFunction = Best->FoundDecl; 3691 User.EllipsisConversion = false; 3692 3693 // C++ [over.ics.user]p2: 3694 // The second standard conversion sequence converts the 3695 // result of the user-defined conversion to the target type 3696 // for the sequence. Since an implicit conversion sequence 3697 // is an initialization, the special rules for 3698 // initialization by user-defined conversion apply when 3699 // selecting the best user-defined conversion for a 3700 // user-defined conversion sequence (see 13.3.3 and 3701 // 13.3.3.1). 3702 User.After = Best->FinalConversion; 3703 return Result; 3704 } 3705 llvm_unreachable("Not a constructor or conversion function?"); 3706 3707 case OR_No_Viable_Function: 3708 return OR_No_Viable_Function; 3709 3710 case OR_Ambiguous: 3711 return OR_Ambiguous; 3712 } 3713 3714 llvm_unreachable("Invalid OverloadResult!"); 3715 } 3716 3717 bool 3718 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3719 ImplicitConversionSequence ICS; 3720 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3721 OverloadCandidateSet::CSK_Normal); 3722 OverloadingResult OvResult = 3723 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3724 CandidateSet, AllowedExplicit::None, false); 3725 3726 if (!(OvResult == OR_Ambiguous || 3727 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3728 return false; 3729 3730 auto Cands = CandidateSet.CompleteCandidates( 3731 *this, 3732 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3733 From); 3734 if (OvResult == OR_Ambiguous) 3735 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3736 << From->getType() << ToType << From->getSourceRange(); 3737 else { // OR_No_Viable_Function && !CandidateSet.empty() 3738 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3739 diag::err_typecheck_nonviable_condition_incomplete, 3740 From->getType(), From->getSourceRange())) 3741 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3742 << false << From->getType() << From->getSourceRange() << ToType; 3743 } 3744 3745 CandidateSet.NoteCandidates( 3746 *this, From, Cands); 3747 return true; 3748 } 3749 3750 // Helper for compareConversionFunctions that gets the FunctionType that the 3751 // conversion-operator return value 'points' to, or nullptr. 3752 static const FunctionType * 3753 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3754 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3755 const PointerType *RetPtrTy = 3756 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3757 3758 if (!RetPtrTy) 3759 return nullptr; 3760 3761 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3762 } 3763 3764 /// Compare the user-defined conversion functions or constructors 3765 /// of two user-defined conversion sequences to determine whether any ordering 3766 /// is possible. 3767 static ImplicitConversionSequence::CompareKind 3768 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3769 FunctionDecl *Function2) { 3770 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3771 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3772 if (!Conv1 || !Conv2) 3773 return ImplicitConversionSequence::Indistinguishable; 3774 3775 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3776 return ImplicitConversionSequence::Indistinguishable; 3777 3778 // Objective-C++: 3779 // If both conversion functions are implicitly-declared conversions from 3780 // a lambda closure type to a function pointer and a block pointer, 3781 // respectively, always prefer the conversion to a function pointer, 3782 // because the function pointer is more lightweight and is more likely 3783 // to keep code working. 3784 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3785 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3786 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3787 if (Block1 != Block2) 3788 return Block1 ? ImplicitConversionSequence::Worse 3789 : ImplicitConversionSequence::Better; 3790 } 3791 3792 // In order to support multiple calling conventions for the lambda conversion 3793 // operator (such as when the free and member function calling convention is 3794 // different), prefer the 'free' mechanism, followed by the calling-convention 3795 // of operator(). The latter is in place to support the MSVC-like solution of 3796 // defining ALL of the possible conversions in regards to calling-convention. 3797 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3798 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3799 3800 if (Conv1FuncRet && Conv2FuncRet && 3801 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3802 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3803 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3804 3805 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3806 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 3807 3808 CallingConv CallOpCC = 3809 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3810 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3811 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3812 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3813 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3814 3815 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3816 for (CallingConv CC : PrefOrder) { 3817 if (Conv1CC == CC) 3818 return ImplicitConversionSequence::Better; 3819 if (Conv2CC == CC) 3820 return ImplicitConversionSequence::Worse; 3821 } 3822 } 3823 3824 return ImplicitConversionSequence::Indistinguishable; 3825 } 3826 3827 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3828 const ImplicitConversionSequence &ICS) { 3829 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3830 (ICS.isUserDefined() && 3831 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3832 } 3833 3834 /// CompareImplicitConversionSequences - Compare two implicit 3835 /// conversion sequences to determine whether one is better than the 3836 /// other or if they are indistinguishable (C++ 13.3.3.2). 3837 static ImplicitConversionSequence::CompareKind 3838 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3839 const ImplicitConversionSequence& ICS1, 3840 const ImplicitConversionSequence& ICS2) 3841 { 3842 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3843 // conversion sequences (as defined in 13.3.3.1) 3844 // -- a standard conversion sequence (13.3.3.1.1) is a better 3845 // conversion sequence than a user-defined conversion sequence or 3846 // an ellipsis conversion sequence, and 3847 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3848 // conversion sequence than an ellipsis conversion sequence 3849 // (13.3.3.1.3). 3850 // 3851 // C++0x [over.best.ics]p10: 3852 // For the purpose of ranking implicit conversion sequences as 3853 // described in 13.3.3.2, the ambiguous conversion sequence is 3854 // treated as a user-defined sequence that is indistinguishable 3855 // from any other user-defined conversion sequence. 3856 3857 // String literal to 'char *' conversion has been deprecated in C++03. It has 3858 // been removed from C++11. We still accept this conversion, if it happens at 3859 // the best viable function. Otherwise, this conversion is considered worse 3860 // than ellipsis conversion. Consider this as an extension; this is not in the 3861 // standard. For example: 3862 // 3863 // int &f(...); // #1 3864 // void f(char*); // #2 3865 // void g() { int &r = f("foo"); } 3866 // 3867 // In C++03, we pick #2 as the best viable function. 3868 // In C++11, we pick #1 as the best viable function, because ellipsis 3869 // conversion is better than string-literal to char* conversion (since there 3870 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3871 // convert arguments, #2 would be the best viable function in C++11. 3872 // If the best viable function has this conversion, a warning will be issued 3873 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3874 3875 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3876 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3877 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 3878 // Ill-formedness must not differ 3879 ICS1.isBad() == ICS2.isBad()) 3880 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3881 ? ImplicitConversionSequence::Worse 3882 : ImplicitConversionSequence::Better; 3883 3884 if (ICS1.getKindRank() < ICS2.getKindRank()) 3885 return ImplicitConversionSequence::Better; 3886 if (ICS2.getKindRank() < ICS1.getKindRank()) 3887 return ImplicitConversionSequence::Worse; 3888 3889 // The following checks require both conversion sequences to be of 3890 // the same kind. 3891 if (ICS1.getKind() != ICS2.getKind()) 3892 return ImplicitConversionSequence::Indistinguishable; 3893 3894 ImplicitConversionSequence::CompareKind Result = 3895 ImplicitConversionSequence::Indistinguishable; 3896 3897 // Two implicit conversion sequences of the same form are 3898 // indistinguishable conversion sequences unless one of the 3899 // following rules apply: (C++ 13.3.3.2p3): 3900 3901 // List-initialization sequence L1 is a better conversion sequence than 3902 // list-initialization sequence L2 if: 3903 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3904 // if not that, 3905 // — L1 and L2 convert to arrays of the same element type, and either the 3906 // number of elements n_1 initialized by L1 is less than the number of 3907 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 3908 // an array of unknown bound and L1 does not, 3909 // even if one of the other rules in this paragraph would otherwise apply. 3910 if (!ICS1.isBad()) { 3911 bool StdInit1 = false, StdInit2 = false; 3912 if (ICS1.hasInitializerListContainerType()) 3913 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 3914 nullptr); 3915 if (ICS2.hasInitializerListContainerType()) 3916 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 3917 nullptr); 3918 if (StdInit1 != StdInit2) 3919 return StdInit1 ? ImplicitConversionSequence::Better 3920 : ImplicitConversionSequence::Worse; 3921 3922 if (ICS1.hasInitializerListContainerType() && 3923 ICS2.hasInitializerListContainerType()) 3924 if (auto *CAT1 = S.Context.getAsConstantArrayType( 3925 ICS1.getInitializerListContainerType())) 3926 if (auto *CAT2 = S.Context.getAsConstantArrayType( 3927 ICS2.getInitializerListContainerType())) { 3928 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 3929 CAT2->getElementType())) { 3930 // Both to arrays of the same element type 3931 if (CAT1->getSize() != CAT2->getSize()) 3932 // Different sized, the smaller wins 3933 return CAT1->getSize().ult(CAT2->getSize()) 3934 ? ImplicitConversionSequence::Better 3935 : ImplicitConversionSequence::Worse; 3936 if (ICS1.isInitializerListOfIncompleteArray() != 3937 ICS2.isInitializerListOfIncompleteArray()) 3938 // One is incomplete, it loses 3939 return ICS2.isInitializerListOfIncompleteArray() 3940 ? ImplicitConversionSequence::Better 3941 : ImplicitConversionSequence::Worse; 3942 } 3943 } 3944 } 3945 3946 if (ICS1.isStandard()) 3947 // Standard conversion sequence S1 is a better conversion sequence than 3948 // standard conversion sequence S2 if [...] 3949 Result = CompareStandardConversionSequences(S, Loc, 3950 ICS1.Standard, ICS2.Standard); 3951 else if (ICS1.isUserDefined()) { 3952 // User-defined conversion sequence U1 is a better conversion 3953 // sequence than another user-defined conversion sequence U2 if 3954 // they contain the same user-defined conversion function or 3955 // constructor and if the second standard conversion sequence of 3956 // U1 is better than the second standard conversion sequence of 3957 // U2 (C++ 13.3.3.2p3). 3958 if (ICS1.UserDefined.ConversionFunction == 3959 ICS2.UserDefined.ConversionFunction) 3960 Result = CompareStandardConversionSequences(S, Loc, 3961 ICS1.UserDefined.After, 3962 ICS2.UserDefined.After); 3963 else 3964 Result = compareConversionFunctions(S, 3965 ICS1.UserDefined.ConversionFunction, 3966 ICS2.UserDefined.ConversionFunction); 3967 } 3968 3969 return Result; 3970 } 3971 3972 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3973 // determine if one is a proper subset of the other. 3974 static ImplicitConversionSequence::CompareKind 3975 compareStandardConversionSubsets(ASTContext &Context, 3976 const StandardConversionSequence& SCS1, 3977 const StandardConversionSequence& SCS2) { 3978 ImplicitConversionSequence::CompareKind Result 3979 = ImplicitConversionSequence::Indistinguishable; 3980 3981 // the identity conversion sequence is considered to be a subsequence of 3982 // any non-identity conversion sequence 3983 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3984 return ImplicitConversionSequence::Better; 3985 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3986 return ImplicitConversionSequence::Worse; 3987 3988 if (SCS1.Second != SCS2.Second) { 3989 if (SCS1.Second == ICK_Identity) 3990 Result = ImplicitConversionSequence::Better; 3991 else if (SCS2.Second == ICK_Identity) 3992 Result = ImplicitConversionSequence::Worse; 3993 else 3994 return ImplicitConversionSequence::Indistinguishable; 3995 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3996 return ImplicitConversionSequence::Indistinguishable; 3997 3998 if (SCS1.Third == SCS2.Third) { 3999 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 4000 : ImplicitConversionSequence::Indistinguishable; 4001 } 4002 4003 if (SCS1.Third == ICK_Identity) 4004 return Result == ImplicitConversionSequence::Worse 4005 ? ImplicitConversionSequence::Indistinguishable 4006 : ImplicitConversionSequence::Better; 4007 4008 if (SCS2.Third == ICK_Identity) 4009 return Result == ImplicitConversionSequence::Better 4010 ? ImplicitConversionSequence::Indistinguishable 4011 : ImplicitConversionSequence::Worse; 4012 4013 return ImplicitConversionSequence::Indistinguishable; 4014 } 4015 4016 /// Determine whether one of the given reference bindings is better 4017 /// than the other based on what kind of bindings they are. 4018 static bool 4019 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 4020 const StandardConversionSequence &SCS2) { 4021 // C++0x [over.ics.rank]p3b4: 4022 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 4023 // implicit object parameter of a non-static member function declared 4024 // without a ref-qualifier, and *either* S1 binds an rvalue reference 4025 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 4026 // lvalue reference to a function lvalue and S2 binds an rvalue 4027 // reference*. 4028 // 4029 // FIXME: Rvalue references. We're going rogue with the above edits, 4030 // because the semantics in the current C++0x working paper (N3225 at the 4031 // time of this writing) break the standard definition of std::forward 4032 // and std::reference_wrapper when dealing with references to functions. 4033 // Proposed wording changes submitted to CWG for consideration. 4034 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 4035 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 4036 return false; 4037 4038 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 4039 SCS2.IsLvalueReference) || 4040 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 4041 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 4042 } 4043 4044 enum class FixedEnumPromotion { 4045 None, 4046 ToUnderlyingType, 4047 ToPromotedUnderlyingType 4048 }; 4049 4050 /// Returns kind of fixed enum promotion the \a SCS uses. 4051 static FixedEnumPromotion 4052 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 4053 4054 if (SCS.Second != ICK_Integral_Promotion) 4055 return FixedEnumPromotion::None; 4056 4057 QualType FromType = SCS.getFromType(); 4058 if (!FromType->isEnumeralType()) 4059 return FixedEnumPromotion::None; 4060 4061 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 4062 if (!Enum->isFixed()) 4063 return FixedEnumPromotion::None; 4064 4065 QualType UnderlyingType = Enum->getIntegerType(); 4066 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 4067 return FixedEnumPromotion::ToUnderlyingType; 4068 4069 return FixedEnumPromotion::ToPromotedUnderlyingType; 4070 } 4071 4072 /// CompareStandardConversionSequences - Compare two standard 4073 /// conversion sequences to determine whether one is better than the 4074 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 4075 static ImplicitConversionSequence::CompareKind 4076 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 4077 const StandardConversionSequence& SCS1, 4078 const StandardConversionSequence& SCS2) 4079 { 4080 // Standard conversion sequence S1 is a better conversion sequence 4081 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 4082 4083 // -- S1 is a proper subsequence of S2 (comparing the conversion 4084 // sequences in the canonical form defined by 13.3.3.1.1, 4085 // excluding any Lvalue Transformation; the identity conversion 4086 // sequence is considered to be a subsequence of any 4087 // non-identity conversion sequence) or, if not that, 4088 if (ImplicitConversionSequence::CompareKind CK 4089 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4090 return CK; 4091 4092 // -- the rank of S1 is better than the rank of S2 (by the rules 4093 // defined below), or, if not that, 4094 ImplicitConversionRank Rank1 = SCS1.getRank(); 4095 ImplicitConversionRank Rank2 = SCS2.getRank(); 4096 if (Rank1 < Rank2) 4097 return ImplicitConversionSequence::Better; 4098 else if (Rank2 < Rank1) 4099 return ImplicitConversionSequence::Worse; 4100 4101 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4102 // are indistinguishable unless one of the following rules 4103 // applies: 4104 4105 // A conversion that is not a conversion of a pointer, or 4106 // pointer to member, to bool is better than another conversion 4107 // that is such a conversion. 4108 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4109 return SCS2.isPointerConversionToBool() 4110 ? ImplicitConversionSequence::Better 4111 : ImplicitConversionSequence::Worse; 4112 4113 // C++14 [over.ics.rank]p4b2: 4114 // This is retroactively applied to C++11 by CWG 1601. 4115 // 4116 // A conversion that promotes an enumeration whose underlying type is fixed 4117 // to its underlying type is better than one that promotes to the promoted 4118 // underlying type, if the two are different. 4119 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4120 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4121 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4122 FEP1 != FEP2) 4123 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4124 ? ImplicitConversionSequence::Better 4125 : ImplicitConversionSequence::Worse; 4126 4127 // C++ [over.ics.rank]p4b2: 4128 // 4129 // If class B is derived directly or indirectly from class A, 4130 // conversion of B* to A* is better than conversion of B* to 4131 // void*, and conversion of A* to void* is better than conversion 4132 // of B* to void*. 4133 bool SCS1ConvertsToVoid 4134 = SCS1.isPointerConversionToVoidPointer(S.Context); 4135 bool SCS2ConvertsToVoid 4136 = SCS2.isPointerConversionToVoidPointer(S.Context); 4137 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4138 // Exactly one of the conversion sequences is a conversion to 4139 // a void pointer; it's the worse conversion. 4140 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4141 : ImplicitConversionSequence::Worse; 4142 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4143 // Neither conversion sequence converts to a void pointer; compare 4144 // their derived-to-base conversions. 4145 if (ImplicitConversionSequence::CompareKind DerivedCK 4146 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4147 return DerivedCK; 4148 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4149 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4150 // Both conversion sequences are conversions to void 4151 // pointers. Compare the source types to determine if there's an 4152 // inheritance relationship in their sources. 4153 QualType FromType1 = SCS1.getFromType(); 4154 QualType FromType2 = SCS2.getFromType(); 4155 4156 // Adjust the types we're converting from via the array-to-pointer 4157 // conversion, if we need to. 4158 if (SCS1.First == ICK_Array_To_Pointer) 4159 FromType1 = S.Context.getArrayDecayedType(FromType1); 4160 if (SCS2.First == ICK_Array_To_Pointer) 4161 FromType2 = S.Context.getArrayDecayedType(FromType2); 4162 4163 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4164 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4165 4166 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4167 return ImplicitConversionSequence::Better; 4168 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4169 return ImplicitConversionSequence::Worse; 4170 4171 // Objective-C++: If one interface is more specific than the 4172 // other, it is the better one. 4173 const ObjCObjectPointerType* FromObjCPtr1 4174 = FromType1->getAs<ObjCObjectPointerType>(); 4175 const ObjCObjectPointerType* FromObjCPtr2 4176 = FromType2->getAs<ObjCObjectPointerType>(); 4177 if (FromObjCPtr1 && FromObjCPtr2) { 4178 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4179 FromObjCPtr2); 4180 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4181 FromObjCPtr1); 4182 if (AssignLeft != AssignRight) { 4183 return AssignLeft? ImplicitConversionSequence::Better 4184 : ImplicitConversionSequence::Worse; 4185 } 4186 } 4187 } 4188 4189 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4190 // Check for a better reference binding based on the kind of bindings. 4191 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4192 return ImplicitConversionSequence::Better; 4193 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4194 return ImplicitConversionSequence::Worse; 4195 } 4196 4197 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4198 // bullet 3). 4199 if (ImplicitConversionSequence::CompareKind QualCK 4200 = CompareQualificationConversions(S, SCS1, SCS2)) 4201 return QualCK; 4202 4203 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4204 // C++ [over.ics.rank]p3b4: 4205 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4206 // which the references refer are the same type except for 4207 // top-level cv-qualifiers, and the type to which the reference 4208 // initialized by S2 refers is more cv-qualified than the type 4209 // to which the reference initialized by S1 refers. 4210 QualType T1 = SCS1.getToType(2); 4211 QualType T2 = SCS2.getToType(2); 4212 T1 = S.Context.getCanonicalType(T1); 4213 T2 = S.Context.getCanonicalType(T2); 4214 Qualifiers T1Quals, T2Quals; 4215 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4216 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4217 if (UnqualT1 == UnqualT2) { 4218 // Objective-C++ ARC: If the references refer to objects with different 4219 // lifetimes, prefer bindings that don't change lifetime. 4220 if (SCS1.ObjCLifetimeConversionBinding != 4221 SCS2.ObjCLifetimeConversionBinding) { 4222 return SCS1.ObjCLifetimeConversionBinding 4223 ? ImplicitConversionSequence::Worse 4224 : ImplicitConversionSequence::Better; 4225 } 4226 4227 // If the type is an array type, promote the element qualifiers to the 4228 // type for comparison. 4229 if (isa<ArrayType>(T1) && T1Quals) 4230 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4231 if (isa<ArrayType>(T2) && T2Quals) 4232 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4233 if (T2.isMoreQualifiedThan(T1)) 4234 return ImplicitConversionSequence::Better; 4235 if (T1.isMoreQualifiedThan(T2)) 4236 return ImplicitConversionSequence::Worse; 4237 } 4238 } 4239 4240 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4241 // floating-to-integral conversion if the integral conversion 4242 // is between types of the same size. 4243 // For example: 4244 // void f(float); 4245 // void f(int); 4246 // int main { 4247 // long a; 4248 // f(a); 4249 // } 4250 // Here, MSVC will call f(int) instead of generating a compile error 4251 // as clang will do in standard mode. 4252 if (S.getLangOpts().MSVCCompat && 4253 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4254 SCS1.Second == ICK_Integral_Conversion && 4255 SCS2.Second == ICK_Floating_Integral && 4256 S.Context.getTypeSize(SCS1.getFromType()) == 4257 S.Context.getTypeSize(SCS1.getToType(2))) 4258 return ImplicitConversionSequence::Better; 4259 4260 // Prefer a compatible vector conversion over a lax vector conversion 4261 // For example: 4262 // 4263 // typedef float __v4sf __attribute__((__vector_size__(16))); 4264 // void f(vector float); 4265 // void f(vector signed int); 4266 // int main() { 4267 // __v4sf a; 4268 // f(a); 4269 // } 4270 // Here, we'd like to choose f(vector float) and not 4271 // report an ambiguous call error 4272 if (SCS1.Second == ICK_Vector_Conversion && 4273 SCS2.Second == ICK_Vector_Conversion) { 4274 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4275 SCS1.getFromType(), SCS1.getToType(2)); 4276 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4277 SCS2.getFromType(), SCS2.getToType(2)); 4278 4279 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4280 return SCS1IsCompatibleVectorConversion 4281 ? ImplicitConversionSequence::Better 4282 : ImplicitConversionSequence::Worse; 4283 } 4284 4285 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4286 SCS2.Second == ICK_SVE_Vector_Conversion) { 4287 bool SCS1IsCompatibleSVEVectorConversion = 4288 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4289 bool SCS2IsCompatibleSVEVectorConversion = 4290 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4291 4292 if (SCS1IsCompatibleSVEVectorConversion != 4293 SCS2IsCompatibleSVEVectorConversion) 4294 return SCS1IsCompatibleSVEVectorConversion 4295 ? ImplicitConversionSequence::Better 4296 : ImplicitConversionSequence::Worse; 4297 } 4298 4299 return ImplicitConversionSequence::Indistinguishable; 4300 } 4301 4302 /// CompareQualificationConversions - Compares two standard conversion 4303 /// sequences to determine whether they can be ranked based on their 4304 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4305 static ImplicitConversionSequence::CompareKind 4306 CompareQualificationConversions(Sema &S, 4307 const StandardConversionSequence& SCS1, 4308 const StandardConversionSequence& SCS2) { 4309 // C++ [over.ics.rank]p3: 4310 // -- S1 and S2 differ only in their qualification conversion and 4311 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4312 // [C++98] 4313 // [...] and the cv-qualification signature of type T1 is a proper subset 4314 // of the cv-qualification signature of type T2, and S1 is not the 4315 // deprecated string literal array-to-pointer conversion (4.2). 4316 // [C++2a] 4317 // [...] where T1 can be converted to T2 by a qualification conversion. 4318 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4319 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4320 return ImplicitConversionSequence::Indistinguishable; 4321 4322 // FIXME: the example in the standard doesn't use a qualification 4323 // conversion (!) 4324 QualType T1 = SCS1.getToType(2); 4325 QualType T2 = SCS2.getToType(2); 4326 T1 = S.Context.getCanonicalType(T1); 4327 T2 = S.Context.getCanonicalType(T2); 4328 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4329 Qualifiers T1Quals, T2Quals; 4330 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4331 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4332 4333 // If the types are the same, we won't learn anything by unwrapping 4334 // them. 4335 if (UnqualT1 == UnqualT2) 4336 return ImplicitConversionSequence::Indistinguishable; 4337 4338 // Don't ever prefer a standard conversion sequence that uses the deprecated 4339 // string literal array to pointer conversion. 4340 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4341 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4342 4343 // Objective-C++ ARC: 4344 // Prefer qualification conversions not involving a change in lifetime 4345 // to qualification conversions that do change lifetime. 4346 if (SCS1.QualificationIncludesObjCLifetime && 4347 !SCS2.QualificationIncludesObjCLifetime) 4348 CanPick1 = false; 4349 if (SCS2.QualificationIncludesObjCLifetime && 4350 !SCS1.QualificationIncludesObjCLifetime) 4351 CanPick2 = false; 4352 4353 bool ObjCLifetimeConversion; 4354 if (CanPick1 && 4355 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4356 CanPick1 = false; 4357 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4358 // directions, so we can't short-cut this second check in general. 4359 if (CanPick2 && 4360 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4361 CanPick2 = false; 4362 4363 if (CanPick1 != CanPick2) 4364 return CanPick1 ? ImplicitConversionSequence::Better 4365 : ImplicitConversionSequence::Worse; 4366 return ImplicitConversionSequence::Indistinguishable; 4367 } 4368 4369 /// CompareDerivedToBaseConversions - Compares two standard conversion 4370 /// sequences to determine whether they can be ranked based on their 4371 /// various kinds of derived-to-base conversions (C++ 4372 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4373 /// conversions between Objective-C interface types. 4374 static ImplicitConversionSequence::CompareKind 4375 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4376 const StandardConversionSequence& SCS1, 4377 const StandardConversionSequence& SCS2) { 4378 QualType FromType1 = SCS1.getFromType(); 4379 QualType ToType1 = SCS1.getToType(1); 4380 QualType FromType2 = SCS2.getFromType(); 4381 QualType ToType2 = SCS2.getToType(1); 4382 4383 // Adjust the types we're converting from via the array-to-pointer 4384 // conversion, if we need to. 4385 if (SCS1.First == ICK_Array_To_Pointer) 4386 FromType1 = S.Context.getArrayDecayedType(FromType1); 4387 if (SCS2.First == ICK_Array_To_Pointer) 4388 FromType2 = S.Context.getArrayDecayedType(FromType2); 4389 4390 // Canonicalize all of the types. 4391 FromType1 = S.Context.getCanonicalType(FromType1); 4392 ToType1 = S.Context.getCanonicalType(ToType1); 4393 FromType2 = S.Context.getCanonicalType(FromType2); 4394 ToType2 = S.Context.getCanonicalType(ToType2); 4395 4396 // C++ [over.ics.rank]p4b3: 4397 // 4398 // If class B is derived directly or indirectly from class A and 4399 // class C is derived directly or indirectly from B, 4400 // 4401 // Compare based on pointer conversions. 4402 if (SCS1.Second == ICK_Pointer_Conversion && 4403 SCS2.Second == ICK_Pointer_Conversion && 4404 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4405 FromType1->isPointerType() && FromType2->isPointerType() && 4406 ToType1->isPointerType() && ToType2->isPointerType()) { 4407 QualType FromPointee1 = 4408 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4409 QualType ToPointee1 = 4410 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4411 QualType FromPointee2 = 4412 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4413 QualType ToPointee2 = 4414 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4415 4416 // -- conversion of C* to B* is better than conversion of C* to A*, 4417 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4418 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4419 return ImplicitConversionSequence::Better; 4420 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4421 return ImplicitConversionSequence::Worse; 4422 } 4423 4424 // -- conversion of B* to A* is better than conversion of C* to A*, 4425 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4426 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4427 return ImplicitConversionSequence::Better; 4428 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4429 return ImplicitConversionSequence::Worse; 4430 } 4431 } else if (SCS1.Second == ICK_Pointer_Conversion && 4432 SCS2.Second == ICK_Pointer_Conversion) { 4433 const ObjCObjectPointerType *FromPtr1 4434 = FromType1->getAs<ObjCObjectPointerType>(); 4435 const ObjCObjectPointerType *FromPtr2 4436 = FromType2->getAs<ObjCObjectPointerType>(); 4437 const ObjCObjectPointerType *ToPtr1 4438 = ToType1->getAs<ObjCObjectPointerType>(); 4439 const ObjCObjectPointerType *ToPtr2 4440 = ToType2->getAs<ObjCObjectPointerType>(); 4441 4442 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4443 // Apply the same conversion ranking rules for Objective-C pointer types 4444 // that we do for C++ pointers to class types. However, we employ the 4445 // Objective-C pseudo-subtyping relationship used for assignment of 4446 // Objective-C pointer types. 4447 bool FromAssignLeft 4448 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4449 bool FromAssignRight 4450 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4451 bool ToAssignLeft 4452 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4453 bool ToAssignRight 4454 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4455 4456 // A conversion to an a non-id object pointer type or qualified 'id' 4457 // type is better than a conversion to 'id'. 4458 if (ToPtr1->isObjCIdType() && 4459 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4460 return ImplicitConversionSequence::Worse; 4461 if (ToPtr2->isObjCIdType() && 4462 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4463 return ImplicitConversionSequence::Better; 4464 4465 // A conversion to a non-id object pointer type is better than a 4466 // conversion to a qualified 'id' type 4467 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4468 return ImplicitConversionSequence::Worse; 4469 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4470 return ImplicitConversionSequence::Better; 4471 4472 // A conversion to an a non-Class object pointer type or qualified 'Class' 4473 // type is better than a conversion to 'Class'. 4474 if (ToPtr1->isObjCClassType() && 4475 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4476 return ImplicitConversionSequence::Worse; 4477 if (ToPtr2->isObjCClassType() && 4478 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4479 return ImplicitConversionSequence::Better; 4480 4481 // A conversion to a non-Class object pointer type is better than a 4482 // conversion to a qualified 'Class' type. 4483 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4484 return ImplicitConversionSequence::Worse; 4485 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4486 return ImplicitConversionSequence::Better; 4487 4488 // -- "conversion of C* to B* is better than conversion of C* to A*," 4489 if (S.Context.hasSameType(FromType1, FromType2) && 4490 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4491 (ToAssignLeft != ToAssignRight)) { 4492 if (FromPtr1->isSpecialized()) { 4493 // "conversion of B<A> * to B * is better than conversion of B * to 4494 // C *. 4495 bool IsFirstSame = 4496 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4497 bool IsSecondSame = 4498 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4499 if (IsFirstSame) { 4500 if (!IsSecondSame) 4501 return ImplicitConversionSequence::Better; 4502 } else if (IsSecondSame) 4503 return ImplicitConversionSequence::Worse; 4504 } 4505 return ToAssignLeft? ImplicitConversionSequence::Worse 4506 : ImplicitConversionSequence::Better; 4507 } 4508 4509 // -- "conversion of B* to A* is better than conversion of C* to A*," 4510 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4511 (FromAssignLeft != FromAssignRight)) 4512 return FromAssignLeft? ImplicitConversionSequence::Better 4513 : ImplicitConversionSequence::Worse; 4514 } 4515 } 4516 4517 // Ranking of member-pointer types. 4518 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4519 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4520 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4521 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4522 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4523 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4524 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4525 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4526 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4527 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4528 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4529 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4530 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4531 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4532 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4533 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4534 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4535 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4536 return ImplicitConversionSequence::Worse; 4537 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4538 return ImplicitConversionSequence::Better; 4539 } 4540 // conversion of B::* to C::* is better than conversion of A::* to C::* 4541 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4542 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4543 return ImplicitConversionSequence::Better; 4544 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4545 return ImplicitConversionSequence::Worse; 4546 } 4547 } 4548 4549 if (SCS1.Second == ICK_Derived_To_Base) { 4550 // -- conversion of C to B is better than conversion of C to A, 4551 // -- binding of an expression of type C to a reference of type 4552 // B& is better than binding an expression of type C to a 4553 // reference of type A&, 4554 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4555 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4556 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4557 return ImplicitConversionSequence::Better; 4558 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4559 return ImplicitConversionSequence::Worse; 4560 } 4561 4562 // -- conversion of B to A is better than conversion of C to A. 4563 // -- binding of an expression of type B to a reference of type 4564 // A& is better than binding an expression of type C to a 4565 // reference of type A&, 4566 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4567 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4568 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4569 return ImplicitConversionSequence::Better; 4570 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4571 return ImplicitConversionSequence::Worse; 4572 } 4573 } 4574 4575 return ImplicitConversionSequence::Indistinguishable; 4576 } 4577 4578 /// Determine whether the given type is valid, e.g., it is not an invalid 4579 /// C++ class. 4580 static bool isTypeValid(QualType T) { 4581 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4582 return !Record->isInvalidDecl(); 4583 4584 return true; 4585 } 4586 4587 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4588 if (!T.getQualifiers().hasUnaligned()) 4589 return T; 4590 4591 Qualifiers Q; 4592 T = Ctx.getUnqualifiedArrayType(T, Q); 4593 Q.removeUnaligned(); 4594 return Ctx.getQualifiedType(T, Q); 4595 } 4596 4597 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4598 /// determine whether they are reference-compatible, 4599 /// reference-related, or incompatible, for use in C++ initialization by 4600 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4601 /// type, and the first type (T1) is the pointee type of the reference 4602 /// type being initialized. 4603 Sema::ReferenceCompareResult 4604 Sema::CompareReferenceRelationship(SourceLocation Loc, 4605 QualType OrigT1, QualType OrigT2, 4606 ReferenceConversions *ConvOut) { 4607 assert(!OrigT1->isReferenceType() && 4608 "T1 must be the pointee type of the reference type"); 4609 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4610 4611 QualType T1 = Context.getCanonicalType(OrigT1); 4612 QualType T2 = Context.getCanonicalType(OrigT2); 4613 Qualifiers T1Quals, T2Quals; 4614 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4615 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4616 4617 ReferenceConversions ConvTmp; 4618 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4619 Conv = ReferenceConversions(); 4620 4621 // C++2a [dcl.init.ref]p4: 4622 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4623 // reference-related to "cv2 T2" if T1 is similar to T2, or 4624 // T1 is a base class of T2. 4625 // "cv1 T1" is reference-compatible with "cv2 T2" if 4626 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4627 // "pointer to cv1 T1" via a standard conversion sequence. 4628 4629 // Check for standard conversions we can apply to pointers: derived-to-base 4630 // conversions, ObjC pointer conversions, and function pointer conversions. 4631 // (Qualification conversions are checked last.) 4632 QualType ConvertedT2; 4633 if (UnqualT1 == UnqualT2) { 4634 // Nothing to do. 4635 } else if (isCompleteType(Loc, OrigT2) && 4636 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4637 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4638 Conv |= ReferenceConversions::DerivedToBase; 4639 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4640 UnqualT2->isObjCObjectOrInterfaceType() && 4641 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4642 Conv |= ReferenceConversions::ObjC; 4643 else if (UnqualT2->isFunctionType() && 4644 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4645 Conv |= ReferenceConversions::Function; 4646 // No need to check qualifiers; function types don't have them. 4647 return Ref_Compatible; 4648 } 4649 bool ConvertedReferent = Conv != 0; 4650 4651 // We can have a qualification conversion. Compute whether the types are 4652 // similar at the same time. 4653 bool PreviousToQualsIncludeConst = true; 4654 bool TopLevel = true; 4655 do { 4656 if (T1 == T2) 4657 break; 4658 4659 // We will need a qualification conversion. 4660 Conv |= ReferenceConversions::Qualification; 4661 4662 // Track whether we performed a qualification conversion anywhere other 4663 // than the top level. This matters for ranking reference bindings in 4664 // overload resolution. 4665 if (!TopLevel) 4666 Conv |= ReferenceConversions::NestedQualification; 4667 4668 // MS compiler ignores __unaligned qualifier for references; do the same. 4669 T1 = withoutUnaligned(Context, T1); 4670 T2 = withoutUnaligned(Context, T2); 4671 4672 // If we find a qualifier mismatch, the types are not reference-compatible, 4673 // but are still be reference-related if they're similar. 4674 bool ObjCLifetimeConversion = false; 4675 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4676 PreviousToQualsIncludeConst, 4677 ObjCLifetimeConversion)) 4678 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4679 ? Ref_Related 4680 : Ref_Incompatible; 4681 4682 // FIXME: Should we track this for any level other than the first? 4683 if (ObjCLifetimeConversion) 4684 Conv |= ReferenceConversions::ObjCLifetime; 4685 4686 TopLevel = false; 4687 } while (Context.UnwrapSimilarTypes(T1, T2)); 4688 4689 // At this point, if the types are reference-related, we must either have the 4690 // same inner type (ignoring qualifiers), or must have already worked out how 4691 // to convert the referent. 4692 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4693 ? Ref_Compatible 4694 : Ref_Incompatible; 4695 } 4696 4697 /// Look for a user-defined conversion to a value reference-compatible 4698 /// with DeclType. Return true if something definite is found. 4699 static bool 4700 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4701 QualType DeclType, SourceLocation DeclLoc, 4702 Expr *Init, QualType T2, bool AllowRvalues, 4703 bool AllowExplicit) { 4704 assert(T2->isRecordType() && "Can only find conversions of record types."); 4705 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4706 4707 OverloadCandidateSet CandidateSet( 4708 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4709 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4710 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4711 NamedDecl *D = *I; 4712 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4713 if (isa<UsingShadowDecl>(D)) 4714 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4715 4716 FunctionTemplateDecl *ConvTemplate 4717 = dyn_cast<FunctionTemplateDecl>(D); 4718 CXXConversionDecl *Conv; 4719 if (ConvTemplate) 4720 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4721 else 4722 Conv = cast<CXXConversionDecl>(D); 4723 4724 if (AllowRvalues) { 4725 // If we are initializing an rvalue reference, don't permit conversion 4726 // functions that return lvalues. 4727 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4728 const ReferenceType *RefType 4729 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4730 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4731 continue; 4732 } 4733 4734 if (!ConvTemplate && 4735 S.CompareReferenceRelationship( 4736 DeclLoc, 4737 Conv->getConversionType() 4738 .getNonReferenceType() 4739 .getUnqualifiedType(), 4740 DeclType.getNonReferenceType().getUnqualifiedType()) == 4741 Sema::Ref_Incompatible) 4742 continue; 4743 } else { 4744 // If the conversion function doesn't return a reference type, 4745 // it can't be considered for this conversion. An rvalue reference 4746 // is only acceptable if its referencee is a function type. 4747 4748 const ReferenceType *RefType = 4749 Conv->getConversionType()->getAs<ReferenceType>(); 4750 if (!RefType || 4751 (!RefType->isLValueReferenceType() && 4752 !RefType->getPointeeType()->isFunctionType())) 4753 continue; 4754 } 4755 4756 if (ConvTemplate) 4757 S.AddTemplateConversionCandidate( 4758 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4759 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4760 else 4761 S.AddConversionCandidate( 4762 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4763 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4764 } 4765 4766 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4767 4768 OverloadCandidateSet::iterator Best; 4769 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4770 case OR_Success: 4771 // C++ [over.ics.ref]p1: 4772 // 4773 // [...] If the parameter binds directly to the result of 4774 // applying a conversion function to the argument 4775 // expression, the implicit conversion sequence is a 4776 // user-defined conversion sequence (13.3.3.1.2), with the 4777 // second standard conversion sequence either an identity 4778 // conversion or, if the conversion function returns an 4779 // entity of a type that is a derived class of the parameter 4780 // type, a derived-to-base Conversion. 4781 if (!Best->FinalConversion.DirectBinding) 4782 return false; 4783 4784 ICS.setUserDefined(); 4785 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4786 ICS.UserDefined.After = Best->FinalConversion; 4787 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4788 ICS.UserDefined.ConversionFunction = Best->Function; 4789 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4790 ICS.UserDefined.EllipsisConversion = false; 4791 assert(ICS.UserDefined.After.ReferenceBinding && 4792 ICS.UserDefined.After.DirectBinding && 4793 "Expected a direct reference binding!"); 4794 return true; 4795 4796 case OR_Ambiguous: 4797 ICS.setAmbiguous(); 4798 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4799 Cand != CandidateSet.end(); ++Cand) 4800 if (Cand->Best) 4801 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4802 return true; 4803 4804 case OR_No_Viable_Function: 4805 case OR_Deleted: 4806 // There was no suitable conversion, or we found a deleted 4807 // conversion; continue with other checks. 4808 return false; 4809 } 4810 4811 llvm_unreachable("Invalid OverloadResult!"); 4812 } 4813 4814 /// Compute an implicit conversion sequence for reference 4815 /// initialization. 4816 static ImplicitConversionSequence 4817 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4818 SourceLocation DeclLoc, 4819 bool SuppressUserConversions, 4820 bool AllowExplicit) { 4821 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4822 4823 // Most paths end in a failed conversion. 4824 ImplicitConversionSequence ICS; 4825 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4826 4827 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4828 QualType T2 = Init->getType(); 4829 4830 // If the initializer is the address of an overloaded function, try 4831 // to resolve the overloaded function. If all goes well, T2 is the 4832 // type of the resulting function. 4833 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4834 DeclAccessPair Found; 4835 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4836 false, Found)) 4837 T2 = Fn->getType(); 4838 } 4839 4840 // Compute some basic properties of the types and the initializer. 4841 bool isRValRef = DeclType->isRValueReferenceType(); 4842 Expr::Classification InitCategory = Init->Classify(S.Context); 4843 4844 Sema::ReferenceConversions RefConv; 4845 Sema::ReferenceCompareResult RefRelationship = 4846 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4847 4848 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4849 ICS.setStandard(); 4850 ICS.Standard.First = ICK_Identity; 4851 // FIXME: A reference binding can be a function conversion too. We should 4852 // consider that when ordering reference-to-function bindings. 4853 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4854 ? ICK_Derived_To_Base 4855 : (RefConv & Sema::ReferenceConversions::ObjC) 4856 ? ICK_Compatible_Conversion 4857 : ICK_Identity; 4858 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4859 // a reference binding that performs a non-top-level qualification 4860 // conversion as a qualification conversion, not as an identity conversion. 4861 ICS.Standard.Third = (RefConv & 4862 Sema::ReferenceConversions::NestedQualification) 4863 ? ICK_Qualification 4864 : ICK_Identity; 4865 ICS.Standard.setFromType(T2); 4866 ICS.Standard.setToType(0, T2); 4867 ICS.Standard.setToType(1, T1); 4868 ICS.Standard.setToType(2, T1); 4869 ICS.Standard.ReferenceBinding = true; 4870 ICS.Standard.DirectBinding = BindsDirectly; 4871 ICS.Standard.IsLvalueReference = !isRValRef; 4872 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4873 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4874 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4875 ICS.Standard.ObjCLifetimeConversionBinding = 4876 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4877 ICS.Standard.CopyConstructor = nullptr; 4878 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4879 }; 4880 4881 // C++0x [dcl.init.ref]p5: 4882 // A reference to type "cv1 T1" is initialized by an expression 4883 // of type "cv2 T2" as follows: 4884 4885 // -- If reference is an lvalue reference and the initializer expression 4886 if (!isRValRef) { 4887 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4888 // reference-compatible with "cv2 T2," or 4889 // 4890 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4891 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4892 // C++ [over.ics.ref]p1: 4893 // When a parameter of reference type binds directly (8.5.3) 4894 // to an argument expression, the implicit conversion sequence 4895 // is the identity conversion, unless the argument expression 4896 // has a type that is a derived class of the parameter type, 4897 // in which case the implicit conversion sequence is a 4898 // derived-to-base Conversion (13.3.3.1). 4899 SetAsReferenceBinding(/*BindsDirectly=*/true); 4900 4901 // Nothing more to do: the inaccessibility/ambiguity check for 4902 // derived-to-base conversions is suppressed when we're 4903 // computing the implicit conversion sequence (C++ 4904 // [over.best.ics]p2). 4905 return ICS; 4906 } 4907 4908 // -- has a class type (i.e., T2 is a class type), where T1 is 4909 // not reference-related to T2, and can be implicitly 4910 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4911 // is reference-compatible with "cv3 T3" 92) (this 4912 // conversion is selected by enumerating the applicable 4913 // conversion functions (13.3.1.6) and choosing the best 4914 // one through overload resolution (13.3)), 4915 if (!SuppressUserConversions && T2->isRecordType() && 4916 S.isCompleteType(DeclLoc, T2) && 4917 RefRelationship == Sema::Ref_Incompatible) { 4918 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4919 Init, T2, /*AllowRvalues=*/false, 4920 AllowExplicit)) 4921 return ICS; 4922 } 4923 } 4924 4925 // -- Otherwise, the reference shall be an lvalue reference to a 4926 // non-volatile const type (i.e., cv1 shall be const), or the reference 4927 // shall be an rvalue reference. 4928 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4929 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4930 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4931 return ICS; 4932 } 4933 4934 // -- If the initializer expression 4935 // 4936 // -- is an xvalue, class prvalue, array prvalue or function 4937 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4938 if (RefRelationship == Sema::Ref_Compatible && 4939 (InitCategory.isXValue() || 4940 (InitCategory.isPRValue() && 4941 (T2->isRecordType() || T2->isArrayType())) || 4942 (InitCategory.isLValue() && T2->isFunctionType()))) { 4943 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4944 // binding unless we're binding to a class prvalue. 4945 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4946 // allow the use of rvalue references in C++98/03 for the benefit of 4947 // standard library implementors; therefore, we need the xvalue check here. 4948 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4949 !(InitCategory.isPRValue() || T2->isRecordType())); 4950 return ICS; 4951 } 4952 4953 // -- has a class type (i.e., T2 is a class type), where T1 is not 4954 // reference-related to T2, and can be implicitly converted to 4955 // an xvalue, class prvalue, or function lvalue of type 4956 // "cv3 T3", where "cv1 T1" is reference-compatible with 4957 // "cv3 T3", 4958 // 4959 // then the reference is bound to the value of the initializer 4960 // expression in the first case and to the result of the conversion 4961 // in the second case (or, in either case, to an appropriate base 4962 // class subobject). 4963 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4964 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4965 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4966 Init, T2, /*AllowRvalues=*/true, 4967 AllowExplicit)) { 4968 // In the second case, if the reference is an rvalue reference 4969 // and the second standard conversion sequence of the 4970 // user-defined conversion sequence includes an lvalue-to-rvalue 4971 // conversion, the program is ill-formed. 4972 if (ICS.isUserDefined() && isRValRef && 4973 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4974 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4975 4976 return ICS; 4977 } 4978 4979 // A temporary of function type cannot be created; don't even try. 4980 if (T1->isFunctionType()) 4981 return ICS; 4982 4983 // -- Otherwise, a temporary of type "cv1 T1" is created and 4984 // initialized from the initializer expression using the 4985 // rules for a non-reference copy initialization (8.5). The 4986 // reference is then bound to the temporary. If T1 is 4987 // reference-related to T2, cv1 must be the same 4988 // cv-qualification as, or greater cv-qualification than, 4989 // cv2; otherwise, the program is ill-formed. 4990 if (RefRelationship == Sema::Ref_Related) { 4991 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4992 // we would be reference-compatible or reference-compatible with 4993 // added qualification. But that wasn't the case, so the reference 4994 // initialization fails. 4995 // 4996 // Note that we only want to check address spaces and cvr-qualifiers here. 4997 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4998 Qualifiers T1Quals = T1.getQualifiers(); 4999 Qualifiers T2Quals = T2.getQualifiers(); 5000 T1Quals.removeObjCGCAttr(); 5001 T1Quals.removeObjCLifetime(); 5002 T2Quals.removeObjCGCAttr(); 5003 T2Quals.removeObjCLifetime(); 5004 // MS compiler ignores __unaligned qualifier for references; do the same. 5005 T1Quals.removeUnaligned(); 5006 T2Quals.removeUnaligned(); 5007 if (!T1Quals.compatiblyIncludes(T2Quals)) 5008 return ICS; 5009 } 5010 5011 // If at least one of the types is a class type, the types are not 5012 // related, and we aren't allowed any user conversions, the 5013 // reference binding fails. This case is important for breaking 5014 // recursion, since TryImplicitConversion below will attempt to 5015 // create a temporary through the use of a copy constructor. 5016 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5017 (T1->isRecordType() || T2->isRecordType())) 5018 return ICS; 5019 5020 // If T1 is reference-related to T2 and the reference is an rvalue 5021 // reference, the initializer expression shall not be an lvalue. 5022 if (RefRelationship >= Sema::Ref_Related && isRValRef && 5023 Init->Classify(S.Context).isLValue()) { 5024 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 5025 return ICS; 5026 } 5027 5028 // C++ [over.ics.ref]p2: 5029 // When a parameter of reference type is not bound directly to 5030 // an argument expression, the conversion sequence is the one 5031 // required to convert the argument expression to the 5032 // underlying type of the reference according to 5033 // 13.3.3.1. Conceptually, this conversion sequence corresponds 5034 // to copy-initializing a temporary of the underlying type with 5035 // the argument expression. Any difference in top-level 5036 // cv-qualification is subsumed by the initialization itself 5037 // and does not constitute a conversion. 5038 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 5039 AllowedExplicit::None, 5040 /*InOverloadResolution=*/false, 5041 /*CStyle=*/false, 5042 /*AllowObjCWritebackConversion=*/false, 5043 /*AllowObjCConversionOnExplicit=*/false); 5044 5045 // Of course, that's still a reference binding. 5046 if (ICS.isStandard()) { 5047 ICS.Standard.ReferenceBinding = true; 5048 ICS.Standard.IsLvalueReference = !isRValRef; 5049 ICS.Standard.BindsToFunctionLvalue = false; 5050 ICS.Standard.BindsToRvalue = true; 5051 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5052 ICS.Standard.ObjCLifetimeConversionBinding = false; 5053 } else if (ICS.isUserDefined()) { 5054 const ReferenceType *LValRefType = 5055 ICS.UserDefined.ConversionFunction->getReturnType() 5056 ->getAs<LValueReferenceType>(); 5057 5058 // C++ [over.ics.ref]p3: 5059 // Except for an implicit object parameter, for which see 13.3.1, a 5060 // standard conversion sequence cannot be formed if it requires [...] 5061 // binding an rvalue reference to an lvalue other than a function 5062 // lvalue. 5063 // Note that the function case is not possible here. 5064 if (isRValRef && LValRefType) { 5065 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5066 return ICS; 5067 } 5068 5069 ICS.UserDefined.After.ReferenceBinding = true; 5070 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 5071 ICS.UserDefined.After.BindsToFunctionLvalue = false; 5072 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 5073 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5074 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 5075 } 5076 5077 return ICS; 5078 } 5079 5080 static ImplicitConversionSequence 5081 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5082 bool SuppressUserConversions, 5083 bool InOverloadResolution, 5084 bool AllowObjCWritebackConversion, 5085 bool AllowExplicit = false); 5086 5087 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5088 /// initializer list From. 5089 static ImplicitConversionSequence 5090 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5091 bool SuppressUserConversions, 5092 bool InOverloadResolution, 5093 bool AllowObjCWritebackConversion) { 5094 // C++11 [over.ics.list]p1: 5095 // When an argument is an initializer list, it is not an expression and 5096 // special rules apply for converting it to a parameter type. 5097 5098 ImplicitConversionSequence Result; 5099 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5100 5101 // We need a complete type for what follows. With one C++20 exception, 5102 // incomplete types can never be initialized from init lists. 5103 QualType InitTy = ToType; 5104 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5105 if (AT && S.getLangOpts().CPlusPlus20) 5106 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5107 // C++20 allows list initialization of an incomplete array type. 5108 InitTy = IAT->getElementType(); 5109 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5110 return Result; 5111 5112 // Per DR1467: 5113 // If the parameter type is a class X and the initializer list has a single 5114 // element of type cv U, where U is X or a class derived from X, the 5115 // implicit conversion sequence is the one required to convert the element 5116 // to the parameter type. 5117 // 5118 // Otherwise, if the parameter type is a character array [... ] 5119 // and the initializer list has a single element that is an 5120 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5121 // implicit conversion sequence is the identity conversion. 5122 if (From->getNumInits() == 1) { 5123 if (ToType->isRecordType()) { 5124 QualType InitType = From->getInit(0)->getType(); 5125 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5126 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5127 return TryCopyInitialization(S, From->getInit(0), ToType, 5128 SuppressUserConversions, 5129 InOverloadResolution, 5130 AllowObjCWritebackConversion); 5131 } 5132 5133 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5134 InitializedEntity Entity = 5135 InitializedEntity::InitializeParameter(S.Context, ToType, 5136 /*Consumed=*/false); 5137 if (S.CanPerformCopyInitialization(Entity, From)) { 5138 Result.setStandard(); 5139 Result.Standard.setAsIdentityConversion(); 5140 Result.Standard.setFromType(ToType); 5141 Result.Standard.setAllToTypes(ToType); 5142 return Result; 5143 } 5144 } 5145 } 5146 5147 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5148 // C++11 [over.ics.list]p2: 5149 // If the parameter type is std::initializer_list<X> or "array of X" and 5150 // all the elements can be implicitly converted to X, the implicit 5151 // conversion sequence is the worst conversion necessary to convert an 5152 // element of the list to X. 5153 // 5154 // C++14 [over.ics.list]p3: 5155 // Otherwise, if the parameter type is "array of N X", if the initializer 5156 // list has exactly N elements or if it has fewer than N elements and X is 5157 // default-constructible, and if all the elements of the initializer list 5158 // can be implicitly converted to X, the implicit conversion sequence is 5159 // the worst conversion necessary to convert an element of the list to X. 5160 if (AT || S.isStdInitializerList(ToType, &InitTy)) { 5161 unsigned e = From->getNumInits(); 5162 ImplicitConversionSequence DfltElt; 5163 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5164 QualType()); 5165 QualType ContTy = ToType; 5166 bool IsUnbounded = false; 5167 if (AT) { 5168 InitTy = AT->getElementType(); 5169 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5170 if (CT->getSize().ult(e)) { 5171 // Too many inits, fatally bad 5172 Result.setBad(BadConversionSequence::too_many_initializers, From, 5173 ToType); 5174 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5175 return Result; 5176 } 5177 if (CT->getSize().ugt(e)) { 5178 // Need an init from empty {}, is there one? 5179 InitListExpr EmptyList(S.Context, From->getEndLoc(), None, 5180 From->getEndLoc()); 5181 EmptyList.setType(S.Context.VoidTy); 5182 DfltElt = TryListConversion( 5183 S, &EmptyList, InitTy, SuppressUserConversions, 5184 InOverloadResolution, AllowObjCWritebackConversion); 5185 if (DfltElt.isBad()) { 5186 // No {} init, fatally bad 5187 Result.setBad(BadConversionSequence::too_few_initializers, From, 5188 ToType); 5189 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5190 return Result; 5191 } 5192 } 5193 } else { 5194 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5195 IsUnbounded = true; 5196 if (!e) { 5197 // Cannot convert to zero-sized. 5198 Result.setBad(BadConversionSequence::too_few_initializers, From, 5199 ToType); 5200 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5201 return Result; 5202 } 5203 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5204 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5205 ArrayType::Normal, 0); 5206 } 5207 } 5208 5209 Result.setStandard(); 5210 Result.Standard.setAsIdentityConversion(); 5211 Result.Standard.setFromType(InitTy); 5212 Result.Standard.setAllToTypes(InitTy); 5213 for (unsigned i = 0; i < e; ++i) { 5214 Expr *Init = From->getInit(i); 5215 ImplicitConversionSequence ICS = TryCopyInitialization( 5216 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5217 AllowObjCWritebackConversion); 5218 5219 // Keep the worse conversion seen so far. 5220 // FIXME: Sequences are not totally ordered, so 'worse' can be 5221 // ambiguous. CWG has been informed. 5222 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5223 Result) == 5224 ImplicitConversionSequence::Worse) { 5225 Result = ICS; 5226 // Bail as soon as we find something unconvertible. 5227 if (Result.isBad()) { 5228 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5229 return Result; 5230 } 5231 } 5232 } 5233 5234 // If we needed any implicit {} initialization, compare that now. 5235 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5236 // has been informed that this might not be the best thing. 5237 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5238 S, From->getEndLoc(), DfltElt, Result) == 5239 ImplicitConversionSequence::Worse) 5240 Result = DfltElt; 5241 // Record the type being initialized so that we may compare sequences 5242 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5243 return Result; 5244 } 5245 5246 // C++14 [over.ics.list]p4: 5247 // C++11 [over.ics.list]p3: 5248 // Otherwise, if the parameter is a non-aggregate class X and overload 5249 // resolution chooses a single best constructor [...] the implicit 5250 // conversion sequence is a user-defined conversion sequence. If multiple 5251 // constructors are viable but none is better than the others, the 5252 // implicit conversion sequence is a user-defined conversion sequence. 5253 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5254 // This function can deal with initializer lists. 5255 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5256 AllowedExplicit::None, 5257 InOverloadResolution, /*CStyle=*/false, 5258 AllowObjCWritebackConversion, 5259 /*AllowObjCConversionOnExplicit=*/false); 5260 } 5261 5262 // C++14 [over.ics.list]p5: 5263 // C++11 [over.ics.list]p4: 5264 // Otherwise, if the parameter has an aggregate type which can be 5265 // initialized from the initializer list [...] the implicit conversion 5266 // sequence is a user-defined conversion sequence. 5267 if (ToType->isAggregateType()) { 5268 // Type is an aggregate, argument is an init list. At this point it comes 5269 // down to checking whether the initialization works. 5270 // FIXME: Find out whether this parameter is consumed or not. 5271 InitializedEntity Entity = 5272 InitializedEntity::InitializeParameter(S.Context, ToType, 5273 /*Consumed=*/false); 5274 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5275 From)) { 5276 Result.setUserDefined(); 5277 Result.UserDefined.Before.setAsIdentityConversion(); 5278 // Initializer lists don't have a type. 5279 Result.UserDefined.Before.setFromType(QualType()); 5280 Result.UserDefined.Before.setAllToTypes(QualType()); 5281 5282 Result.UserDefined.After.setAsIdentityConversion(); 5283 Result.UserDefined.After.setFromType(ToType); 5284 Result.UserDefined.After.setAllToTypes(ToType); 5285 Result.UserDefined.ConversionFunction = nullptr; 5286 } 5287 return Result; 5288 } 5289 5290 // C++14 [over.ics.list]p6: 5291 // C++11 [over.ics.list]p5: 5292 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5293 if (ToType->isReferenceType()) { 5294 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5295 // mention initializer lists in any way. So we go by what list- 5296 // initialization would do and try to extrapolate from that. 5297 5298 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5299 5300 // If the initializer list has a single element that is reference-related 5301 // to the parameter type, we initialize the reference from that. 5302 if (From->getNumInits() == 1) { 5303 Expr *Init = From->getInit(0); 5304 5305 QualType T2 = Init->getType(); 5306 5307 // If the initializer is the address of an overloaded function, try 5308 // to resolve the overloaded function. If all goes well, T2 is the 5309 // type of the resulting function. 5310 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5311 DeclAccessPair Found; 5312 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5313 Init, ToType, false, Found)) 5314 T2 = Fn->getType(); 5315 } 5316 5317 // Compute some basic properties of the types and the initializer. 5318 Sema::ReferenceCompareResult RefRelationship = 5319 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5320 5321 if (RefRelationship >= Sema::Ref_Related) { 5322 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5323 SuppressUserConversions, 5324 /*AllowExplicit=*/false); 5325 } 5326 } 5327 5328 // Otherwise, we bind the reference to a temporary created from the 5329 // initializer list. 5330 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5331 InOverloadResolution, 5332 AllowObjCWritebackConversion); 5333 if (Result.isFailure()) 5334 return Result; 5335 assert(!Result.isEllipsis() && 5336 "Sub-initialization cannot result in ellipsis conversion."); 5337 5338 // Can we even bind to a temporary? 5339 if (ToType->isRValueReferenceType() || 5340 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5341 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5342 Result.UserDefined.After; 5343 SCS.ReferenceBinding = true; 5344 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5345 SCS.BindsToRvalue = true; 5346 SCS.BindsToFunctionLvalue = false; 5347 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5348 SCS.ObjCLifetimeConversionBinding = false; 5349 } else 5350 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5351 From, ToType); 5352 return Result; 5353 } 5354 5355 // C++14 [over.ics.list]p7: 5356 // C++11 [over.ics.list]p6: 5357 // Otherwise, if the parameter type is not a class: 5358 if (!ToType->isRecordType()) { 5359 // - if the initializer list has one element that is not itself an 5360 // initializer list, the implicit conversion sequence is the one 5361 // required to convert the element to the parameter type. 5362 unsigned NumInits = From->getNumInits(); 5363 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5364 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5365 SuppressUserConversions, 5366 InOverloadResolution, 5367 AllowObjCWritebackConversion); 5368 // - if the initializer list has no elements, the implicit conversion 5369 // sequence is the identity conversion. 5370 else if (NumInits == 0) { 5371 Result.setStandard(); 5372 Result.Standard.setAsIdentityConversion(); 5373 Result.Standard.setFromType(ToType); 5374 Result.Standard.setAllToTypes(ToType); 5375 } 5376 return Result; 5377 } 5378 5379 // C++14 [over.ics.list]p8: 5380 // C++11 [over.ics.list]p7: 5381 // In all cases other than those enumerated above, no conversion is possible 5382 return Result; 5383 } 5384 5385 /// TryCopyInitialization - Try to copy-initialize a value of type 5386 /// ToType from the expression From. Return the implicit conversion 5387 /// sequence required to pass this argument, which may be a bad 5388 /// conversion sequence (meaning that the argument cannot be passed to 5389 /// a parameter of this type). If @p SuppressUserConversions, then we 5390 /// do not permit any user-defined conversion sequences. 5391 static ImplicitConversionSequence 5392 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5393 bool SuppressUserConversions, 5394 bool InOverloadResolution, 5395 bool AllowObjCWritebackConversion, 5396 bool AllowExplicit) { 5397 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5398 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5399 InOverloadResolution,AllowObjCWritebackConversion); 5400 5401 if (ToType->isReferenceType()) 5402 return TryReferenceInit(S, From, ToType, 5403 /*FIXME:*/ From->getBeginLoc(), 5404 SuppressUserConversions, AllowExplicit); 5405 5406 return TryImplicitConversion(S, From, ToType, 5407 SuppressUserConversions, 5408 AllowedExplicit::None, 5409 InOverloadResolution, 5410 /*CStyle=*/false, 5411 AllowObjCWritebackConversion, 5412 /*AllowObjCConversionOnExplicit=*/false); 5413 } 5414 5415 static bool TryCopyInitialization(const CanQualType FromQTy, 5416 const CanQualType ToQTy, 5417 Sema &S, 5418 SourceLocation Loc, 5419 ExprValueKind FromVK) { 5420 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5421 ImplicitConversionSequence ICS = 5422 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5423 5424 return !ICS.isBad(); 5425 } 5426 5427 /// TryObjectArgumentInitialization - Try to initialize the object 5428 /// parameter of the given member function (@c Method) from the 5429 /// expression @p From. 5430 static ImplicitConversionSequence 5431 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5432 Expr::Classification FromClassification, 5433 CXXMethodDecl *Method, 5434 CXXRecordDecl *ActingContext) { 5435 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5436 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5437 // const volatile object. 5438 Qualifiers Quals = Method->getMethodQualifiers(); 5439 if (isa<CXXDestructorDecl>(Method)) { 5440 Quals.addConst(); 5441 Quals.addVolatile(); 5442 } 5443 5444 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5445 5446 // Set up the conversion sequence as a "bad" conversion, to allow us 5447 // to exit early. 5448 ImplicitConversionSequence ICS; 5449 5450 // We need to have an object of class type. 5451 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5452 FromType = PT->getPointeeType(); 5453 5454 // When we had a pointer, it's implicitly dereferenced, so we 5455 // better have an lvalue. 5456 assert(FromClassification.isLValue()); 5457 } 5458 5459 assert(FromType->isRecordType()); 5460 5461 // C++0x [over.match.funcs]p4: 5462 // For non-static member functions, the type of the implicit object 5463 // parameter is 5464 // 5465 // - "lvalue reference to cv X" for functions declared without a 5466 // ref-qualifier or with the & ref-qualifier 5467 // - "rvalue reference to cv X" for functions declared with the && 5468 // ref-qualifier 5469 // 5470 // where X is the class of which the function is a member and cv is the 5471 // cv-qualification on the member function declaration. 5472 // 5473 // However, when finding an implicit conversion sequence for the argument, we 5474 // are not allowed to perform user-defined conversions 5475 // (C++ [over.match.funcs]p5). We perform a simplified version of 5476 // reference binding here, that allows class rvalues to bind to 5477 // non-constant references. 5478 5479 // First check the qualifiers. 5480 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5481 if (ImplicitParamType.getCVRQualifiers() 5482 != FromTypeCanon.getLocalCVRQualifiers() && 5483 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5484 ICS.setBad(BadConversionSequence::bad_qualifiers, 5485 FromType, ImplicitParamType); 5486 return ICS; 5487 } 5488 5489 if (FromTypeCanon.hasAddressSpace()) { 5490 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5491 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5492 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5493 ICS.setBad(BadConversionSequence::bad_qualifiers, 5494 FromType, ImplicitParamType); 5495 return ICS; 5496 } 5497 } 5498 5499 // Check that we have either the same type or a derived type. It 5500 // affects the conversion rank. 5501 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5502 ImplicitConversionKind SecondKind; 5503 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5504 SecondKind = ICK_Identity; 5505 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5506 SecondKind = ICK_Derived_To_Base; 5507 else { 5508 ICS.setBad(BadConversionSequence::unrelated_class, 5509 FromType, ImplicitParamType); 5510 return ICS; 5511 } 5512 5513 // Check the ref-qualifier. 5514 switch (Method->getRefQualifier()) { 5515 case RQ_None: 5516 // Do nothing; we don't care about lvalueness or rvalueness. 5517 break; 5518 5519 case RQ_LValue: 5520 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5521 // non-const lvalue reference cannot bind to an rvalue 5522 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5523 ImplicitParamType); 5524 return ICS; 5525 } 5526 break; 5527 5528 case RQ_RValue: 5529 if (!FromClassification.isRValue()) { 5530 // rvalue reference cannot bind to an lvalue 5531 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5532 ImplicitParamType); 5533 return ICS; 5534 } 5535 break; 5536 } 5537 5538 // Success. Mark this as a reference binding. 5539 ICS.setStandard(); 5540 ICS.Standard.setAsIdentityConversion(); 5541 ICS.Standard.Second = SecondKind; 5542 ICS.Standard.setFromType(FromType); 5543 ICS.Standard.setAllToTypes(ImplicitParamType); 5544 ICS.Standard.ReferenceBinding = true; 5545 ICS.Standard.DirectBinding = true; 5546 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5547 ICS.Standard.BindsToFunctionLvalue = false; 5548 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5549 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5550 = (Method->getRefQualifier() == RQ_None); 5551 return ICS; 5552 } 5553 5554 /// PerformObjectArgumentInitialization - Perform initialization of 5555 /// the implicit object parameter for the given Method with the given 5556 /// expression. 5557 ExprResult 5558 Sema::PerformObjectArgumentInitialization(Expr *From, 5559 NestedNameSpecifier *Qualifier, 5560 NamedDecl *FoundDecl, 5561 CXXMethodDecl *Method) { 5562 QualType FromRecordType, DestType; 5563 QualType ImplicitParamRecordType = 5564 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5565 5566 Expr::Classification FromClassification; 5567 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5568 FromRecordType = PT->getPointeeType(); 5569 DestType = Method->getThisType(); 5570 FromClassification = Expr::Classification::makeSimpleLValue(); 5571 } else { 5572 FromRecordType = From->getType(); 5573 DestType = ImplicitParamRecordType; 5574 FromClassification = From->Classify(Context); 5575 5576 // When performing member access on a prvalue, materialize a temporary. 5577 if (From->isPRValue()) { 5578 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5579 Method->getRefQualifier() != 5580 RefQualifierKind::RQ_RValue); 5581 } 5582 } 5583 5584 // Note that we always use the true parent context when performing 5585 // the actual argument initialization. 5586 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5587 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5588 Method->getParent()); 5589 if (ICS.isBad()) { 5590 switch (ICS.Bad.Kind) { 5591 case BadConversionSequence::bad_qualifiers: { 5592 Qualifiers FromQs = FromRecordType.getQualifiers(); 5593 Qualifiers ToQs = DestType.getQualifiers(); 5594 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5595 if (CVR) { 5596 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5597 << Method->getDeclName() << FromRecordType << (CVR - 1) 5598 << From->getSourceRange(); 5599 Diag(Method->getLocation(), diag::note_previous_decl) 5600 << Method->getDeclName(); 5601 return ExprError(); 5602 } 5603 break; 5604 } 5605 5606 case BadConversionSequence::lvalue_ref_to_rvalue: 5607 case BadConversionSequence::rvalue_ref_to_lvalue: { 5608 bool IsRValueQualified = 5609 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5610 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5611 << Method->getDeclName() << FromClassification.isRValue() 5612 << IsRValueQualified; 5613 Diag(Method->getLocation(), diag::note_previous_decl) 5614 << Method->getDeclName(); 5615 return ExprError(); 5616 } 5617 5618 case BadConversionSequence::no_conversion: 5619 case BadConversionSequence::unrelated_class: 5620 break; 5621 5622 case BadConversionSequence::too_few_initializers: 5623 case BadConversionSequence::too_many_initializers: 5624 llvm_unreachable("Lists are not objects"); 5625 } 5626 5627 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5628 << ImplicitParamRecordType << FromRecordType 5629 << From->getSourceRange(); 5630 } 5631 5632 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5633 ExprResult FromRes = 5634 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5635 if (FromRes.isInvalid()) 5636 return ExprError(); 5637 From = FromRes.get(); 5638 } 5639 5640 if (!Context.hasSameType(From->getType(), DestType)) { 5641 CastKind CK; 5642 QualType PteeTy = DestType->getPointeeType(); 5643 LangAS DestAS = 5644 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5645 if (FromRecordType.getAddressSpace() != DestAS) 5646 CK = CK_AddressSpaceConversion; 5647 else 5648 CK = CK_NoOp; 5649 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5650 } 5651 return From; 5652 } 5653 5654 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5655 /// expression From to bool (C++0x [conv]p3). 5656 static ImplicitConversionSequence 5657 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5658 // C++ [dcl.init]/17.8: 5659 // - Otherwise, if the initialization is direct-initialization, the source 5660 // type is std::nullptr_t, and the destination type is bool, the initial 5661 // value of the object being initialized is false. 5662 if (From->getType()->isNullPtrType()) 5663 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5664 S.Context.BoolTy, 5665 From->isGLValue()); 5666 5667 // All other direct-initialization of bool is equivalent to an implicit 5668 // conversion to bool in which explicit conversions are permitted. 5669 return TryImplicitConversion(S, From, S.Context.BoolTy, 5670 /*SuppressUserConversions=*/false, 5671 AllowedExplicit::Conversions, 5672 /*InOverloadResolution=*/false, 5673 /*CStyle=*/false, 5674 /*AllowObjCWritebackConversion=*/false, 5675 /*AllowObjCConversionOnExplicit=*/false); 5676 } 5677 5678 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5679 /// of the expression From to bool (C++0x [conv]p3). 5680 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5681 if (checkPlaceholderForOverload(*this, From)) 5682 return ExprError(); 5683 5684 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5685 if (!ICS.isBad()) 5686 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5687 5688 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5689 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5690 << From->getType() << From->getSourceRange(); 5691 return ExprError(); 5692 } 5693 5694 /// Check that the specified conversion is permitted in a converted constant 5695 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5696 /// is acceptable. 5697 static bool CheckConvertedConstantConversions(Sema &S, 5698 StandardConversionSequence &SCS) { 5699 // Since we know that the target type is an integral or unscoped enumeration 5700 // type, most conversion kinds are impossible. All possible First and Third 5701 // conversions are fine. 5702 switch (SCS.Second) { 5703 case ICK_Identity: 5704 case ICK_Integral_Promotion: 5705 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5706 case ICK_Zero_Queue_Conversion: 5707 return true; 5708 5709 case ICK_Boolean_Conversion: 5710 // Conversion from an integral or unscoped enumeration type to bool is 5711 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5712 // conversion, so we allow it in a converted constant expression. 5713 // 5714 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5715 // a lot of popular code. We should at least add a warning for this 5716 // (non-conforming) extension. 5717 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5718 SCS.getToType(2)->isBooleanType(); 5719 5720 case ICK_Pointer_Conversion: 5721 case ICK_Pointer_Member: 5722 // C++1z: null pointer conversions and null member pointer conversions are 5723 // only permitted if the source type is std::nullptr_t. 5724 return SCS.getFromType()->isNullPtrType(); 5725 5726 case ICK_Floating_Promotion: 5727 case ICK_Complex_Promotion: 5728 case ICK_Floating_Conversion: 5729 case ICK_Complex_Conversion: 5730 case ICK_Floating_Integral: 5731 case ICK_Compatible_Conversion: 5732 case ICK_Derived_To_Base: 5733 case ICK_Vector_Conversion: 5734 case ICK_SVE_Vector_Conversion: 5735 case ICK_Vector_Splat: 5736 case ICK_Complex_Real: 5737 case ICK_Block_Pointer_Conversion: 5738 case ICK_TransparentUnionConversion: 5739 case ICK_Writeback_Conversion: 5740 case ICK_Zero_Event_Conversion: 5741 case ICK_C_Only_Conversion: 5742 case ICK_Incompatible_Pointer_Conversion: 5743 return false; 5744 5745 case ICK_Lvalue_To_Rvalue: 5746 case ICK_Array_To_Pointer: 5747 case ICK_Function_To_Pointer: 5748 llvm_unreachable("found a first conversion kind in Second"); 5749 5750 case ICK_Function_Conversion: 5751 case ICK_Qualification: 5752 llvm_unreachable("found a third conversion kind in Second"); 5753 5754 case ICK_Num_Conversion_Kinds: 5755 break; 5756 } 5757 5758 llvm_unreachable("unknown conversion kind"); 5759 } 5760 5761 /// CheckConvertedConstantExpression - Check that the expression From is a 5762 /// converted constant expression of type T, perform the conversion and produce 5763 /// the converted expression, per C++11 [expr.const]p3. 5764 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5765 QualType T, APValue &Value, 5766 Sema::CCEKind CCE, 5767 bool RequireInt, 5768 NamedDecl *Dest) { 5769 assert(S.getLangOpts().CPlusPlus11 && 5770 "converted constant expression outside C++11"); 5771 5772 if (checkPlaceholderForOverload(S, From)) 5773 return ExprError(); 5774 5775 // C++1z [expr.const]p3: 5776 // A converted constant expression of type T is an expression, 5777 // implicitly converted to type T, where the converted 5778 // expression is a constant expression and the implicit conversion 5779 // sequence contains only [... list of conversions ...]. 5780 ImplicitConversionSequence ICS = 5781 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 5782 ? TryContextuallyConvertToBool(S, From) 5783 : TryCopyInitialization(S, From, T, 5784 /*SuppressUserConversions=*/false, 5785 /*InOverloadResolution=*/false, 5786 /*AllowObjCWritebackConversion=*/false, 5787 /*AllowExplicit=*/false); 5788 StandardConversionSequence *SCS = nullptr; 5789 switch (ICS.getKind()) { 5790 case ImplicitConversionSequence::StandardConversion: 5791 SCS = &ICS.Standard; 5792 break; 5793 case ImplicitConversionSequence::UserDefinedConversion: 5794 if (T->isRecordType()) 5795 SCS = &ICS.UserDefined.Before; 5796 else 5797 SCS = &ICS.UserDefined.After; 5798 break; 5799 case ImplicitConversionSequence::AmbiguousConversion: 5800 case ImplicitConversionSequence::BadConversion: 5801 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5802 return S.Diag(From->getBeginLoc(), 5803 diag::err_typecheck_converted_constant_expression) 5804 << From->getType() << From->getSourceRange() << T; 5805 return ExprError(); 5806 5807 case ImplicitConversionSequence::EllipsisConversion: 5808 llvm_unreachable("ellipsis conversion in converted constant expression"); 5809 } 5810 5811 // Check that we would only use permitted conversions. 5812 if (!CheckConvertedConstantConversions(S, *SCS)) { 5813 return S.Diag(From->getBeginLoc(), 5814 diag::err_typecheck_converted_constant_expression_disallowed) 5815 << From->getType() << From->getSourceRange() << T; 5816 } 5817 // [...] and where the reference binding (if any) binds directly. 5818 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5819 return S.Diag(From->getBeginLoc(), 5820 diag::err_typecheck_converted_constant_expression_indirect) 5821 << From->getType() << From->getSourceRange() << T; 5822 } 5823 5824 // Usually we can simply apply the ImplicitConversionSequence we formed 5825 // earlier, but that's not guaranteed to work when initializing an object of 5826 // class type. 5827 ExprResult Result; 5828 if (T->isRecordType()) { 5829 assert(CCE == Sema::CCEK_TemplateArg && 5830 "unexpected class type converted constant expr"); 5831 Result = S.PerformCopyInitialization( 5832 InitializedEntity::InitializeTemplateParameter( 5833 T, cast<NonTypeTemplateParmDecl>(Dest)), 5834 SourceLocation(), From); 5835 } else { 5836 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5837 } 5838 if (Result.isInvalid()) 5839 return Result; 5840 5841 // C++2a [intro.execution]p5: 5842 // A full-expression is [...] a constant-expression [...] 5843 Result = 5844 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5845 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5846 if (Result.isInvalid()) 5847 return Result; 5848 5849 // Check for a narrowing implicit conversion. 5850 bool ReturnPreNarrowingValue = false; 5851 APValue PreNarrowingValue; 5852 QualType PreNarrowingType; 5853 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5854 PreNarrowingType)) { 5855 case NK_Dependent_Narrowing: 5856 // Implicit conversion to a narrower type, but the expression is 5857 // value-dependent so we can't tell whether it's actually narrowing. 5858 case NK_Variable_Narrowing: 5859 // Implicit conversion to a narrower type, and the value is not a constant 5860 // expression. We'll diagnose this in a moment. 5861 case NK_Not_Narrowing: 5862 break; 5863 5864 case NK_Constant_Narrowing: 5865 if (CCE == Sema::CCEK_ArrayBound && 5866 PreNarrowingType->isIntegralOrEnumerationType() && 5867 PreNarrowingValue.isInt()) { 5868 // Don't diagnose array bound narrowing here; we produce more precise 5869 // errors by allowing the un-narrowed value through. 5870 ReturnPreNarrowingValue = true; 5871 break; 5872 } 5873 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5874 << CCE << /*Constant*/ 1 5875 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5876 break; 5877 5878 case NK_Type_Narrowing: 5879 // FIXME: It would be better to diagnose that the expression is not a 5880 // constant expression. 5881 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5882 << CCE << /*Constant*/ 0 << From->getType() << T; 5883 break; 5884 } 5885 5886 if (Result.get()->isValueDependent()) { 5887 Value = APValue(); 5888 return Result; 5889 } 5890 5891 // Check the expression is a constant expression. 5892 SmallVector<PartialDiagnosticAt, 8> Notes; 5893 Expr::EvalResult Eval; 5894 Eval.Diag = &Notes; 5895 5896 ConstantExprKind Kind; 5897 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5898 Kind = ConstantExprKind::ClassTemplateArgument; 5899 else if (CCE == Sema::CCEK_TemplateArg) 5900 Kind = ConstantExprKind::NonClassTemplateArgument; 5901 else 5902 Kind = ConstantExprKind::Normal; 5903 5904 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5905 (RequireInt && !Eval.Val.isInt())) { 5906 // The expression can't be folded, so we can't keep it at this position in 5907 // the AST. 5908 Result = ExprError(); 5909 } else { 5910 Value = Eval.Val; 5911 5912 if (Notes.empty()) { 5913 // It's a constant expression. 5914 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5915 if (ReturnPreNarrowingValue) 5916 Value = std::move(PreNarrowingValue); 5917 return E; 5918 } 5919 } 5920 5921 // It's not a constant expression. Produce an appropriate diagnostic. 5922 if (Notes.size() == 1 && 5923 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5924 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5925 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5926 diag::note_constexpr_invalid_template_arg) { 5927 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5928 for (unsigned I = 0; I < Notes.size(); ++I) 5929 S.Diag(Notes[I].first, Notes[I].second); 5930 } else { 5931 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5932 << CCE << From->getSourceRange(); 5933 for (unsigned I = 0; I < Notes.size(); ++I) 5934 S.Diag(Notes[I].first, Notes[I].second); 5935 } 5936 return ExprError(); 5937 } 5938 5939 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5940 APValue &Value, CCEKind CCE, 5941 NamedDecl *Dest) { 5942 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5943 Dest); 5944 } 5945 5946 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5947 llvm::APSInt &Value, 5948 CCEKind CCE) { 5949 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5950 5951 APValue V; 5952 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5953 /*Dest=*/nullptr); 5954 if (!R.isInvalid() && !R.get()->isValueDependent()) 5955 Value = V.getInt(); 5956 return R; 5957 } 5958 5959 5960 /// dropPointerConversions - If the given standard conversion sequence 5961 /// involves any pointer conversions, remove them. This may change 5962 /// the result type of the conversion sequence. 5963 static void dropPointerConversion(StandardConversionSequence &SCS) { 5964 if (SCS.Second == ICK_Pointer_Conversion) { 5965 SCS.Second = ICK_Identity; 5966 SCS.Third = ICK_Identity; 5967 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5968 } 5969 } 5970 5971 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5972 /// convert the expression From to an Objective-C pointer type. 5973 static ImplicitConversionSequence 5974 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5975 // Do an implicit conversion to 'id'. 5976 QualType Ty = S.Context.getObjCIdType(); 5977 ImplicitConversionSequence ICS 5978 = TryImplicitConversion(S, From, Ty, 5979 // FIXME: Are these flags correct? 5980 /*SuppressUserConversions=*/false, 5981 AllowedExplicit::Conversions, 5982 /*InOverloadResolution=*/false, 5983 /*CStyle=*/false, 5984 /*AllowObjCWritebackConversion=*/false, 5985 /*AllowObjCConversionOnExplicit=*/true); 5986 5987 // Strip off any final conversions to 'id'. 5988 switch (ICS.getKind()) { 5989 case ImplicitConversionSequence::BadConversion: 5990 case ImplicitConversionSequence::AmbiguousConversion: 5991 case ImplicitConversionSequence::EllipsisConversion: 5992 break; 5993 5994 case ImplicitConversionSequence::UserDefinedConversion: 5995 dropPointerConversion(ICS.UserDefined.After); 5996 break; 5997 5998 case ImplicitConversionSequence::StandardConversion: 5999 dropPointerConversion(ICS.Standard); 6000 break; 6001 } 6002 6003 return ICS; 6004 } 6005 6006 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 6007 /// conversion of the expression From to an Objective-C pointer type. 6008 /// Returns a valid but null ExprResult if no conversion sequence exists. 6009 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 6010 if (checkPlaceholderForOverload(*this, From)) 6011 return ExprError(); 6012 6013 QualType Ty = Context.getObjCIdType(); 6014 ImplicitConversionSequence ICS = 6015 TryContextuallyConvertToObjCPointer(*this, From); 6016 if (!ICS.isBad()) 6017 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 6018 return ExprResult(); 6019 } 6020 6021 /// Determine whether the provided type is an integral type, or an enumeration 6022 /// type of a permitted flavor. 6023 bool Sema::ICEConvertDiagnoser::match(QualType T) { 6024 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 6025 : T->isIntegralOrUnscopedEnumerationType(); 6026 } 6027 6028 static ExprResult 6029 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 6030 Sema::ContextualImplicitConverter &Converter, 6031 QualType T, UnresolvedSetImpl &ViableConversions) { 6032 6033 if (Converter.Suppress) 6034 return ExprError(); 6035 6036 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 6037 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6038 CXXConversionDecl *Conv = 6039 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 6040 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 6041 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 6042 } 6043 return From; 6044 } 6045 6046 static bool 6047 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6048 Sema::ContextualImplicitConverter &Converter, 6049 QualType T, bool HadMultipleCandidates, 6050 UnresolvedSetImpl &ExplicitConversions) { 6051 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 6052 DeclAccessPair Found = ExplicitConversions[0]; 6053 CXXConversionDecl *Conversion = 6054 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6055 6056 // The user probably meant to invoke the given explicit 6057 // conversion; use it. 6058 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 6059 std::string TypeStr; 6060 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 6061 6062 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 6063 << FixItHint::CreateInsertion(From->getBeginLoc(), 6064 "static_cast<" + TypeStr + ">(") 6065 << FixItHint::CreateInsertion( 6066 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 6067 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 6068 6069 // If we aren't in a SFINAE context, build a call to the 6070 // explicit conversion function. 6071 if (SemaRef.isSFINAEContext()) 6072 return true; 6073 6074 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6075 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6076 HadMultipleCandidates); 6077 if (Result.isInvalid()) 6078 return true; 6079 // Record usage of conversion in an implicit cast. 6080 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6081 CK_UserDefinedConversion, Result.get(), 6082 nullptr, Result.get()->getValueKind(), 6083 SemaRef.CurFPFeatureOverrides()); 6084 } 6085 return false; 6086 } 6087 6088 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6089 Sema::ContextualImplicitConverter &Converter, 6090 QualType T, bool HadMultipleCandidates, 6091 DeclAccessPair &Found) { 6092 CXXConversionDecl *Conversion = 6093 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6094 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6095 6096 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6097 if (!Converter.SuppressConversion) { 6098 if (SemaRef.isSFINAEContext()) 6099 return true; 6100 6101 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6102 << From->getSourceRange(); 6103 } 6104 6105 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6106 HadMultipleCandidates); 6107 if (Result.isInvalid()) 6108 return true; 6109 // Record usage of conversion in an implicit cast. 6110 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6111 CK_UserDefinedConversion, Result.get(), 6112 nullptr, Result.get()->getValueKind(), 6113 SemaRef.CurFPFeatureOverrides()); 6114 return false; 6115 } 6116 6117 static ExprResult finishContextualImplicitConversion( 6118 Sema &SemaRef, SourceLocation Loc, Expr *From, 6119 Sema::ContextualImplicitConverter &Converter) { 6120 if (!Converter.match(From->getType()) && !Converter.Suppress) 6121 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6122 << From->getSourceRange(); 6123 6124 return SemaRef.DefaultLvalueConversion(From); 6125 } 6126 6127 static void 6128 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6129 UnresolvedSetImpl &ViableConversions, 6130 OverloadCandidateSet &CandidateSet) { 6131 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6132 DeclAccessPair FoundDecl = ViableConversions[I]; 6133 NamedDecl *D = FoundDecl.getDecl(); 6134 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6135 if (isa<UsingShadowDecl>(D)) 6136 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6137 6138 CXXConversionDecl *Conv; 6139 FunctionTemplateDecl *ConvTemplate; 6140 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6141 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6142 else 6143 Conv = cast<CXXConversionDecl>(D); 6144 6145 if (ConvTemplate) 6146 SemaRef.AddTemplateConversionCandidate( 6147 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6148 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6149 else 6150 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6151 ToType, CandidateSet, 6152 /*AllowObjCConversionOnExplicit=*/false, 6153 /*AllowExplicit*/ true); 6154 } 6155 } 6156 6157 /// Attempt to convert the given expression to a type which is accepted 6158 /// by the given converter. 6159 /// 6160 /// This routine will attempt to convert an expression of class type to a 6161 /// type accepted by the specified converter. In C++11 and before, the class 6162 /// must have a single non-explicit conversion function converting to a matching 6163 /// type. In C++1y, there can be multiple such conversion functions, but only 6164 /// one target type. 6165 /// 6166 /// \param Loc The source location of the construct that requires the 6167 /// conversion. 6168 /// 6169 /// \param From The expression we're converting from. 6170 /// 6171 /// \param Converter Used to control and diagnose the conversion process. 6172 /// 6173 /// \returns The expression, converted to an integral or enumeration type if 6174 /// successful. 6175 ExprResult Sema::PerformContextualImplicitConversion( 6176 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6177 // We can't perform any more checking for type-dependent expressions. 6178 if (From->isTypeDependent()) 6179 return From; 6180 6181 // Process placeholders immediately. 6182 if (From->hasPlaceholderType()) { 6183 ExprResult result = CheckPlaceholderExpr(From); 6184 if (result.isInvalid()) 6185 return result; 6186 From = result.get(); 6187 } 6188 6189 // If the expression already has a matching type, we're golden. 6190 QualType T = From->getType(); 6191 if (Converter.match(T)) 6192 return DefaultLvalueConversion(From); 6193 6194 // FIXME: Check for missing '()' if T is a function type? 6195 6196 // We can only perform contextual implicit conversions on objects of class 6197 // type. 6198 const RecordType *RecordTy = T->getAs<RecordType>(); 6199 if (!RecordTy || !getLangOpts().CPlusPlus) { 6200 if (!Converter.Suppress) 6201 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6202 return From; 6203 } 6204 6205 // We must have a complete class type. 6206 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6207 ContextualImplicitConverter &Converter; 6208 Expr *From; 6209 6210 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6211 : Converter(Converter), From(From) {} 6212 6213 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6214 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6215 } 6216 } IncompleteDiagnoser(Converter, From); 6217 6218 if (Converter.Suppress ? !isCompleteType(Loc, T) 6219 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6220 return From; 6221 6222 // Look for a conversion to an integral or enumeration type. 6223 UnresolvedSet<4> 6224 ViableConversions; // These are *potentially* viable in C++1y. 6225 UnresolvedSet<4> ExplicitConversions; 6226 const auto &Conversions = 6227 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6228 6229 bool HadMultipleCandidates = 6230 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6231 6232 // To check that there is only one target type, in C++1y: 6233 QualType ToType; 6234 bool HasUniqueTargetType = true; 6235 6236 // Collect explicit or viable (potentially in C++1y) conversions. 6237 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6238 NamedDecl *D = (*I)->getUnderlyingDecl(); 6239 CXXConversionDecl *Conversion; 6240 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6241 if (ConvTemplate) { 6242 if (getLangOpts().CPlusPlus14) 6243 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6244 else 6245 continue; // C++11 does not consider conversion operator templates(?). 6246 } else 6247 Conversion = cast<CXXConversionDecl>(D); 6248 6249 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6250 "Conversion operator templates are considered potentially " 6251 "viable in C++1y"); 6252 6253 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6254 if (Converter.match(CurToType) || ConvTemplate) { 6255 6256 if (Conversion->isExplicit()) { 6257 // FIXME: For C++1y, do we need this restriction? 6258 // cf. diagnoseNoViableConversion() 6259 if (!ConvTemplate) 6260 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6261 } else { 6262 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6263 if (ToType.isNull()) 6264 ToType = CurToType.getUnqualifiedType(); 6265 else if (HasUniqueTargetType && 6266 (CurToType.getUnqualifiedType() != ToType)) 6267 HasUniqueTargetType = false; 6268 } 6269 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6270 } 6271 } 6272 } 6273 6274 if (getLangOpts().CPlusPlus14) { 6275 // C++1y [conv]p6: 6276 // ... An expression e of class type E appearing in such a context 6277 // is said to be contextually implicitly converted to a specified 6278 // type T and is well-formed if and only if e can be implicitly 6279 // converted to a type T that is determined as follows: E is searched 6280 // for conversion functions whose return type is cv T or reference to 6281 // cv T such that T is allowed by the context. There shall be 6282 // exactly one such T. 6283 6284 // If no unique T is found: 6285 if (ToType.isNull()) { 6286 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6287 HadMultipleCandidates, 6288 ExplicitConversions)) 6289 return ExprError(); 6290 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6291 } 6292 6293 // If more than one unique Ts are found: 6294 if (!HasUniqueTargetType) 6295 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6296 ViableConversions); 6297 6298 // If one unique T is found: 6299 // First, build a candidate set from the previously recorded 6300 // potentially viable conversions. 6301 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6302 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6303 CandidateSet); 6304 6305 // Then, perform overload resolution over the candidate set. 6306 OverloadCandidateSet::iterator Best; 6307 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6308 case OR_Success: { 6309 // Apply this conversion. 6310 DeclAccessPair Found = 6311 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6312 if (recordConversion(*this, Loc, From, Converter, T, 6313 HadMultipleCandidates, Found)) 6314 return ExprError(); 6315 break; 6316 } 6317 case OR_Ambiguous: 6318 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6319 ViableConversions); 6320 case OR_No_Viable_Function: 6321 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6322 HadMultipleCandidates, 6323 ExplicitConversions)) 6324 return ExprError(); 6325 LLVM_FALLTHROUGH; 6326 case OR_Deleted: 6327 // We'll complain below about a non-integral condition type. 6328 break; 6329 } 6330 } else { 6331 switch (ViableConversions.size()) { 6332 case 0: { 6333 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6334 HadMultipleCandidates, 6335 ExplicitConversions)) 6336 return ExprError(); 6337 6338 // We'll complain below about a non-integral condition type. 6339 break; 6340 } 6341 case 1: { 6342 // Apply this conversion. 6343 DeclAccessPair Found = ViableConversions[0]; 6344 if (recordConversion(*this, Loc, From, Converter, T, 6345 HadMultipleCandidates, Found)) 6346 return ExprError(); 6347 break; 6348 } 6349 default: 6350 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6351 ViableConversions); 6352 } 6353 } 6354 6355 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6356 } 6357 6358 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6359 /// an acceptable non-member overloaded operator for a call whose 6360 /// arguments have types T1 (and, if non-empty, T2). This routine 6361 /// implements the check in C++ [over.match.oper]p3b2 concerning 6362 /// enumeration types. 6363 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6364 FunctionDecl *Fn, 6365 ArrayRef<Expr *> Args) { 6366 QualType T1 = Args[0]->getType(); 6367 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6368 6369 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6370 return true; 6371 6372 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6373 return true; 6374 6375 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6376 if (Proto->getNumParams() < 1) 6377 return false; 6378 6379 if (T1->isEnumeralType()) { 6380 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6381 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6382 return true; 6383 } 6384 6385 if (Proto->getNumParams() < 2) 6386 return false; 6387 6388 if (!T2.isNull() && T2->isEnumeralType()) { 6389 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6390 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6391 return true; 6392 } 6393 6394 return false; 6395 } 6396 6397 /// AddOverloadCandidate - Adds the given function to the set of 6398 /// candidate functions, using the given function call arguments. If 6399 /// @p SuppressUserConversions, then don't allow user-defined 6400 /// conversions via constructors or conversion operators. 6401 /// 6402 /// \param PartialOverloading true if we are performing "partial" overloading 6403 /// based on an incomplete set of function arguments. This feature is used by 6404 /// code completion. 6405 void Sema::AddOverloadCandidate( 6406 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6407 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6408 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6409 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6410 OverloadCandidateParamOrder PO) { 6411 const FunctionProtoType *Proto 6412 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6413 assert(Proto && "Functions without a prototype cannot be overloaded"); 6414 assert(!Function->getDescribedFunctionTemplate() && 6415 "Use AddTemplateOverloadCandidate for function templates"); 6416 6417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6418 if (!isa<CXXConstructorDecl>(Method)) { 6419 // If we get here, it's because we're calling a member function 6420 // that is named without a member access expression (e.g., 6421 // "this->f") that was either written explicitly or created 6422 // implicitly. This can happen with a qualified call to a member 6423 // function, e.g., X::f(). We use an empty type for the implied 6424 // object argument (C++ [over.call.func]p3), and the acting context 6425 // is irrelevant. 6426 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6427 Expr::Classification::makeSimpleLValue(), Args, 6428 CandidateSet, SuppressUserConversions, 6429 PartialOverloading, EarlyConversions, PO); 6430 return; 6431 } 6432 // We treat a constructor like a non-member function, since its object 6433 // argument doesn't participate in overload resolution. 6434 } 6435 6436 if (!CandidateSet.isNewCandidate(Function, PO)) 6437 return; 6438 6439 // C++11 [class.copy]p11: [DR1402] 6440 // A defaulted move constructor that is defined as deleted is ignored by 6441 // overload resolution. 6442 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6443 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6444 Constructor->isMoveConstructor()) 6445 return; 6446 6447 // Overload resolution is always an unevaluated context. 6448 EnterExpressionEvaluationContext Unevaluated( 6449 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6450 6451 // C++ [over.match.oper]p3: 6452 // if no operand has a class type, only those non-member functions in the 6453 // lookup set that have a first parameter of type T1 or "reference to 6454 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6455 // is a right operand) a second parameter of type T2 or "reference to 6456 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6457 // candidate functions. 6458 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6459 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6460 return; 6461 6462 // Add this candidate 6463 OverloadCandidate &Candidate = 6464 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6465 Candidate.FoundDecl = FoundDecl; 6466 Candidate.Function = Function; 6467 Candidate.Viable = true; 6468 Candidate.RewriteKind = 6469 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6470 Candidate.IsSurrogate = false; 6471 Candidate.IsADLCandidate = IsADLCandidate; 6472 Candidate.IgnoreObjectArgument = false; 6473 Candidate.ExplicitCallArguments = Args.size(); 6474 6475 // Explicit functions are not actually candidates at all if we're not 6476 // allowing them in this context, but keep them around so we can point 6477 // to them in diagnostics. 6478 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6479 Candidate.Viable = false; 6480 Candidate.FailureKind = ovl_fail_explicit; 6481 return; 6482 } 6483 6484 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6485 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6486 Candidate.Viable = false; 6487 Candidate.FailureKind = ovl_non_default_multiversion_function; 6488 return; 6489 } 6490 6491 if (Constructor) { 6492 // C++ [class.copy]p3: 6493 // A member function template is never instantiated to perform the copy 6494 // of a class object to an object of its class type. 6495 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6496 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6497 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6498 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6499 ClassType))) { 6500 Candidate.Viable = false; 6501 Candidate.FailureKind = ovl_fail_illegal_constructor; 6502 return; 6503 } 6504 6505 // C++ [over.match.funcs]p8: (proposed DR resolution) 6506 // A constructor inherited from class type C that has a first parameter 6507 // of type "reference to P" (including such a constructor instantiated 6508 // from a template) is excluded from the set of candidate functions when 6509 // constructing an object of type cv D if the argument list has exactly 6510 // one argument and D is reference-related to P and P is reference-related 6511 // to C. 6512 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6513 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6514 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6515 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6516 QualType C = Context.getRecordType(Constructor->getParent()); 6517 QualType D = Context.getRecordType(Shadow->getParent()); 6518 SourceLocation Loc = Args.front()->getExprLoc(); 6519 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6520 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6521 Candidate.Viable = false; 6522 Candidate.FailureKind = ovl_fail_inhctor_slice; 6523 return; 6524 } 6525 } 6526 6527 // Check that the constructor is capable of constructing an object in the 6528 // destination address space. 6529 if (!Qualifiers::isAddressSpaceSupersetOf( 6530 Constructor->getMethodQualifiers().getAddressSpace(), 6531 CandidateSet.getDestAS())) { 6532 Candidate.Viable = false; 6533 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6534 } 6535 } 6536 6537 unsigned NumParams = Proto->getNumParams(); 6538 6539 // (C++ 13.3.2p2): A candidate function having fewer than m 6540 // parameters is viable only if it has an ellipsis in its parameter 6541 // list (8.3.5). 6542 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6543 !Proto->isVariadic() && 6544 shouldEnforceArgLimit(PartialOverloading, Function)) { 6545 Candidate.Viable = false; 6546 Candidate.FailureKind = ovl_fail_too_many_arguments; 6547 return; 6548 } 6549 6550 // (C++ 13.3.2p2): A candidate function having more than m parameters 6551 // is viable only if the (m+1)st parameter has a default argument 6552 // (8.3.6). For the purposes of overload resolution, the 6553 // parameter list is truncated on the right, so that there are 6554 // exactly m parameters. 6555 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6556 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6557 // Not enough arguments. 6558 Candidate.Viable = false; 6559 Candidate.FailureKind = ovl_fail_too_few_arguments; 6560 return; 6561 } 6562 6563 // (CUDA B.1): Check for invalid calls between targets. 6564 if (getLangOpts().CUDA) 6565 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) 6566 // Skip the check for callers that are implicit members, because in this 6567 // case we may not yet know what the member's target is; the target is 6568 // inferred for the member automatically, based on the bases and fields of 6569 // the class. 6570 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6571 Candidate.Viable = false; 6572 Candidate.FailureKind = ovl_fail_bad_target; 6573 return; 6574 } 6575 6576 if (Function->getTrailingRequiresClause()) { 6577 ConstraintSatisfaction Satisfaction; 6578 if (CheckFunctionConstraints(Function, Satisfaction) || 6579 !Satisfaction.IsSatisfied) { 6580 Candidate.Viable = false; 6581 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6582 return; 6583 } 6584 } 6585 6586 // Determine the implicit conversion sequences for each of the 6587 // arguments. 6588 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6589 unsigned ConvIdx = 6590 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6591 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6592 // We already formed a conversion sequence for this parameter during 6593 // template argument deduction. 6594 } else if (ArgIdx < NumParams) { 6595 // (C++ 13.3.2p3): for F to be a viable function, there shall 6596 // exist for each argument an implicit conversion sequence 6597 // (13.3.3.1) that converts that argument to the corresponding 6598 // parameter of F. 6599 QualType ParamType = Proto->getParamType(ArgIdx); 6600 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6601 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6602 /*InOverloadResolution=*/true, 6603 /*AllowObjCWritebackConversion=*/ 6604 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6605 if (Candidate.Conversions[ConvIdx].isBad()) { 6606 Candidate.Viable = false; 6607 Candidate.FailureKind = ovl_fail_bad_conversion; 6608 return; 6609 } 6610 } else { 6611 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6612 // argument for which there is no corresponding parameter is 6613 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6614 Candidate.Conversions[ConvIdx].setEllipsis(); 6615 } 6616 } 6617 6618 if (EnableIfAttr *FailedAttr = 6619 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6620 Candidate.Viable = false; 6621 Candidate.FailureKind = ovl_fail_enable_if; 6622 Candidate.DeductionFailure.Data = FailedAttr; 6623 return; 6624 } 6625 } 6626 6627 ObjCMethodDecl * 6628 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6629 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6630 if (Methods.size() <= 1) 6631 return nullptr; 6632 6633 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6634 bool Match = true; 6635 ObjCMethodDecl *Method = Methods[b]; 6636 unsigned NumNamedArgs = Sel.getNumArgs(); 6637 // Method might have more arguments than selector indicates. This is due 6638 // to addition of c-style arguments in method. 6639 if (Method->param_size() > NumNamedArgs) 6640 NumNamedArgs = Method->param_size(); 6641 if (Args.size() < NumNamedArgs) 6642 continue; 6643 6644 for (unsigned i = 0; i < NumNamedArgs; i++) { 6645 // We can't do any type-checking on a type-dependent argument. 6646 if (Args[i]->isTypeDependent()) { 6647 Match = false; 6648 break; 6649 } 6650 6651 ParmVarDecl *param = Method->parameters()[i]; 6652 Expr *argExpr = Args[i]; 6653 assert(argExpr && "SelectBestMethod(): missing expression"); 6654 6655 // Strip the unbridged-cast placeholder expression off unless it's 6656 // a consumed argument. 6657 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6658 !param->hasAttr<CFConsumedAttr>()) 6659 argExpr = stripARCUnbridgedCast(argExpr); 6660 6661 // If the parameter is __unknown_anytype, move on to the next method. 6662 if (param->getType() == Context.UnknownAnyTy) { 6663 Match = false; 6664 break; 6665 } 6666 6667 ImplicitConversionSequence ConversionState 6668 = TryCopyInitialization(*this, argExpr, param->getType(), 6669 /*SuppressUserConversions*/false, 6670 /*InOverloadResolution=*/true, 6671 /*AllowObjCWritebackConversion=*/ 6672 getLangOpts().ObjCAutoRefCount, 6673 /*AllowExplicit*/false); 6674 // This function looks for a reasonably-exact match, so we consider 6675 // incompatible pointer conversions to be a failure here. 6676 if (ConversionState.isBad() || 6677 (ConversionState.isStandard() && 6678 ConversionState.Standard.Second == 6679 ICK_Incompatible_Pointer_Conversion)) { 6680 Match = false; 6681 break; 6682 } 6683 } 6684 // Promote additional arguments to variadic methods. 6685 if (Match && Method->isVariadic()) { 6686 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6687 if (Args[i]->isTypeDependent()) { 6688 Match = false; 6689 break; 6690 } 6691 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6692 nullptr); 6693 if (Arg.isInvalid()) { 6694 Match = false; 6695 break; 6696 } 6697 } 6698 } else { 6699 // Check for extra arguments to non-variadic methods. 6700 if (Args.size() != NumNamedArgs) 6701 Match = false; 6702 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6703 // Special case when selectors have no argument. In this case, select 6704 // one with the most general result type of 'id'. 6705 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6706 QualType ReturnT = Methods[b]->getReturnType(); 6707 if (ReturnT->isObjCIdType()) 6708 return Methods[b]; 6709 } 6710 } 6711 } 6712 6713 if (Match) 6714 return Method; 6715 } 6716 return nullptr; 6717 } 6718 6719 static bool convertArgsForAvailabilityChecks( 6720 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6721 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6722 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6723 if (ThisArg) { 6724 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6725 assert(!isa<CXXConstructorDecl>(Method) && 6726 "Shouldn't have `this` for ctors!"); 6727 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6728 ExprResult R = S.PerformObjectArgumentInitialization( 6729 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6730 if (R.isInvalid()) 6731 return false; 6732 ConvertedThis = R.get(); 6733 } else { 6734 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6735 (void)MD; 6736 assert((MissingImplicitThis || MD->isStatic() || 6737 isa<CXXConstructorDecl>(MD)) && 6738 "Expected `this` for non-ctor instance methods"); 6739 } 6740 ConvertedThis = nullptr; 6741 } 6742 6743 // Ignore any variadic arguments. Converting them is pointless, since the 6744 // user can't refer to them in the function condition. 6745 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6746 6747 // Convert the arguments. 6748 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6749 ExprResult R; 6750 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6751 S.Context, Function->getParamDecl(I)), 6752 SourceLocation(), Args[I]); 6753 6754 if (R.isInvalid()) 6755 return false; 6756 6757 ConvertedArgs.push_back(R.get()); 6758 } 6759 6760 if (Trap.hasErrorOccurred()) 6761 return false; 6762 6763 // Push default arguments if needed. 6764 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6765 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6766 ParmVarDecl *P = Function->getParamDecl(i); 6767 if (!P->hasDefaultArg()) 6768 return false; 6769 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6770 if (R.isInvalid()) 6771 return false; 6772 ConvertedArgs.push_back(R.get()); 6773 } 6774 6775 if (Trap.hasErrorOccurred()) 6776 return false; 6777 } 6778 return true; 6779 } 6780 6781 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6782 SourceLocation CallLoc, 6783 ArrayRef<Expr *> Args, 6784 bool MissingImplicitThis) { 6785 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6786 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6787 return nullptr; 6788 6789 SFINAETrap Trap(*this); 6790 SmallVector<Expr *, 16> ConvertedArgs; 6791 // FIXME: We should look into making enable_if late-parsed. 6792 Expr *DiscardedThis; 6793 if (!convertArgsForAvailabilityChecks( 6794 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6795 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6796 return *EnableIfAttrs.begin(); 6797 6798 for (auto *EIA : EnableIfAttrs) { 6799 APValue Result; 6800 // FIXME: This doesn't consider value-dependent cases, because doing so is 6801 // very difficult. Ideally, we should handle them more gracefully. 6802 if (EIA->getCond()->isValueDependent() || 6803 !EIA->getCond()->EvaluateWithSubstitution( 6804 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6805 return EIA; 6806 6807 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6808 return EIA; 6809 } 6810 return nullptr; 6811 } 6812 6813 template <typename CheckFn> 6814 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6815 bool ArgDependent, SourceLocation Loc, 6816 CheckFn &&IsSuccessful) { 6817 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6818 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6819 if (ArgDependent == DIA->getArgDependent()) 6820 Attrs.push_back(DIA); 6821 } 6822 6823 // Common case: No diagnose_if attributes, so we can quit early. 6824 if (Attrs.empty()) 6825 return false; 6826 6827 auto WarningBegin = std::stable_partition( 6828 Attrs.begin(), Attrs.end(), 6829 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6830 6831 // Note that diagnose_if attributes are late-parsed, so they appear in the 6832 // correct order (unlike enable_if attributes). 6833 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6834 IsSuccessful); 6835 if (ErrAttr != WarningBegin) { 6836 const DiagnoseIfAttr *DIA = *ErrAttr; 6837 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6838 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6839 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6840 return true; 6841 } 6842 6843 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6844 if (IsSuccessful(DIA)) { 6845 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6846 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6847 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6848 } 6849 6850 return false; 6851 } 6852 6853 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6854 const Expr *ThisArg, 6855 ArrayRef<const Expr *> Args, 6856 SourceLocation Loc) { 6857 return diagnoseDiagnoseIfAttrsWith( 6858 *this, Function, /*ArgDependent=*/true, Loc, 6859 [&](const DiagnoseIfAttr *DIA) { 6860 APValue Result; 6861 // It's sane to use the same Args for any redecl of this function, since 6862 // EvaluateWithSubstitution only cares about the position of each 6863 // argument in the arg list, not the ParmVarDecl* it maps to. 6864 if (!DIA->getCond()->EvaluateWithSubstitution( 6865 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6866 return false; 6867 return Result.isInt() && Result.getInt().getBoolValue(); 6868 }); 6869 } 6870 6871 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6872 SourceLocation Loc) { 6873 return diagnoseDiagnoseIfAttrsWith( 6874 *this, ND, /*ArgDependent=*/false, Loc, 6875 [&](const DiagnoseIfAttr *DIA) { 6876 bool Result; 6877 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6878 Result; 6879 }); 6880 } 6881 6882 /// Add all of the function declarations in the given function set to 6883 /// the overload candidate set. 6884 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6885 ArrayRef<Expr *> Args, 6886 OverloadCandidateSet &CandidateSet, 6887 TemplateArgumentListInfo *ExplicitTemplateArgs, 6888 bool SuppressUserConversions, 6889 bool PartialOverloading, 6890 bool FirstArgumentIsBase) { 6891 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6892 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6893 ArrayRef<Expr *> FunctionArgs = Args; 6894 6895 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6896 FunctionDecl *FD = 6897 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6898 6899 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6900 QualType ObjectType; 6901 Expr::Classification ObjectClassification; 6902 if (Args.size() > 0) { 6903 if (Expr *E = Args[0]) { 6904 // Use the explicit base to restrict the lookup: 6905 ObjectType = E->getType(); 6906 // Pointers in the object arguments are implicitly dereferenced, so we 6907 // always classify them as l-values. 6908 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6909 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6910 else 6911 ObjectClassification = E->Classify(Context); 6912 } // .. else there is an implicit base. 6913 FunctionArgs = Args.slice(1); 6914 } 6915 if (FunTmpl) { 6916 AddMethodTemplateCandidate( 6917 FunTmpl, F.getPair(), 6918 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6919 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6920 FunctionArgs, CandidateSet, SuppressUserConversions, 6921 PartialOverloading); 6922 } else { 6923 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6924 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6925 ObjectClassification, FunctionArgs, CandidateSet, 6926 SuppressUserConversions, PartialOverloading); 6927 } 6928 } else { 6929 // This branch handles both standalone functions and static methods. 6930 6931 // Slice the first argument (which is the base) when we access 6932 // static method as non-static. 6933 if (Args.size() > 0 && 6934 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6935 !isa<CXXConstructorDecl>(FD)))) { 6936 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6937 FunctionArgs = Args.slice(1); 6938 } 6939 if (FunTmpl) { 6940 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6941 ExplicitTemplateArgs, FunctionArgs, 6942 CandidateSet, SuppressUserConversions, 6943 PartialOverloading); 6944 } else { 6945 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6946 SuppressUserConversions, PartialOverloading); 6947 } 6948 } 6949 } 6950 } 6951 6952 /// AddMethodCandidate - Adds a named decl (which is some kind of 6953 /// method) as a method candidate to the given overload set. 6954 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6955 Expr::Classification ObjectClassification, 6956 ArrayRef<Expr *> Args, 6957 OverloadCandidateSet &CandidateSet, 6958 bool SuppressUserConversions, 6959 OverloadCandidateParamOrder PO) { 6960 NamedDecl *Decl = FoundDecl.getDecl(); 6961 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6962 6963 if (isa<UsingShadowDecl>(Decl)) 6964 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6965 6966 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6967 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6968 "Expected a member function template"); 6969 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6970 /*ExplicitArgs*/ nullptr, ObjectType, 6971 ObjectClassification, Args, CandidateSet, 6972 SuppressUserConversions, false, PO); 6973 } else { 6974 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6975 ObjectType, ObjectClassification, Args, CandidateSet, 6976 SuppressUserConversions, false, None, PO); 6977 } 6978 } 6979 6980 /// AddMethodCandidate - Adds the given C++ member function to the set 6981 /// of candidate functions, using the given function call arguments 6982 /// and the object argument (@c Object). For example, in a call 6983 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6984 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6985 /// allow user-defined conversions via constructors or conversion 6986 /// operators. 6987 void 6988 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6989 CXXRecordDecl *ActingContext, QualType ObjectType, 6990 Expr::Classification ObjectClassification, 6991 ArrayRef<Expr *> Args, 6992 OverloadCandidateSet &CandidateSet, 6993 bool SuppressUserConversions, 6994 bool PartialOverloading, 6995 ConversionSequenceList EarlyConversions, 6996 OverloadCandidateParamOrder PO) { 6997 const FunctionProtoType *Proto 6998 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6999 assert(Proto && "Methods without a prototype cannot be overloaded"); 7000 assert(!isa<CXXConstructorDecl>(Method) && 7001 "Use AddOverloadCandidate for constructors"); 7002 7003 if (!CandidateSet.isNewCandidate(Method, PO)) 7004 return; 7005 7006 // C++11 [class.copy]p23: [DR1402] 7007 // A defaulted move assignment operator that is defined as deleted is 7008 // ignored by overload resolution. 7009 if (Method->isDefaulted() && Method->isDeleted() && 7010 Method->isMoveAssignmentOperator()) 7011 return; 7012 7013 // Overload resolution is always an unevaluated context. 7014 EnterExpressionEvaluationContext Unevaluated( 7015 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7016 7017 // Add this candidate 7018 OverloadCandidate &Candidate = 7019 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 7020 Candidate.FoundDecl = FoundDecl; 7021 Candidate.Function = Method; 7022 Candidate.RewriteKind = 7023 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 7024 Candidate.IsSurrogate = false; 7025 Candidate.IgnoreObjectArgument = false; 7026 Candidate.ExplicitCallArguments = Args.size(); 7027 7028 unsigned NumParams = Proto->getNumParams(); 7029 7030 // (C++ 13.3.2p2): A candidate function having fewer than m 7031 // parameters is viable only if it has an ellipsis in its parameter 7032 // list (8.3.5). 7033 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 7034 !Proto->isVariadic() && 7035 shouldEnforceArgLimit(PartialOverloading, Method)) { 7036 Candidate.Viable = false; 7037 Candidate.FailureKind = ovl_fail_too_many_arguments; 7038 return; 7039 } 7040 7041 // (C++ 13.3.2p2): A candidate function having more than m parameters 7042 // is viable only if the (m+1)st parameter has a default argument 7043 // (8.3.6). For the purposes of overload resolution, the 7044 // parameter list is truncated on the right, so that there are 7045 // exactly m parameters. 7046 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 7047 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 7048 // Not enough arguments. 7049 Candidate.Viable = false; 7050 Candidate.FailureKind = ovl_fail_too_few_arguments; 7051 return; 7052 } 7053 7054 Candidate.Viable = true; 7055 7056 if (Method->isStatic() || ObjectType.isNull()) 7057 // The implicit object argument is ignored. 7058 Candidate.IgnoreObjectArgument = true; 7059 else { 7060 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7061 // Determine the implicit conversion sequence for the object 7062 // parameter. 7063 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 7064 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7065 Method, ActingContext); 7066 if (Candidate.Conversions[ConvIdx].isBad()) { 7067 Candidate.Viable = false; 7068 Candidate.FailureKind = ovl_fail_bad_conversion; 7069 return; 7070 } 7071 } 7072 7073 // (CUDA B.1): Check for invalid calls between targets. 7074 if (getLangOpts().CUDA) 7075 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) 7076 if (!IsAllowedCUDACall(Caller, Method)) { 7077 Candidate.Viable = false; 7078 Candidate.FailureKind = ovl_fail_bad_target; 7079 return; 7080 } 7081 7082 if (Method->getTrailingRequiresClause()) { 7083 ConstraintSatisfaction Satisfaction; 7084 if (CheckFunctionConstraints(Method, Satisfaction) || 7085 !Satisfaction.IsSatisfied) { 7086 Candidate.Viable = false; 7087 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7088 return; 7089 } 7090 } 7091 7092 // Determine the implicit conversion sequences for each of the 7093 // arguments. 7094 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7095 unsigned ConvIdx = 7096 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7097 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7098 // We already formed a conversion sequence for this parameter during 7099 // template argument deduction. 7100 } else if (ArgIdx < NumParams) { 7101 // (C++ 13.3.2p3): for F to be a viable function, there shall 7102 // exist for each argument an implicit conversion sequence 7103 // (13.3.3.1) that converts that argument to the corresponding 7104 // parameter of F. 7105 QualType ParamType = Proto->getParamType(ArgIdx); 7106 Candidate.Conversions[ConvIdx] 7107 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7108 SuppressUserConversions, 7109 /*InOverloadResolution=*/true, 7110 /*AllowObjCWritebackConversion=*/ 7111 getLangOpts().ObjCAutoRefCount); 7112 if (Candidate.Conversions[ConvIdx].isBad()) { 7113 Candidate.Viable = false; 7114 Candidate.FailureKind = ovl_fail_bad_conversion; 7115 return; 7116 } 7117 } else { 7118 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7119 // argument for which there is no corresponding parameter is 7120 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7121 Candidate.Conversions[ConvIdx].setEllipsis(); 7122 } 7123 } 7124 7125 if (EnableIfAttr *FailedAttr = 7126 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7127 Candidate.Viable = false; 7128 Candidate.FailureKind = ovl_fail_enable_if; 7129 Candidate.DeductionFailure.Data = FailedAttr; 7130 return; 7131 } 7132 7133 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 7134 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 7135 Candidate.Viable = false; 7136 Candidate.FailureKind = ovl_non_default_multiversion_function; 7137 } 7138 } 7139 7140 /// Add a C++ member function template as a candidate to the candidate 7141 /// set, using template argument deduction to produce an appropriate member 7142 /// function template specialization. 7143 void Sema::AddMethodTemplateCandidate( 7144 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7145 CXXRecordDecl *ActingContext, 7146 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7147 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7148 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7149 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7150 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7151 return; 7152 7153 // C++ [over.match.funcs]p7: 7154 // In each case where a candidate is a function template, candidate 7155 // function template specializations are generated using template argument 7156 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7157 // candidate functions in the usual way.113) A given name can refer to one 7158 // or more function templates and also to a set of overloaded non-template 7159 // functions. In such a case, the candidate functions generated from each 7160 // function template are combined with the set of non-template candidate 7161 // functions. 7162 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7163 FunctionDecl *Specialization = nullptr; 7164 ConversionSequenceList Conversions; 7165 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7166 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7167 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7168 return CheckNonDependentConversions( 7169 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7170 SuppressUserConversions, ActingContext, ObjectType, 7171 ObjectClassification, PO); 7172 })) { 7173 OverloadCandidate &Candidate = 7174 CandidateSet.addCandidate(Conversions.size(), Conversions); 7175 Candidate.FoundDecl = FoundDecl; 7176 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7177 Candidate.Viable = false; 7178 Candidate.RewriteKind = 7179 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7180 Candidate.IsSurrogate = false; 7181 Candidate.IgnoreObjectArgument = 7182 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7183 ObjectType.isNull(); 7184 Candidate.ExplicitCallArguments = Args.size(); 7185 if (Result == TDK_NonDependentConversionFailure) 7186 Candidate.FailureKind = ovl_fail_bad_conversion; 7187 else { 7188 Candidate.FailureKind = ovl_fail_bad_deduction; 7189 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7190 Info); 7191 } 7192 return; 7193 } 7194 7195 // Add the function template specialization produced by template argument 7196 // deduction as a candidate. 7197 assert(Specialization && "Missing member function template specialization?"); 7198 assert(isa<CXXMethodDecl>(Specialization) && 7199 "Specialization is not a member function?"); 7200 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7201 ActingContext, ObjectType, ObjectClassification, Args, 7202 CandidateSet, SuppressUserConversions, PartialOverloading, 7203 Conversions, PO); 7204 } 7205 7206 /// Determine whether a given function template has a simple explicit specifier 7207 /// or a non-value-dependent explicit-specification that evaluates to true. 7208 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7209 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7210 } 7211 7212 /// Add a C++ function template specialization as a candidate 7213 /// in the candidate set, using template argument deduction to produce 7214 /// an appropriate function template specialization. 7215 void Sema::AddTemplateOverloadCandidate( 7216 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7217 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7218 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7219 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7220 OverloadCandidateParamOrder PO) { 7221 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7222 return; 7223 7224 // If the function template has a non-dependent explicit specification, 7225 // exclude it now if appropriate; we are not permitted to perform deduction 7226 // and substitution in this case. 7227 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7228 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7229 Candidate.FoundDecl = FoundDecl; 7230 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7231 Candidate.Viable = false; 7232 Candidate.FailureKind = ovl_fail_explicit; 7233 return; 7234 } 7235 7236 // C++ [over.match.funcs]p7: 7237 // In each case where a candidate is a function template, candidate 7238 // function template specializations are generated using template argument 7239 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7240 // candidate functions in the usual way.113) A given name can refer to one 7241 // or more function templates and also to a set of overloaded non-template 7242 // functions. In such a case, the candidate functions generated from each 7243 // function template are combined with the set of non-template candidate 7244 // functions. 7245 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7246 FunctionDecl *Specialization = nullptr; 7247 ConversionSequenceList Conversions; 7248 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7249 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7250 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7251 return CheckNonDependentConversions( 7252 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7253 SuppressUserConversions, nullptr, QualType(), {}, PO); 7254 })) { 7255 OverloadCandidate &Candidate = 7256 CandidateSet.addCandidate(Conversions.size(), Conversions); 7257 Candidate.FoundDecl = FoundDecl; 7258 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7259 Candidate.Viable = false; 7260 Candidate.RewriteKind = 7261 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7262 Candidate.IsSurrogate = false; 7263 Candidate.IsADLCandidate = IsADLCandidate; 7264 // Ignore the object argument if there is one, since we don't have an object 7265 // type. 7266 Candidate.IgnoreObjectArgument = 7267 isa<CXXMethodDecl>(Candidate.Function) && 7268 !isa<CXXConstructorDecl>(Candidate.Function); 7269 Candidate.ExplicitCallArguments = Args.size(); 7270 if (Result == TDK_NonDependentConversionFailure) 7271 Candidate.FailureKind = ovl_fail_bad_conversion; 7272 else { 7273 Candidate.FailureKind = ovl_fail_bad_deduction; 7274 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7275 Info); 7276 } 7277 return; 7278 } 7279 7280 // Add the function template specialization produced by template argument 7281 // deduction as a candidate. 7282 assert(Specialization && "Missing function template specialization?"); 7283 AddOverloadCandidate( 7284 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7285 PartialOverloading, AllowExplicit, 7286 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7287 } 7288 7289 /// Check that implicit conversion sequences can be formed for each argument 7290 /// whose corresponding parameter has a non-dependent type, per DR1391's 7291 /// [temp.deduct.call]p10. 7292 bool Sema::CheckNonDependentConversions( 7293 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7294 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7295 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7296 CXXRecordDecl *ActingContext, QualType ObjectType, 7297 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7298 // FIXME: The cases in which we allow explicit conversions for constructor 7299 // arguments never consider calling a constructor template. It's not clear 7300 // that is correct. 7301 const bool AllowExplicit = false; 7302 7303 auto *FD = FunctionTemplate->getTemplatedDecl(); 7304 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7305 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7306 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7307 7308 Conversions = 7309 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7310 7311 // Overload resolution is always an unevaluated context. 7312 EnterExpressionEvaluationContext Unevaluated( 7313 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7314 7315 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7316 // require that, but this check should never result in a hard error, and 7317 // overload resolution is permitted to sidestep instantiations. 7318 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7319 !ObjectType.isNull()) { 7320 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7321 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7322 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7323 Method, ActingContext); 7324 if (Conversions[ConvIdx].isBad()) 7325 return true; 7326 } 7327 7328 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7329 ++I) { 7330 QualType ParamType = ParamTypes[I]; 7331 if (!ParamType->isDependentType()) { 7332 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7333 ? 0 7334 : (ThisConversions + I); 7335 Conversions[ConvIdx] 7336 = TryCopyInitialization(*this, Args[I], ParamType, 7337 SuppressUserConversions, 7338 /*InOverloadResolution=*/true, 7339 /*AllowObjCWritebackConversion=*/ 7340 getLangOpts().ObjCAutoRefCount, 7341 AllowExplicit); 7342 if (Conversions[ConvIdx].isBad()) 7343 return true; 7344 } 7345 } 7346 7347 return false; 7348 } 7349 7350 /// Determine whether this is an allowable conversion from the result 7351 /// of an explicit conversion operator to the expected type, per C++ 7352 /// [over.match.conv]p1 and [over.match.ref]p1. 7353 /// 7354 /// \param ConvType The return type of the conversion function. 7355 /// 7356 /// \param ToType The type we are converting to. 7357 /// 7358 /// \param AllowObjCPointerConversion Allow a conversion from one 7359 /// Objective-C pointer to another. 7360 /// 7361 /// \returns true if the conversion is allowable, false otherwise. 7362 static bool isAllowableExplicitConversion(Sema &S, 7363 QualType ConvType, QualType ToType, 7364 bool AllowObjCPointerConversion) { 7365 QualType ToNonRefType = ToType.getNonReferenceType(); 7366 7367 // Easy case: the types are the same. 7368 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7369 return true; 7370 7371 // Allow qualification conversions. 7372 bool ObjCLifetimeConversion; 7373 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7374 ObjCLifetimeConversion)) 7375 return true; 7376 7377 // If we're not allowed to consider Objective-C pointer conversions, 7378 // we're done. 7379 if (!AllowObjCPointerConversion) 7380 return false; 7381 7382 // Is this an Objective-C pointer conversion? 7383 bool IncompatibleObjC = false; 7384 QualType ConvertedType; 7385 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7386 IncompatibleObjC); 7387 } 7388 7389 /// AddConversionCandidate - Add a C++ conversion function as a 7390 /// candidate in the candidate set (C++ [over.match.conv], 7391 /// C++ [over.match.copy]). From is the expression we're converting from, 7392 /// and ToType is the type that we're eventually trying to convert to 7393 /// (which may or may not be the same type as the type that the 7394 /// conversion function produces). 7395 void Sema::AddConversionCandidate( 7396 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7397 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7398 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7399 bool AllowExplicit, bool AllowResultConversion) { 7400 assert(!Conversion->getDescribedFunctionTemplate() && 7401 "Conversion function templates use AddTemplateConversionCandidate"); 7402 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7403 if (!CandidateSet.isNewCandidate(Conversion)) 7404 return; 7405 7406 // If the conversion function has an undeduced return type, trigger its 7407 // deduction now. 7408 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7409 if (DeduceReturnType(Conversion, From->getExprLoc())) 7410 return; 7411 ConvType = Conversion->getConversionType().getNonReferenceType(); 7412 } 7413 7414 // If we don't allow any conversion of the result type, ignore conversion 7415 // functions that don't convert to exactly (possibly cv-qualified) T. 7416 if (!AllowResultConversion && 7417 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7418 return; 7419 7420 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7421 // operator is only a candidate if its return type is the target type or 7422 // can be converted to the target type with a qualification conversion. 7423 // 7424 // FIXME: Include such functions in the candidate list and explain why we 7425 // can't select them. 7426 if (Conversion->isExplicit() && 7427 !isAllowableExplicitConversion(*this, ConvType, ToType, 7428 AllowObjCConversionOnExplicit)) 7429 return; 7430 7431 // Overload resolution is always an unevaluated context. 7432 EnterExpressionEvaluationContext Unevaluated( 7433 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7434 7435 // Add this candidate 7436 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7437 Candidate.FoundDecl = FoundDecl; 7438 Candidate.Function = Conversion; 7439 Candidate.IsSurrogate = false; 7440 Candidate.IgnoreObjectArgument = false; 7441 Candidate.FinalConversion.setAsIdentityConversion(); 7442 Candidate.FinalConversion.setFromType(ConvType); 7443 Candidate.FinalConversion.setAllToTypes(ToType); 7444 Candidate.Viable = true; 7445 Candidate.ExplicitCallArguments = 1; 7446 7447 // Explicit functions are not actually candidates at all if we're not 7448 // allowing them in this context, but keep them around so we can point 7449 // to them in diagnostics. 7450 if (!AllowExplicit && Conversion->isExplicit()) { 7451 Candidate.Viable = false; 7452 Candidate.FailureKind = ovl_fail_explicit; 7453 return; 7454 } 7455 7456 // C++ [over.match.funcs]p4: 7457 // For conversion functions, the function is considered to be a member of 7458 // the class of the implicit implied object argument for the purpose of 7459 // defining the type of the implicit object parameter. 7460 // 7461 // Determine the implicit conversion sequence for the implicit 7462 // object parameter. 7463 QualType ImplicitParamType = From->getType(); 7464 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7465 ImplicitParamType = FromPtrType->getPointeeType(); 7466 CXXRecordDecl *ConversionContext 7467 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7468 7469 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7470 *this, CandidateSet.getLocation(), From->getType(), 7471 From->Classify(Context), Conversion, ConversionContext); 7472 7473 if (Candidate.Conversions[0].isBad()) { 7474 Candidate.Viable = false; 7475 Candidate.FailureKind = ovl_fail_bad_conversion; 7476 return; 7477 } 7478 7479 if (Conversion->getTrailingRequiresClause()) { 7480 ConstraintSatisfaction Satisfaction; 7481 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7482 !Satisfaction.IsSatisfied) { 7483 Candidate.Viable = false; 7484 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7485 return; 7486 } 7487 } 7488 7489 // We won't go through a user-defined type conversion function to convert a 7490 // derived to base as such conversions are given Conversion Rank. They only 7491 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7492 QualType FromCanon 7493 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7494 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7495 if (FromCanon == ToCanon || 7496 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7497 Candidate.Viable = false; 7498 Candidate.FailureKind = ovl_fail_trivial_conversion; 7499 return; 7500 } 7501 7502 // To determine what the conversion from the result of calling the 7503 // conversion function to the type we're eventually trying to 7504 // convert to (ToType), we need to synthesize a call to the 7505 // conversion function and attempt copy initialization from it. This 7506 // makes sure that we get the right semantics with respect to 7507 // lvalues/rvalues and the type. Fortunately, we can allocate this 7508 // call on the stack and we don't need its arguments to be 7509 // well-formed. 7510 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7511 VK_LValue, From->getBeginLoc()); 7512 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7513 Context.getPointerType(Conversion->getType()), 7514 CK_FunctionToPointerDecay, &ConversionRef, 7515 VK_PRValue, FPOptionsOverride()); 7516 7517 QualType ConversionType = Conversion->getConversionType(); 7518 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7519 Candidate.Viable = false; 7520 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7521 return; 7522 } 7523 7524 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7525 7526 // Note that it is safe to allocate CallExpr on the stack here because 7527 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7528 // allocator). 7529 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7530 7531 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7532 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7533 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7534 7535 ImplicitConversionSequence ICS = 7536 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7537 /*SuppressUserConversions=*/true, 7538 /*InOverloadResolution=*/false, 7539 /*AllowObjCWritebackConversion=*/false); 7540 7541 switch (ICS.getKind()) { 7542 case ImplicitConversionSequence::StandardConversion: 7543 Candidate.FinalConversion = ICS.Standard; 7544 7545 // C++ [over.ics.user]p3: 7546 // If the user-defined conversion is specified by a specialization of a 7547 // conversion function template, the second standard conversion sequence 7548 // shall have exact match rank. 7549 if (Conversion->getPrimaryTemplate() && 7550 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7551 Candidate.Viable = false; 7552 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7553 return; 7554 } 7555 7556 // C++0x [dcl.init.ref]p5: 7557 // In the second case, if the reference is an rvalue reference and 7558 // the second standard conversion sequence of the user-defined 7559 // conversion sequence includes an lvalue-to-rvalue conversion, the 7560 // program is ill-formed. 7561 if (ToType->isRValueReferenceType() && 7562 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7563 Candidate.Viable = false; 7564 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7565 return; 7566 } 7567 break; 7568 7569 case ImplicitConversionSequence::BadConversion: 7570 Candidate.Viable = false; 7571 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7572 return; 7573 7574 default: 7575 llvm_unreachable( 7576 "Can only end up with a standard conversion sequence or failure"); 7577 } 7578 7579 if (EnableIfAttr *FailedAttr = 7580 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7581 Candidate.Viable = false; 7582 Candidate.FailureKind = ovl_fail_enable_if; 7583 Candidate.DeductionFailure.Data = FailedAttr; 7584 return; 7585 } 7586 7587 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7588 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7589 Candidate.Viable = false; 7590 Candidate.FailureKind = ovl_non_default_multiversion_function; 7591 } 7592 } 7593 7594 /// Adds a conversion function template specialization 7595 /// candidate to the overload set, using template argument deduction 7596 /// to deduce the template arguments of the conversion function 7597 /// template from the type that we are converting to (C++ 7598 /// [temp.deduct.conv]). 7599 void Sema::AddTemplateConversionCandidate( 7600 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7601 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7602 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7603 bool AllowExplicit, bool AllowResultConversion) { 7604 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7605 "Only conversion function templates permitted here"); 7606 7607 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7608 return; 7609 7610 // If the function template has a non-dependent explicit specification, 7611 // exclude it now if appropriate; we are not permitted to perform deduction 7612 // and substitution in this case. 7613 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7614 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7615 Candidate.FoundDecl = FoundDecl; 7616 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7617 Candidate.Viable = false; 7618 Candidate.FailureKind = ovl_fail_explicit; 7619 return; 7620 } 7621 7622 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7623 CXXConversionDecl *Specialization = nullptr; 7624 if (TemplateDeductionResult Result 7625 = DeduceTemplateArguments(FunctionTemplate, ToType, 7626 Specialization, Info)) { 7627 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7628 Candidate.FoundDecl = FoundDecl; 7629 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7630 Candidate.Viable = false; 7631 Candidate.FailureKind = ovl_fail_bad_deduction; 7632 Candidate.IsSurrogate = false; 7633 Candidate.IgnoreObjectArgument = false; 7634 Candidate.ExplicitCallArguments = 1; 7635 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7636 Info); 7637 return; 7638 } 7639 7640 // Add the conversion function template specialization produced by 7641 // template argument deduction as a candidate. 7642 assert(Specialization && "Missing function template specialization?"); 7643 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7644 CandidateSet, AllowObjCConversionOnExplicit, 7645 AllowExplicit, AllowResultConversion); 7646 } 7647 7648 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7649 /// converts the given @c Object to a function pointer via the 7650 /// conversion function @c Conversion, and then attempts to call it 7651 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7652 /// the type of function that we'll eventually be calling. 7653 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7654 DeclAccessPair FoundDecl, 7655 CXXRecordDecl *ActingContext, 7656 const FunctionProtoType *Proto, 7657 Expr *Object, 7658 ArrayRef<Expr *> Args, 7659 OverloadCandidateSet& CandidateSet) { 7660 if (!CandidateSet.isNewCandidate(Conversion)) 7661 return; 7662 7663 // Overload resolution is always an unevaluated context. 7664 EnterExpressionEvaluationContext Unevaluated( 7665 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7666 7667 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7668 Candidate.FoundDecl = FoundDecl; 7669 Candidate.Function = nullptr; 7670 Candidate.Surrogate = Conversion; 7671 Candidate.Viable = true; 7672 Candidate.IsSurrogate = true; 7673 Candidate.IgnoreObjectArgument = false; 7674 Candidate.ExplicitCallArguments = Args.size(); 7675 7676 // Determine the implicit conversion sequence for the implicit 7677 // object parameter. 7678 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7679 *this, CandidateSet.getLocation(), Object->getType(), 7680 Object->Classify(Context), Conversion, ActingContext); 7681 if (ObjectInit.isBad()) { 7682 Candidate.Viable = false; 7683 Candidate.FailureKind = ovl_fail_bad_conversion; 7684 Candidate.Conversions[0] = ObjectInit; 7685 return; 7686 } 7687 7688 // The first conversion is actually a user-defined conversion whose 7689 // first conversion is ObjectInit's standard conversion (which is 7690 // effectively a reference binding). Record it as such. 7691 Candidate.Conversions[0].setUserDefined(); 7692 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7693 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7694 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7695 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7696 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7697 Candidate.Conversions[0].UserDefined.After 7698 = Candidate.Conversions[0].UserDefined.Before; 7699 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7700 7701 // Find the 7702 unsigned NumParams = Proto->getNumParams(); 7703 7704 // (C++ 13.3.2p2): A candidate function having fewer than m 7705 // parameters is viable only if it has an ellipsis in its parameter 7706 // list (8.3.5). 7707 if (Args.size() > NumParams && !Proto->isVariadic()) { 7708 Candidate.Viable = false; 7709 Candidate.FailureKind = ovl_fail_too_many_arguments; 7710 return; 7711 } 7712 7713 // Function types don't have any default arguments, so just check if 7714 // we have enough arguments. 7715 if (Args.size() < NumParams) { 7716 // Not enough arguments. 7717 Candidate.Viable = false; 7718 Candidate.FailureKind = ovl_fail_too_few_arguments; 7719 return; 7720 } 7721 7722 // Determine the implicit conversion sequences for each of the 7723 // arguments. 7724 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7725 if (ArgIdx < NumParams) { 7726 // (C++ 13.3.2p3): for F to be a viable function, there shall 7727 // exist for each argument an implicit conversion sequence 7728 // (13.3.3.1) that converts that argument to the corresponding 7729 // parameter of F. 7730 QualType ParamType = Proto->getParamType(ArgIdx); 7731 Candidate.Conversions[ArgIdx + 1] 7732 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7733 /*SuppressUserConversions=*/false, 7734 /*InOverloadResolution=*/false, 7735 /*AllowObjCWritebackConversion=*/ 7736 getLangOpts().ObjCAutoRefCount); 7737 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7738 Candidate.Viable = false; 7739 Candidate.FailureKind = ovl_fail_bad_conversion; 7740 return; 7741 } 7742 } else { 7743 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7744 // argument for which there is no corresponding parameter is 7745 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7746 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7747 } 7748 } 7749 7750 if (EnableIfAttr *FailedAttr = 7751 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7752 Candidate.Viable = false; 7753 Candidate.FailureKind = ovl_fail_enable_if; 7754 Candidate.DeductionFailure.Data = FailedAttr; 7755 return; 7756 } 7757 } 7758 7759 /// Add all of the non-member operator function declarations in the given 7760 /// function set to the overload candidate set. 7761 void Sema::AddNonMemberOperatorCandidates( 7762 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7763 OverloadCandidateSet &CandidateSet, 7764 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7765 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7766 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7767 ArrayRef<Expr *> FunctionArgs = Args; 7768 7769 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7770 FunctionDecl *FD = 7771 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7772 7773 // Don't consider rewritten functions if we're not rewriting. 7774 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7775 continue; 7776 7777 assert(!isa<CXXMethodDecl>(FD) && 7778 "unqualified operator lookup found a member function"); 7779 7780 if (FunTmpl) { 7781 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7782 FunctionArgs, CandidateSet); 7783 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7784 AddTemplateOverloadCandidate( 7785 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7786 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7787 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7788 } else { 7789 if (ExplicitTemplateArgs) 7790 continue; 7791 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7792 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7793 AddOverloadCandidate(FD, F.getPair(), 7794 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7795 false, false, true, false, ADLCallKind::NotADL, 7796 None, OverloadCandidateParamOrder::Reversed); 7797 } 7798 } 7799 } 7800 7801 /// Add overload candidates for overloaded operators that are 7802 /// member functions. 7803 /// 7804 /// Add the overloaded operator candidates that are member functions 7805 /// for the operator Op that was used in an operator expression such 7806 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7807 /// CandidateSet will store the added overload candidates. (C++ 7808 /// [over.match.oper]). 7809 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7810 SourceLocation OpLoc, 7811 ArrayRef<Expr *> Args, 7812 OverloadCandidateSet &CandidateSet, 7813 OverloadCandidateParamOrder PO) { 7814 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7815 7816 // C++ [over.match.oper]p3: 7817 // For a unary operator @ with an operand of a type whose 7818 // cv-unqualified version is T1, and for a binary operator @ with 7819 // a left operand of a type whose cv-unqualified version is T1 and 7820 // a right operand of a type whose cv-unqualified version is T2, 7821 // three sets of candidate functions, designated member 7822 // candidates, non-member candidates and built-in candidates, are 7823 // constructed as follows: 7824 QualType T1 = Args[0]->getType(); 7825 7826 // -- If T1 is a complete class type or a class currently being 7827 // defined, the set of member candidates is the result of the 7828 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7829 // the set of member candidates is empty. 7830 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7831 // Complete the type if it can be completed. 7832 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7833 return; 7834 // If the type is neither complete nor being defined, bail out now. 7835 if (!T1Rec->getDecl()->getDefinition()) 7836 return; 7837 7838 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7839 LookupQualifiedName(Operators, T1Rec->getDecl()); 7840 Operators.suppressDiagnostics(); 7841 7842 for (LookupResult::iterator Oper = Operators.begin(), 7843 OperEnd = Operators.end(); 7844 Oper != OperEnd; 7845 ++Oper) 7846 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7847 Args[0]->Classify(Context), Args.slice(1), 7848 CandidateSet, /*SuppressUserConversion=*/false, PO); 7849 } 7850 } 7851 7852 /// AddBuiltinCandidate - Add a candidate for a built-in 7853 /// operator. ResultTy and ParamTys are the result and parameter types 7854 /// of the built-in candidate, respectively. Args and NumArgs are the 7855 /// arguments being passed to the candidate. IsAssignmentOperator 7856 /// should be true when this built-in candidate is an assignment 7857 /// operator. NumContextualBoolArguments is the number of arguments 7858 /// (at the beginning of the argument list) that will be contextually 7859 /// converted to bool. 7860 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7861 OverloadCandidateSet& CandidateSet, 7862 bool IsAssignmentOperator, 7863 unsigned NumContextualBoolArguments) { 7864 // Overload resolution is always an unevaluated context. 7865 EnterExpressionEvaluationContext Unevaluated( 7866 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7867 7868 // Add this candidate 7869 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7870 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7871 Candidate.Function = nullptr; 7872 Candidate.IsSurrogate = false; 7873 Candidate.IgnoreObjectArgument = false; 7874 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7875 7876 // Determine the implicit conversion sequences for each of the 7877 // arguments. 7878 Candidate.Viable = true; 7879 Candidate.ExplicitCallArguments = Args.size(); 7880 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7881 // C++ [over.match.oper]p4: 7882 // For the built-in assignment operators, conversions of the 7883 // left operand are restricted as follows: 7884 // -- no temporaries are introduced to hold the left operand, and 7885 // -- no user-defined conversions are applied to the left 7886 // operand to achieve a type match with the left-most 7887 // parameter of a built-in candidate. 7888 // 7889 // We block these conversions by turning off user-defined 7890 // conversions, since that is the only way that initialization of 7891 // a reference to a non-class type can occur from something that 7892 // is not of the same type. 7893 if (ArgIdx < NumContextualBoolArguments) { 7894 assert(ParamTys[ArgIdx] == Context.BoolTy && 7895 "Contextual conversion to bool requires bool type"); 7896 Candidate.Conversions[ArgIdx] 7897 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7898 } else { 7899 Candidate.Conversions[ArgIdx] 7900 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7901 ArgIdx == 0 && IsAssignmentOperator, 7902 /*InOverloadResolution=*/false, 7903 /*AllowObjCWritebackConversion=*/ 7904 getLangOpts().ObjCAutoRefCount); 7905 } 7906 if (Candidate.Conversions[ArgIdx].isBad()) { 7907 Candidate.Viable = false; 7908 Candidate.FailureKind = ovl_fail_bad_conversion; 7909 break; 7910 } 7911 } 7912 } 7913 7914 namespace { 7915 7916 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7917 /// candidate operator functions for built-in operators (C++ 7918 /// [over.built]). The types are separated into pointer types and 7919 /// enumeration types. 7920 class BuiltinCandidateTypeSet { 7921 /// TypeSet - A set of types. 7922 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7923 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7924 7925 /// PointerTypes - The set of pointer types that will be used in the 7926 /// built-in candidates. 7927 TypeSet PointerTypes; 7928 7929 /// MemberPointerTypes - The set of member pointer types that will be 7930 /// used in the built-in candidates. 7931 TypeSet MemberPointerTypes; 7932 7933 /// EnumerationTypes - The set of enumeration types that will be 7934 /// used in the built-in candidates. 7935 TypeSet EnumerationTypes; 7936 7937 /// The set of vector types that will be used in the built-in 7938 /// candidates. 7939 TypeSet VectorTypes; 7940 7941 /// The set of matrix types that will be used in the built-in 7942 /// candidates. 7943 TypeSet MatrixTypes; 7944 7945 /// A flag indicating non-record types are viable candidates 7946 bool HasNonRecordTypes; 7947 7948 /// A flag indicating whether either arithmetic or enumeration types 7949 /// were present in the candidate set. 7950 bool HasArithmeticOrEnumeralTypes; 7951 7952 /// A flag indicating whether the nullptr type was present in the 7953 /// candidate set. 7954 bool HasNullPtrType; 7955 7956 /// Sema - The semantic analysis instance where we are building the 7957 /// candidate type set. 7958 Sema &SemaRef; 7959 7960 /// Context - The AST context in which we will build the type sets. 7961 ASTContext &Context; 7962 7963 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7964 const Qualifiers &VisibleQuals); 7965 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7966 7967 public: 7968 /// iterator - Iterates through the types that are part of the set. 7969 typedef TypeSet::iterator iterator; 7970 7971 BuiltinCandidateTypeSet(Sema &SemaRef) 7972 : HasNonRecordTypes(false), 7973 HasArithmeticOrEnumeralTypes(false), 7974 HasNullPtrType(false), 7975 SemaRef(SemaRef), 7976 Context(SemaRef.Context) { } 7977 7978 void AddTypesConvertedFrom(QualType Ty, 7979 SourceLocation Loc, 7980 bool AllowUserConversions, 7981 bool AllowExplicitConversions, 7982 const Qualifiers &VisibleTypeConversionsQuals); 7983 7984 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7985 llvm::iterator_range<iterator> member_pointer_types() { 7986 return MemberPointerTypes; 7987 } 7988 llvm::iterator_range<iterator> enumeration_types() { 7989 return EnumerationTypes; 7990 } 7991 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7992 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7993 7994 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7995 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7996 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7997 bool hasNullPtrType() const { return HasNullPtrType; } 7998 }; 7999 8000 } // end anonymous namespace 8001 8002 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 8003 /// the set of pointer types along with any more-qualified variants of 8004 /// that type. For example, if @p Ty is "int const *", this routine 8005 /// will add "int const *", "int const volatile *", "int const 8006 /// restrict *", and "int const volatile restrict *" to the set of 8007 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8008 /// false otherwise. 8009 /// 8010 /// FIXME: what to do about extended qualifiers? 8011 bool 8012 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8013 const Qualifiers &VisibleQuals) { 8014 8015 // Insert this type. 8016 if (!PointerTypes.insert(Ty)) 8017 return false; 8018 8019 QualType PointeeTy; 8020 const PointerType *PointerTy = Ty->getAs<PointerType>(); 8021 bool buildObjCPtr = false; 8022 if (!PointerTy) { 8023 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 8024 PointeeTy = PTy->getPointeeType(); 8025 buildObjCPtr = true; 8026 } else { 8027 PointeeTy = PointerTy->getPointeeType(); 8028 } 8029 8030 // Don't add qualified variants of arrays. For one, they're not allowed 8031 // (the qualifier would sink to the element type), and for another, the 8032 // only overload situation where it matters is subscript or pointer +- int, 8033 // and those shouldn't have qualifier variants anyway. 8034 if (PointeeTy->isArrayType()) 8035 return true; 8036 8037 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8038 bool hasVolatile = VisibleQuals.hasVolatile(); 8039 bool hasRestrict = VisibleQuals.hasRestrict(); 8040 8041 // Iterate through all strict supersets of BaseCVR. 8042 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8043 if ((CVR | BaseCVR) != CVR) continue; 8044 // Skip over volatile if no volatile found anywhere in the types. 8045 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 8046 8047 // Skip over restrict if no restrict found anywhere in the types, or if 8048 // the type cannot be restrict-qualified. 8049 if ((CVR & Qualifiers::Restrict) && 8050 (!hasRestrict || 8051 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 8052 continue; 8053 8054 // Build qualified pointee type. 8055 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8056 8057 // Build qualified pointer type. 8058 QualType QPointerTy; 8059 if (!buildObjCPtr) 8060 QPointerTy = Context.getPointerType(QPointeeTy); 8061 else 8062 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 8063 8064 // Insert qualified pointer type. 8065 PointerTypes.insert(QPointerTy); 8066 } 8067 8068 return true; 8069 } 8070 8071 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 8072 /// to the set of pointer types along with any more-qualified variants of 8073 /// that type. For example, if @p Ty is "int const *", this routine 8074 /// will add "int const *", "int const volatile *", "int const 8075 /// restrict *", and "int const volatile restrict *" to the set of 8076 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8077 /// false otherwise. 8078 /// 8079 /// FIXME: what to do about extended qualifiers? 8080 bool 8081 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 8082 QualType Ty) { 8083 // Insert this type. 8084 if (!MemberPointerTypes.insert(Ty)) 8085 return false; 8086 8087 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8088 assert(PointerTy && "type was not a member pointer type!"); 8089 8090 QualType PointeeTy = PointerTy->getPointeeType(); 8091 // Don't add qualified variants of arrays. For one, they're not allowed 8092 // (the qualifier would sink to the element type), and for another, the 8093 // only overload situation where it matters is subscript or pointer +- int, 8094 // and those shouldn't have qualifier variants anyway. 8095 if (PointeeTy->isArrayType()) 8096 return true; 8097 const Type *ClassTy = PointerTy->getClass(); 8098 8099 // Iterate through all strict supersets of the pointee type's CVR 8100 // qualifiers. 8101 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8102 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8103 if ((CVR | BaseCVR) != CVR) continue; 8104 8105 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8106 MemberPointerTypes.insert( 8107 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8108 } 8109 8110 return true; 8111 } 8112 8113 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8114 /// Ty can be implicit converted to the given set of @p Types. We're 8115 /// primarily interested in pointer types and enumeration types. We also 8116 /// take member pointer types, for the conditional operator. 8117 /// AllowUserConversions is true if we should look at the conversion 8118 /// functions of a class type, and AllowExplicitConversions if we 8119 /// should also include the explicit conversion functions of a class 8120 /// type. 8121 void 8122 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8123 SourceLocation Loc, 8124 bool AllowUserConversions, 8125 bool AllowExplicitConversions, 8126 const Qualifiers &VisibleQuals) { 8127 // Only deal with canonical types. 8128 Ty = Context.getCanonicalType(Ty); 8129 8130 // Look through reference types; they aren't part of the type of an 8131 // expression for the purposes of conversions. 8132 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8133 Ty = RefTy->getPointeeType(); 8134 8135 // If we're dealing with an array type, decay to the pointer. 8136 if (Ty->isArrayType()) 8137 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8138 8139 // Otherwise, we don't care about qualifiers on the type. 8140 Ty = Ty.getLocalUnqualifiedType(); 8141 8142 // Flag if we ever add a non-record type. 8143 const RecordType *TyRec = Ty->getAs<RecordType>(); 8144 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8145 8146 // Flag if we encounter an arithmetic type. 8147 HasArithmeticOrEnumeralTypes = 8148 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8149 8150 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8151 PointerTypes.insert(Ty); 8152 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8153 // Insert our type, and its more-qualified variants, into the set 8154 // of types. 8155 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8156 return; 8157 } else if (Ty->isMemberPointerType()) { 8158 // Member pointers are far easier, since the pointee can't be converted. 8159 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8160 return; 8161 } else if (Ty->isEnumeralType()) { 8162 HasArithmeticOrEnumeralTypes = true; 8163 EnumerationTypes.insert(Ty); 8164 } else if (Ty->isVectorType()) { 8165 // We treat vector types as arithmetic types in many contexts as an 8166 // extension. 8167 HasArithmeticOrEnumeralTypes = true; 8168 VectorTypes.insert(Ty); 8169 } else if (Ty->isMatrixType()) { 8170 // Similar to vector types, we treat vector types as arithmetic types in 8171 // many contexts as an extension. 8172 HasArithmeticOrEnumeralTypes = true; 8173 MatrixTypes.insert(Ty); 8174 } else if (Ty->isNullPtrType()) { 8175 HasNullPtrType = true; 8176 } else if (AllowUserConversions && TyRec) { 8177 // No conversion functions in incomplete types. 8178 if (!SemaRef.isCompleteType(Loc, Ty)) 8179 return; 8180 8181 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8182 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8183 if (isa<UsingShadowDecl>(D)) 8184 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8185 8186 // Skip conversion function templates; they don't tell us anything 8187 // about which builtin types we can convert to. 8188 if (isa<FunctionTemplateDecl>(D)) 8189 continue; 8190 8191 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8192 if (AllowExplicitConversions || !Conv->isExplicit()) { 8193 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8194 VisibleQuals); 8195 } 8196 } 8197 } 8198 } 8199 /// Helper function for adjusting address spaces for the pointer or reference 8200 /// operands of builtin operators depending on the argument. 8201 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8202 Expr *Arg) { 8203 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8204 } 8205 8206 /// Helper function for AddBuiltinOperatorCandidates() that adds 8207 /// the volatile- and non-volatile-qualified assignment operators for the 8208 /// given type to the candidate set. 8209 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8210 QualType T, 8211 ArrayRef<Expr *> Args, 8212 OverloadCandidateSet &CandidateSet) { 8213 QualType ParamTypes[2]; 8214 8215 // T& operator=(T&, T) 8216 ParamTypes[0] = S.Context.getLValueReferenceType( 8217 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8218 ParamTypes[1] = T; 8219 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8220 /*IsAssignmentOperator=*/true); 8221 8222 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8223 // volatile T& operator=(volatile T&, T) 8224 ParamTypes[0] = S.Context.getLValueReferenceType( 8225 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8226 Args[0])); 8227 ParamTypes[1] = T; 8228 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8229 /*IsAssignmentOperator=*/true); 8230 } 8231 } 8232 8233 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8234 /// if any, found in visible type conversion functions found in ArgExpr's type. 8235 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8236 Qualifiers VRQuals; 8237 const RecordType *TyRec; 8238 if (const MemberPointerType *RHSMPType = 8239 ArgExpr->getType()->getAs<MemberPointerType>()) 8240 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8241 else 8242 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8243 if (!TyRec) { 8244 // Just to be safe, assume the worst case. 8245 VRQuals.addVolatile(); 8246 VRQuals.addRestrict(); 8247 return VRQuals; 8248 } 8249 8250 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8251 if (!ClassDecl->hasDefinition()) 8252 return VRQuals; 8253 8254 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8255 if (isa<UsingShadowDecl>(D)) 8256 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8257 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8258 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8259 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8260 CanTy = ResTypeRef->getPointeeType(); 8261 // Need to go down the pointer/mempointer chain and add qualifiers 8262 // as see them. 8263 bool done = false; 8264 while (!done) { 8265 if (CanTy.isRestrictQualified()) 8266 VRQuals.addRestrict(); 8267 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8268 CanTy = ResTypePtr->getPointeeType(); 8269 else if (const MemberPointerType *ResTypeMPtr = 8270 CanTy->getAs<MemberPointerType>()) 8271 CanTy = ResTypeMPtr->getPointeeType(); 8272 else 8273 done = true; 8274 if (CanTy.isVolatileQualified()) 8275 VRQuals.addVolatile(); 8276 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8277 return VRQuals; 8278 } 8279 } 8280 } 8281 return VRQuals; 8282 } 8283 8284 // Note: We're currently only handling qualifiers that are meaningful for the 8285 // LHS of compound assignment overloading. 8286 static void forAllQualifierCombinationsImpl( 8287 QualifiersAndAtomic Available, QualifiersAndAtomic Applied, 8288 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8289 // _Atomic 8290 if (Available.hasAtomic()) { 8291 Available.removeAtomic(); 8292 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); 8293 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8294 return; 8295 } 8296 8297 // volatile 8298 if (Available.hasVolatile()) { 8299 Available.removeVolatile(); 8300 assert(!Applied.hasVolatile()); 8301 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), 8302 Callback); 8303 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8304 return; 8305 } 8306 8307 Callback(Applied); 8308 } 8309 8310 static void forAllQualifierCombinations( 8311 QualifiersAndAtomic Quals, 8312 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8313 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), 8314 Callback); 8315 } 8316 8317 static QualType makeQualifiedLValueReferenceType(QualType Base, 8318 QualifiersAndAtomic Quals, 8319 Sema &S) { 8320 if (Quals.hasAtomic()) 8321 Base = S.Context.getAtomicType(Base); 8322 if (Quals.hasVolatile()) 8323 Base = S.Context.getVolatileType(Base); 8324 return S.Context.getLValueReferenceType(Base); 8325 } 8326 8327 namespace { 8328 8329 /// Helper class to manage the addition of builtin operator overload 8330 /// candidates. It provides shared state and utility methods used throughout 8331 /// the process, as well as a helper method to add each group of builtin 8332 /// operator overloads from the standard to a candidate set. 8333 class BuiltinOperatorOverloadBuilder { 8334 // Common instance state available to all overload candidate addition methods. 8335 Sema &S; 8336 ArrayRef<Expr *> Args; 8337 QualifiersAndAtomic VisibleTypeConversionsQuals; 8338 bool HasArithmeticOrEnumeralCandidateType; 8339 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8340 OverloadCandidateSet &CandidateSet; 8341 8342 static constexpr int ArithmeticTypesCap = 24; 8343 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8344 8345 // Define some indices used to iterate over the arithmetic types in 8346 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8347 // types are that preserved by promotion (C++ [over.built]p2). 8348 unsigned FirstIntegralType, 8349 LastIntegralType; 8350 unsigned FirstPromotedIntegralType, 8351 LastPromotedIntegralType; 8352 unsigned FirstPromotedArithmeticType, 8353 LastPromotedArithmeticType; 8354 unsigned NumArithmeticTypes; 8355 8356 void InitArithmeticTypes() { 8357 // Start of promoted types. 8358 FirstPromotedArithmeticType = 0; 8359 ArithmeticTypes.push_back(S.Context.FloatTy); 8360 ArithmeticTypes.push_back(S.Context.DoubleTy); 8361 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8362 if (S.Context.getTargetInfo().hasFloat128Type()) 8363 ArithmeticTypes.push_back(S.Context.Float128Ty); 8364 if (S.Context.getTargetInfo().hasIbm128Type()) 8365 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8366 8367 // Start of integral types. 8368 FirstIntegralType = ArithmeticTypes.size(); 8369 FirstPromotedIntegralType = ArithmeticTypes.size(); 8370 ArithmeticTypes.push_back(S.Context.IntTy); 8371 ArithmeticTypes.push_back(S.Context.LongTy); 8372 ArithmeticTypes.push_back(S.Context.LongLongTy); 8373 if (S.Context.getTargetInfo().hasInt128Type() || 8374 (S.Context.getAuxTargetInfo() && 8375 S.Context.getAuxTargetInfo()->hasInt128Type())) 8376 ArithmeticTypes.push_back(S.Context.Int128Ty); 8377 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8378 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8379 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8380 if (S.Context.getTargetInfo().hasInt128Type() || 8381 (S.Context.getAuxTargetInfo() && 8382 S.Context.getAuxTargetInfo()->hasInt128Type())) 8383 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8384 LastPromotedIntegralType = ArithmeticTypes.size(); 8385 LastPromotedArithmeticType = ArithmeticTypes.size(); 8386 // End of promoted types. 8387 8388 ArithmeticTypes.push_back(S.Context.BoolTy); 8389 ArithmeticTypes.push_back(S.Context.CharTy); 8390 ArithmeticTypes.push_back(S.Context.WCharTy); 8391 if (S.Context.getLangOpts().Char8) 8392 ArithmeticTypes.push_back(S.Context.Char8Ty); 8393 ArithmeticTypes.push_back(S.Context.Char16Ty); 8394 ArithmeticTypes.push_back(S.Context.Char32Ty); 8395 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8396 ArithmeticTypes.push_back(S.Context.ShortTy); 8397 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8398 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8399 LastIntegralType = ArithmeticTypes.size(); 8400 NumArithmeticTypes = ArithmeticTypes.size(); 8401 // End of integral types. 8402 // FIXME: What about complex? What about half? 8403 8404 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8405 "Enough inline storage for all arithmetic types."); 8406 } 8407 8408 /// Helper method to factor out the common pattern of adding overloads 8409 /// for '++' and '--' builtin operators. 8410 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8411 bool HasVolatile, 8412 bool HasRestrict) { 8413 QualType ParamTypes[2] = { 8414 S.Context.getLValueReferenceType(CandidateTy), 8415 S.Context.IntTy 8416 }; 8417 8418 // Non-volatile version. 8419 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8420 8421 // Use a heuristic to reduce number of builtin candidates in the set: 8422 // add volatile version only if there are conversions to a volatile type. 8423 if (HasVolatile) { 8424 ParamTypes[0] = 8425 S.Context.getLValueReferenceType( 8426 S.Context.getVolatileType(CandidateTy)); 8427 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8428 } 8429 8430 // Add restrict version only if there are conversions to a restrict type 8431 // and our candidate type is a non-restrict-qualified pointer. 8432 if (HasRestrict && CandidateTy->isAnyPointerType() && 8433 !CandidateTy.isRestrictQualified()) { 8434 ParamTypes[0] 8435 = S.Context.getLValueReferenceType( 8436 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8437 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8438 8439 if (HasVolatile) { 8440 ParamTypes[0] 8441 = S.Context.getLValueReferenceType( 8442 S.Context.getCVRQualifiedType(CandidateTy, 8443 (Qualifiers::Volatile | 8444 Qualifiers::Restrict))); 8445 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8446 } 8447 } 8448 8449 } 8450 8451 /// Helper to add an overload candidate for a binary builtin with types \p L 8452 /// and \p R. 8453 void AddCandidate(QualType L, QualType R) { 8454 QualType LandR[2] = {L, R}; 8455 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8456 } 8457 8458 public: 8459 BuiltinOperatorOverloadBuilder( 8460 Sema &S, ArrayRef<Expr *> Args, 8461 QualifiersAndAtomic VisibleTypeConversionsQuals, 8462 bool HasArithmeticOrEnumeralCandidateType, 8463 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8464 OverloadCandidateSet &CandidateSet) 8465 : S(S), Args(Args), 8466 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8467 HasArithmeticOrEnumeralCandidateType( 8468 HasArithmeticOrEnumeralCandidateType), 8469 CandidateTypes(CandidateTypes), 8470 CandidateSet(CandidateSet) { 8471 8472 InitArithmeticTypes(); 8473 } 8474 8475 // Increment is deprecated for bool since C++17. 8476 // 8477 // C++ [over.built]p3: 8478 // 8479 // For every pair (T, VQ), where T is an arithmetic type other 8480 // than bool, and VQ is either volatile or empty, there exist 8481 // candidate operator functions of the form 8482 // 8483 // VQ T& operator++(VQ T&); 8484 // T operator++(VQ T&, int); 8485 // 8486 // C++ [over.built]p4: 8487 // 8488 // For every pair (T, VQ), where T is an arithmetic type other 8489 // than bool, and VQ is either volatile or empty, there exist 8490 // candidate operator functions of the form 8491 // 8492 // VQ T& operator--(VQ T&); 8493 // T operator--(VQ T&, int); 8494 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8495 if (!HasArithmeticOrEnumeralCandidateType) 8496 return; 8497 8498 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8499 const auto TypeOfT = ArithmeticTypes[Arith]; 8500 if (TypeOfT == S.Context.BoolTy) { 8501 if (Op == OO_MinusMinus) 8502 continue; 8503 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8504 continue; 8505 } 8506 addPlusPlusMinusMinusStyleOverloads( 8507 TypeOfT, 8508 VisibleTypeConversionsQuals.hasVolatile(), 8509 VisibleTypeConversionsQuals.hasRestrict()); 8510 } 8511 } 8512 8513 // C++ [over.built]p5: 8514 // 8515 // For every pair (T, VQ), where T is a cv-qualified or 8516 // cv-unqualified object type, and VQ is either volatile or 8517 // empty, there exist candidate operator functions of the form 8518 // 8519 // T*VQ& operator++(T*VQ&); 8520 // T*VQ& operator--(T*VQ&); 8521 // T* operator++(T*VQ&, int); 8522 // T* operator--(T*VQ&, int); 8523 void addPlusPlusMinusMinusPointerOverloads() { 8524 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8525 // Skip pointer types that aren't pointers to object types. 8526 if (!PtrTy->getPointeeType()->isObjectType()) 8527 continue; 8528 8529 addPlusPlusMinusMinusStyleOverloads( 8530 PtrTy, 8531 (!PtrTy.isVolatileQualified() && 8532 VisibleTypeConversionsQuals.hasVolatile()), 8533 (!PtrTy.isRestrictQualified() && 8534 VisibleTypeConversionsQuals.hasRestrict())); 8535 } 8536 } 8537 8538 // C++ [over.built]p6: 8539 // For every cv-qualified or cv-unqualified object type T, there 8540 // exist candidate operator functions of the form 8541 // 8542 // T& operator*(T*); 8543 // 8544 // C++ [over.built]p7: 8545 // For every function type T that does not have cv-qualifiers or a 8546 // ref-qualifier, there exist candidate operator functions of the form 8547 // T& operator*(T*); 8548 void addUnaryStarPointerOverloads() { 8549 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8550 QualType PointeeTy = ParamTy->getPointeeType(); 8551 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8552 continue; 8553 8554 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8555 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8556 continue; 8557 8558 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8559 } 8560 } 8561 8562 // C++ [over.built]p9: 8563 // For every promoted arithmetic type T, there exist candidate 8564 // operator functions of the form 8565 // 8566 // T operator+(T); 8567 // T operator-(T); 8568 void addUnaryPlusOrMinusArithmeticOverloads() { 8569 if (!HasArithmeticOrEnumeralCandidateType) 8570 return; 8571 8572 for (unsigned Arith = FirstPromotedArithmeticType; 8573 Arith < LastPromotedArithmeticType; ++Arith) { 8574 QualType ArithTy = ArithmeticTypes[Arith]; 8575 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8576 } 8577 8578 // Extension: We also add these operators for vector types. 8579 for (QualType VecTy : CandidateTypes[0].vector_types()) 8580 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8581 } 8582 8583 // C++ [over.built]p8: 8584 // For every type T, there exist candidate operator functions of 8585 // the form 8586 // 8587 // T* operator+(T*); 8588 void addUnaryPlusPointerOverloads() { 8589 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8590 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8591 } 8592 8593 // C++ [over.built]p10: 8594 // For every promoted integral type T, there exist candidate 8595 // operator functions of the form 8596 // 8597 // T operator~(T); 8598 void addUnaryTildePromotedIntegralOverloads() { 8599 if (!HasArithmeticOrEnumeralCandidateType) 8600 return; 8601 8602 for (unsigned Int = FirstPromotedIntegralType; 8603 Int < LastPromotedIntegralType; ++Int) { 8604 QualType IntTy = ArithmeticTypes[Int]; 8605 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8606 } 8607 8608 // Extension: We also add this operator for vector types. 8609 for (QualType VecTy : CandidateTypes[0].vector_types()) 8610 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8611 } 8612 8613 // C++ [over.match.oper]p16: 8614 // For every pointer to member type T or type std::nullptr_t, there 8615 // exist candidate operator functions of the form 8616 // 8617 // bool operator==(T,T); 8618 // bool operator!=(T,T); 8619 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8620 /// Set of (canonical) types that we've already handled. 8621 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8622 8623 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8624 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8625 // Don't add the same builtin candidate twice. 8626 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8627 continue; 8628 8629 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8630 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8631 } 8632 8633 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8634 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8635 if (AddedTypes.insert(NullPtrTy).second) { 8636 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8638 } 8639 } 8640 } 8641 } 8642 8643 // C++ [over.built]p15: 8644 // 8645 // For every T, where T is an enumeration type or a pointer type, 8646 // there exist candidate operator functions of the form 8647 // 8648 // bool operator<(T, T); 8649 // bool operator>(T, T); 8650 // bool operator<=(T, T); 8651 // bool operator>=(T, T); 8652 // bool operator==(T, T); 8653 // bool operator!=(T, T); 8654 // R operator<=>(T, T) 8655 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 8656 // C++ [over.match.oper]p3: 8657 // [...]the built-in candidates include all of the candidate operator 8658 // functions defined in 13.6 that, compared to the given operator, [...] 8659 // do not have the same parameter-type-list as any non-template non-member 8660 // candidate. 8661 // 8662 // Note that in practice, this only affects enumeration types because there 8663 // aren't any built-in candidates of record type, and a user-defined operator 8664 // must have an operand of record or enumeration type. Also, the only other 8665 // overloaded operator with enumeration arguments, operator=, 8666 // cannot be overloaded for enumeration types, so this is the only place 8667 // where we must suppress candidates like this. 8668 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8669 UserDefinedBinaryOperators; 8670 8671 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8672 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8673 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8674 CEnd = CandidateSet.end(); 8675 C != CEnd; ++C) { 8676 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8677 continue; 8678 8679 if (C->Function->isFunctionTemplateSpecialization()) 8680 continue; 8681 8682 // We interpret "same parameter-type-list" as applying to the 8683 // "synthesized candidate, with the order of the two parameters 8684 // reversed", not to the original function. 8685 bool Reversed = C->isReversed(); 8686 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8687 ->getType() 8688 .getUnqualifiedType(); 8689 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8690 ->getType() 8691 .getUnqualifiedType(); 8692 8693 // Skip if either parameter isn't of enumeral type. 8694 if (!FirstParamType->isEnumeralType() || 8695 !SecondParamType->isEnumeralType()) 8696 continue; 8697 8698 // Add this operator to the set of known user-defined operators. 8699 UserDefinedBinaryOperators.insert( 8700 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8701 S.Context.getCanonicalType(SecondParamType))); 8702 } 8703 } 8704 } 8705 8706 /// Set of (canonical) types that we've already handled. 8707 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8708 8709 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8710 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8711 // Don't add the same builtin candidate twice. 8712 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8713 continue; 8714 if (IsSpaceship && PtrTy->isFunctionPointerType()) 8715 continue; 8716 8717 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8718 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8719 } 8720 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8721 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8722 8723 // Don't add the same builtin candidate twice, or if a user defined 8724 // candidate exists. 8725 if (!AddedTypes.insert(CanonType).second || 8726 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8727 CanonType))) 8728 continue; 8729 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8730 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8731 } 8732 } 8733 } 8734 8735 // C++ [over.built]p13: 8736 // 8737 // For every cv-qualified or cv-unqualified object type T 8738 // there exist candidate operator functions of the form 8739 // 8740 // T* operator+(T*, ptrdiff_t); 8741 // T& operator[](T*, ptrdiff_t); [BELOW] 8742 // T* operator-(T*, ptrdiff_t); 8743 // T* operator+(ptrdiff_t, T*); 8744 // T& operator[](ptrdiff_t, T*); [BELOW] 8745 // 8746 // C++ [over.built]p14: 8747 // 8748 // For every T, where T is a pointer to object type, there 8749 // exist candidate operator functions of the form 8750 // 8751 // ptrdiff_t operator-(T, T); 8752 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8753 /// Set of (canonical) types that we've already handled. 8754 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8755 8756 for (int Arg = 0; Arg < 2; ++Arg) { 8757 QualType AsymmetricParamTypes[2] = { 8758 S.Context.getPointerDiffType(), 8759 S.Context.getPointerDiffType(), 8760 }; 8761 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8762 QualType PointeeTy = PtrTy->getPointeeType(); 8763 if (!PointeeTy->isObjectType()) 8764 continue; 8765 8766 AsymmetricParamTypes[Arg] = PtrTy; 8767 if (Arg == 0 || Op == OO_Plus) { 8768 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8769 // T* operator+(ptrdiff_t, T*); 8770 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8771 } 8772 if (Op == OO_Minus) { 8773 // ptrdiff_t operator-(T, T); 8774 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8775 continue; 8776 8777 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8778 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8779 } 8780 } 8781 } 8782 } 8783 8784 // C++ [over.built]p12: 8785 // 8786 // For every pair of promoted arithmetic types L and R, there 8787 // exist candidate operator functions of the form 8788 // 8789 // LR operator*(L, R); 8790 // LR operator/(L, R); 8791 // LR operator+(L, R); 8792 // LR operator-(L, R); 8793 // bool operator<(L, R); 8794 // bool operator>(L, R); 8795 // bool operator<=(L, R); 8796 // bool operator>=(L, R); 8797 // bool operator==(L, R); 8798 // bool operator!=(L, R); 8799 // 8800 // where LR is the result of the usual arithmetic conversions 8801 // between types L and R. 8802 // 8803 // C++ [over.built]p24: 8804 // 8805 // For every pair of promoted arithmetic types L and R, there exist 8806 // candidate operator functions of the form 8807 // 8808 // LR operator?(bool, L, R); 8809 // 8810 // where LR is the result of the usual arithmetic conversions 8811 // between types L and R. 8812 // Our candidates ignore the first parameter. 8813 void addGenericBinaryArithmeticOverloads() { 8814 if (!HasArithmeticOrEnumeralCandidateType) 8815 return; 8816 8817 for (unsigned Left = FirstPromotedArithmeticType; 8818 Left < LastPromotedArithmeticType; ++Left) { 8819 for (unsigned Right = FirstPromotedArithmeticType; 8820 Right < LastPromotedArithmeticType; ++Right) { 8821 QualType LandR[2] = { ArithmeticTypes[Left], 8822 ArithmeticTypes[Right] }; 8823 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8824 } 8825 } 8826 8827 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8828 // conditional operator for vector types. 8829 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8830 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8831 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8832 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8833 } 8834 } 8835 8836 /// Add binary operator overloads for each candidate matrix type M1, M2: 8837 /// * (M1, M1) -> M1 8838 /// * (M1, M1.getElementType()) -> M1 8839 /// * (M2.getElementType(), M2) -> M2 8840 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8841 void addMatrixBinaryArithmeticOverloads() { 8842 if (!HasArithmeticOrEnumeralCandidateType) 8843 return; 8844 8845 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8846 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8847 AddCandidate(M1, M1); 8848 } 8849 8850 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8851 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8852 if (!CandidateTypes[0].containsMatrixType(M2)) 8853 AddCandidate(M2, M2); 8854 } 8855 } 8856 8857 // C++2a [over.built]p14: 8858 // 8859 // For every integral type T there exists a candidate operator function 8860 // of the form 8861 // 8862 // std::strong_ordering operator<=>(T, T) 8863 // 8864 // C++2a [over.built]p15: 8865 // 8866 // For every pair of floating-point types L and R, there exists a candidate 8867 // operator function of the form 8868 // 8869 // std::partial_ordering operator<=>(L, R); 8870 // 8871 // FIXME: The current specification for integral types doesn't play nice with 8872 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8873 // comparisons. Under the current spec this can lead to ambiguity during 8874 // overload resolution. For example: 8875 // 8876 // enum A : int {a}; 8877 // auto x = (a <=> (long)42); 8878 // 8879 // error: call is ambiguous for arguments 'A' and 'long'. 8880 // note: candidate operator<=>(int, int) 8881 // note: candidate operator<=>(long, long) 8882 // 8883 // To avoid this error, this function deviates from the specification and adds 8884 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8885 // arithmetic types (the same as the generic relational overloads). 8886 // 8887 // For now this function acts as a placeholder. 8888 void addThreeWayArithmeticOverloads() { 8889 addGenericBinaryArithmeticOverloads(); 8890 } 8891 8892 // C++ [over.built]p17: 8893 // 8894 // For every pair of promoted integral types L and R, there 8895 // exist candidate operator functions of the form 8896 // 8897 // LR operator%(L, R); 8898 // LR operator&(L, R); 8899 // LR operator^(L, R); 8900 // LR operator|(L, R); 8901 // L operator<<(L, R); 8902 // L operator>>(L, R); 8903 // 8904 // where LR is the result of the usual arithmetic conversions 8905 // between types L and R. 8906 void addBinaryBitwiseArithmeticOverloads() { 8907 if (!HasArithmeticOrEnumeralCandidateType) 8908 return; 8909 8910 for (unsigned Left = FirstPromotedIntegralType; 8911 Left < LastPromotedIntegralType; ++Left) { 8912 for (unsigned Right = FirstPromotedIntegralType; 8913 Right < LastPromotedIntegralType; ++Right) { 8914 QualType LandR[2] = { ArithmeticTypes[Left], 8915 ArithmeticTypes[Right] }; 8916 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8917 } 8918 } 8919 } 8920 8921 // C++ [over.built]p20: 8922 // 8923 // For every pair (T, VQ), where T is an enumeration or 8924 // pointer to member type and VQ is either volatile or 8925 // empty, there exist candidate operator functions of the form 8926 // 8927 // VQ T& operator=(VQ T&, T); 8928 void addAssignmentMemberPointerOrEnumeralOverloads() { 8929 /// Set of (canonical) types that we've already handled. 8930 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8931 8932 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8933 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8934 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8935 continue; 8936 8937 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8938 } 8939 8940 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8941 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8942 continue; 8943 8944 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8945 } 8946 } 8947 } 8948 8949 // C++ [over.built]p19: 8950 // 8951 // For every pair (T, VQ), where T is any type and VQ is either 8952 // volatile or empty, there exist candidate operator functions 8953 // of the form 8954 // 8955 // T*VQ& operator=(T*VQ&, T*); 8956 // 8957 // C++ [over.built]p21: 8958 // 8959 // For every pair (T, VQ), where T is a cv-qualified or 8960 // cv-unqualified object type and VQ is either volatile or 8961 // empty, there exist candidate operator functions of the form 8962 // 8963 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8964 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8965 void addAssignmentPointerOverloads(bool isEqualOp) { 8966 /// Set of (canonical) types that we've already handled. 8967 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8968 8969 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8970 // If this is operator=, keep track of the builtin candidates we added. 8971 if (isEqualOp) 8972 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8973 else if (!PtrTy->getPointeeType()->isObjectType()) 8974 continue; 8975 8976 // non-volatile version 8977 QualType ParamTypes[2] = { 8978 S.Context.getLValueReferenceType(PtrTy), 8979 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8980 }; 8981 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8982 /*IsAssignmentOperator=*/ isEqualOp); 8983 8984 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8985 VisibleTypeConversionsQuals.hasVolatile(); 8986 if (NeedVolatile) { 8987 // volatile version 8988 ParamTypes[0] = 8989 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8990 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8991 /*IsAssignmentOperator=*/isEqualOp); 8992 } 8993 8994 if (!PtrTy.isRestrictQualified() && 8995 VisibleTypeConversionsQuals.hasRestrict()) { 8996 // restrict version 8997 ParamTypes[0] = 8998 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8999 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9000 /*IsAssignmentOperator=*/isEqualOp); 9001 9002 if (NeedVolatile) { 9003 // volatile restrict version 9004 ParamTypes[0] = 9005 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9006 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9007 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9008 /*IsAssignmentOperator=*/isEqualOp); 9009 } 9010 } 9011 } 9012 9013 if (isEqualOp) { 9014 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9015 // Make sure we don't add the same candidate twice. 9016 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9017 continue; 9018 9019 QualType ParamTypes[2] = { 9020 S.Context.getLValueReferenceType(PtrTy), 9021 PtrTy, 9022 }; 9023 9024 // non-volatile version 9025 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9026 /*IsAssignmentOperator=*/true); 9027 9028 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9029 VisibleTypeConversionsQuals.hasVolatile(); 9030 if (NeedVolatile) { 9031 // volatile version 9032 ParamTypes[0] = S.Context.getLValueReferenceType( 9033 S.Context.getVolatileType(PtrTy)); 9034 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9035 /*IsAssignmentOperator=*/true); 9036 } 9037 9038 if (!PtrTy.isRestrictQualified() && 9039 VisibleTypeConversionsQuals.hasRestrict()) { 9040 // restrict version 9041 ParamTypes[0] = S.Context.getLValueReferenceType( 9042 S.Context.getRestrictType(PtrTy)); 9043 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9044 /*IsAssignmentOperator=*/true); 9045 9046 if (NeedVolatile) { 9047 // volatile restrict version 9048 ParamTypes[0] = 9049 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9050 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9051 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9052 /*IsAssignmentOperator=*/true); 9053 } 9054 } 9055 } 9056 } 9057 } 9058 9059 // C++ [over.built]p18: 9060 // 9061 // For every triple (L, VQ, R), where L is an arithmetic type, 9062 // VQ is either volatile or empty, and R is a promoted 9063 // arithmetic type, there exist candidate operator functions of 9064 // the form 9065 // 9066 // VQ L& operator=(VQ L&, R); 9067 // VQ L& operator*=(VQ L&, R); 9068 // VQ L& operator/=(VQ L&, R); 9069 // VQ L& operator+=(VQ L&, R); 9070 // VQ L& operator-=(VQ L&, R); 9071 void addAssignmentArithmeticOverloads(bool isEqualOp) { 9072 if (!HasArithmeticOrEnumeralCandidateType) 9073 return; 9074 9075 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 9076 for (unsigned Right = FirstPromotedArithmeticType; 9077 Right < LastPromotedArithmeticType; ++Right) { 9078 QualType ParamTypes[2]; 9079 ParamTypes[1] = ArithmeticTypes[Right]; 9080 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9081 S, ArithmeticTypes[Left], Args[0]); 9082 9083 forAllQualifierCombinations( 9084 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9085 ParamTypes[0] = 9086 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9087 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9088 /*IsAssignmentOperator=*/isEqualOp); 9089 }); 9090 } 9091 } 9092 9093 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 9094 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9095 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 9096 QualType ParamTypes[2]; 9097 ParamTypes[1] = Vec2Ty; 9098 // Add this built-in operator as a candidate (VQ is empty). 9099 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 9100 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9101 /*IsAssignmentOperator=*/isEqualOp); 9102 9103 // Add this built-in operator as a candidate (VQ is 'volatile'). 9104 if (VisibleTypeConversionsQuals.hasVolatile()) { 9105 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 9106 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9107 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9108 /*IsAssignmentOperator=*/isEqualOp); 9109 } 9110 } 9111 } 9112 9113 // C++ [over.built]p22: 9114 // 9115 // For every triple (L, VQ, R), where L is an integral type, VQ 9116 // is either volatile or empty, and R is a promoted integral 9117 // type, there exist candidate operator functions of the form 9118 // 9119 // VQ L& operator%=(VQ L&, R); 9120 // VQ L& operator<<=(VQ L&, R); 9121 // VQ L& operator>>=(VQ L&, R); 9122 // VQ L& operator&=(VQ L&, R); 9123 // VQ L& operator^=(VQ L&, R); 9124 // VQ L& operator|=(VQ L&, R); 9125 void addAssignmentIntegralOverloads() { 9126 if (!HasArithmeticOrEnumeralCandidateType) 9127 return; 9128 9129 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9130 for (unsigned Right = FirstPromotedIntegralType; 9131 Right < LastPromotedIntegralType; ++Right) { 9132 QualType ParamTypes[2]; 9133 ParamTypes[1] = ArithmeticTypes[Right]; 9134 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9135 S, ArithmeticTypes[Left], Args[0]); 9136 9137 forAllQualifierCombinations( 9138 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9139 ParamTypes[0] = 9140 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9141 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9142 }); 9143 } 9144 } 9145 } 9146 9147 // C++ [over.operator]p23: 9148 // 9149 // There also exist candidate operator functions of the form 9150 // 9151 // bool operator!(bool); 9152 // bool operator&&(bool, bool); 9153 // bool operator||(bool, bool); 9154 void addExclaimOverload() { 9155 QualType ParamTy = S.Context.BoolTy; 9156 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9157 /*IsAssignmentOperator=*/false, 9158 /*NumContextualBoolArguments=*/1); 9159 } 9160 void addAmpAmpOrPipePipeOverload() { 9161 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9162 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9163 /*IsAssignmentOperator=*/false, 9164 /*NumContextualBoolArguments=*/2); 9165 } 9166 9167 // C++ [over.built]p13: 9168 // 9169 // For every cv-qualified or cv-unqualified object type T there 9170 // exist candidate operator functions of the form 9171 // 9172 // T* operator+(T*, ptrdiff_t); [ABOVE] 9173 // T& operator[](T*, ptrdiff_t); 9174 // T* operator-(T*, ptrdiff_t); [ABOVE] 9175 // T* operator+(ptrdiff_t, T*); [ABOVE] 9176 // T& operator[](ptrdiff_t, T*); 9177 void addSubscriptOverloads() { 9178 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9179 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9180 QualType PointeeType = PtrTy->getPointeeType(); 9181 if (!PointeeType->isObjectType()) 9182 continue; 9183 9184 // T& operator[](T*, ptrdiff_t) 9185 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9186 } 9187 9188 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9189 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9190 QualType PointeeType = PtrTy->getPointeeType(); 9191 if (!PointeeType->isObjectType()) 9192 continue; 9193 9194 // T& operator[](ptrdiff_t, T*) 9195 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9196 } 9197 } 9198 9199 // C++ [over.built]p11: 9200 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9201 // C1 is the same type as C2 or is a derived class of C2, T is an object 9202 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9203 // there exist candidate operator functions of the form 9204 // 9205 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9206 // 9207 // where CV12 is the union of CV1 and CV2. 9208 void addArrowStarOverloads() { 9209 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9210 QualType C1Ty = PtrTy; 9211 QualType C1; 9212 QualifierCollector Q1; 9213 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9214 if (!isa<RecordType>(C1)) 9215 continue; 9216 // heuristic to reduce number of builtin candidates in the set. 9217 // Add volatile/restrict version only if there are conversions to a 9218 // volatile/restrict type. 9219 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9220 continue; 9221 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9222 continue; 9223 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9224 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9225 QualType C2 = QualType(mptr->getClass(), 0); 9226 C2 = C2.getUnqualifiedType(); 9227 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9228 break; 9229 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9230 // build CV12 T& 9231 QualType T = mptr->getPointeeType(); 9232 if (!VisibleTypeConversionsQuals.hasVolatile() && 9233 T.isVolatileQualified()) 9234 continue; 9235 if (!VisibleTypeConversionsQuals.hasRestrict() && 9236 T.isRestrictQualified()) 9237 continue; 9238 T = Q1.apply(S.Context, T); 9239 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9240 } 9241 } 9242 } 9243 9244 // Note that we don't consider the first argument, since it has been 9245 // contextually converted to bool long ago. The candidates below are 9246 // therefore added as binary. 9247 // 9248 // C++ [over.built]p25: 9249 // For every type T, where T is a pointer, pointer-to-member, or scoped 9250 // enumeration type, there exist candidate operator functions of the form 9251 // 9252 // T operator?(bool, T, T); 9253 // 9254 void addConditionalOperatorOverloads() { 9255 /// Set of (canonical) types that we've already handled. 9256 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9257 9258 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9259 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9260 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9261 continue; 9262 9263 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9264 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9265 } 9266 9267 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9268 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9269 continue; 9270 9271 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9272 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9273 } 9274 9275 if (S.getLangOpts().CPlusPlus11) { 9276 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9277 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9278 continue; 9279 9280 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9281 continue; 9282 9283 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9284 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9285 } 9286 } 9287 } 9288 } 9289 }; 9290 9291 } // end anonymous namespace 9292 9293 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9294 /// operator overloads to the candidate set (C++ [over.built]), based 9295 /// on the operator @p Op and the arguments given. For example, if the 9296 /// operator is a binary '+', this routine might add "int 9297 /// operator+(int, int)" to cover integer addition. 9298 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9299 SourceLocation OpLoc, 9300 ArrayRef<Expr *> Args, 9301 OverloadCandidateSet &CandidateSet) { 9302 // Find all of the types that the arguments can convert to, but only 9303 // if the operator we're looking at has built-in operator candidates 9304 // that make use of these types. Also record whether we encounter non-record 9305 // candidate types or either arithmetic or enumeral candidate types. 9306 QualifiersAndAtomic VisibleTypeConversionsQuals; 9307 VisibleTypeConversionsQuals.addConst(); 9308 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9309 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9310 if (Args[ArgIdx]->getType()->isAtomicType()) 9311 VisibleTypeConversionsQuals.addAtomic(); 9312 } 9313 9314 bool HasNonRecordCandidateType = false; 9315 bool HasArithmeticOrEnumeralCandidateType = false; 9316 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9317 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9318 CandidateTypes.emplace_back(*this); 9319 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9320 OpLoc, 9321 true, 9322 (Op == OO_Exclaim || 9323 Op == OO_AmpAmp || 9324 Op == OO_PipePipe), 9325 VisibleTypeConversionsQuals); 9326 HasNonRecordCandidateType = HasNonRecordCandidateType || 9327 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9328 HasArithmeticOrEnumeralCandidateType = 9329 HasArithmeticOrEnumeralCandidateType || 9330 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9331 } 9332 9333 // Exit early when no non-record types have been added to the candidate set 9334 // for any of the arguments to the operator. 9335 // 9336 // We can't exit early for !, ||, or &&, since there we have always have 9337 // 'bool' overloads. 9338 if (!HasNonRecordCandidateType && 9339 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9340 return; 9341 9342 // Setup an object to manage the common state for building overloads. 9343 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9344 VisibleTypeConversionsQuals, 9345 HasArithmeticOrEnumeralCandidateType, 9346 CandidateTypes, CandidateSet); 9347 9348 // Dispatch over the operation to add in only those overloads which apply. 9349 switch (Op) { 9350 case OO_None: 9351 case NUM_OVERLOADED_OPERATORS: 9352 llvm_unreachable("Expected an overloaded operator"); 9353 9354 case OO_New: 9355 case OO_Delete: 9356 case OO_Array_New: 9357 case OO_Array_Delete: 9358 case OO_Call: 9359 llvm_unreachable( 9360 "Special operators don't use AddBuiltinOperatorCandidates"); 9361 9362 case OO_Comma: 9363 case OO_Arrow: 9364 case OO_Coawait: 9365 // C++ [over.match.oper]p3: 9366 // -- For the operator ',', the unary operator '&', the 9367 // operator '->', or the operator 'co_await', the 9368 // built-in candidates set is empty. 9369 break; 9370 9371 case OO_Plus: // '+' is either unary or binary 9372 if (Args.size() == 1) 9373 OpBuilder.addUnaryPlusPointerOverloads(); 9374 LLVM_FALLTHROUGH; 9375 9376 case OO_Minus: // '-' is either unary or binary 9377 if (Args.size() == 1) { 9378 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9379 } else { 9380 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9381 OpBuilder.addGenericBinaryArithmeticOverloads(); 9382 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9383 } 9384 break; 9385 9386 case OO_Star: // '*' is either unary or binary 9387 if (Args.size() == 1) 9388 OpBuilder.addUnaryStarPointerOverloads(); 9389 else { 9390 OpBuilder.addGenericBinaryArithmeticOverloads(); 9391 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9392 } 9393 break; 9394 9395 case OO_Slash: 9396 OpBuilder.addGenericBinaryArithmeticOverloads(); 9397 break; 9398 9399 case OO_PlusPlus: 9400 case OO_MinusMinus: 9401 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9402 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9403 break; 9404 9405 case OO_EqualEqual: 9406 case OO_ExclaimEqual: 9407 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9408 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9409 OpBuilder.addGenericBinaryArithmeticOverloads(); 9410 break; 9411 9412 case OO_Less: 9413 case OO_Greater: 9414 case OO_LessEqual: 9415 case OO_GreaterEqual: 9416 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9417 OpBuilder.addGenericBinaryArithmeticOverloads(); 9418 break; 9419 9420 case OO_Spaceship: 9421 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9422 OpBuilder.addThreeWayArithmeticOverloads(); 9423 break; 9424 9425 case OO_Percent: 9426 case OO_Caret: 9427 case OO_Pipe: 9428 case OO_LessLess: 9429 case OO_GreaterGreater: 9430 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9431 break; 9432 9433 case OO_Amp: // '&' is either unary or binary 9434 if (Args.size() == 1) 9435 // C++ [over.match.oper]p3: 9436 // -- For the operator ',', the unary operator '&', or the 9437 // operator '->', the built-in candidates set is empty. 9438 break; 9439 9440 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9441 break; 9442 9443 case OO_Tilde: 9444 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9445 break; 9446 9447 case OO_Equal: 9448 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9449 LLVM_FALLTHROUGH; 9450 9451 case OO_PlusEqual: 9452 case OO_MinusEqual: 9453 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9454 LLVM_FALLTHROUGH; 9455 9456 case OO_StarEqual: 9457 case OO_SlashEqual: 9458 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9459 break; 9460 9461 case OO_PercentEqual: 9462 case OO_LessLessEqual: 9463 case OO_GreaterGreaterEqual: 9464 case OO_AmpEqual: 9465 case OO_CaretEqual: 9466 case OO_PipeEqual: 9467 OpBuilder.addAssignmentIntegralOverloads(); 9468 break; 9469 9470 case OO_Exclaim: 9471 OpBuilder.addExclaimOverload(); 9472 break; 9473 9474 case OO_AmpAmp: 9475 case OO_PipePipe: 9476 OpBuilder.addAmpAmpOrPipePipeOverload(); 9477 break; 9478 9479 case OO_Subscript: 9480 if (Args.size() == 2) 9481 OpBuilder.addSubscriptOverloads(); 9482 break; 9483 9484 case OO_ArrowStar: 9485 OpBuilder.addArrowStarOverloads(); 9486 break; 9487 9488 case OO_Conditional: 9489 OpBuilder.addConditionalOperatorOverloads(); 9490 OpBuilder.addGenericBinaryArithmeticOverloads(); 9491 break; 9492 } 9493 } 9494 9495 /// Add function candidates found via argument-dependent lookup 9496 /// to the set of overloading candidates. 9497 /// 9498 /// This routine performs argument-dependent name lookup based on the 9499 /// given function name (which may also be an operator name) and adds 9500 /// all of the overload candidates found by ADL to the overload 9501 /// candidate set (C++ [basic.lookup.argdep]). 9502 void 9503 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9504 SourceLocation Loc, 9505 ArrayRef<Expr *> Args, 9506 TemplateArgumentListInfo *ExplicitTemplateArgs, 9507 OverloadCandidateSet& CandidateSet, 9508 bool PartialOverloading) { 9509 ADLResult Fns; 9510 9511 // FIXME: This approach for uniquing ADL results (and removing 9512 // redundant candidates from the set) relies on pointer-equality, 9513 // which means we need to key off the canonical decl. However, 9514 // always going back to the canonical decl might not get us the 9515 // right set of default arguments. What default arguments are 9516 // we supposed to consider on ADL candidates, anyway? 9517 9518 // FIXME: Pass in the explicit template arguments? 9519 ArgumentDependentLookup(Name, Loc, Args, Fns); 9520 9521 // Erase all of the candidates we already knew about. 9522 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9523 CandEnd = CandidateSet.end(); 9524 Cand != CandEnd; ++Cand) 9525 if (Cand->Function) { 9526 Fns.erase(Cand->Function); 9527 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9528 Fns.erase(FunTmpl); 9529 } 9530 9531 // For each of the ADL candidates we found, add it to the overload 9532 // set. 9533 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9534 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9535 9536 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9537 if (ExplicitTemplateArgs) 9538 continue; 9539 9540 AddOverloadCandidate( 9541 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9542 PartialOverloading, /*AllowExplicit=*/true, 9543 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9544 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9545 AddOverloadCandidate( 9546 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9547 /*SuppressUserConversions=*/false, PartialOverloading, 9548 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9549 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9550 } 9551 } else { 9552 auto *FTD = cast<FunctionTemplateDecl>(*I); 9553 AddTemplateOverloadCandidate( 9554 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9555 /*SuppressUserConversions=*/false, PartialOverloading, 9556 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9557 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9558 Context, FTD->getTemplatedDecl())) { 9559 AddTemplateOverloadCandidate( 9560 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9561 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9562 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9563 OverloadCandidateParamOrder::Reversed); 9564 } 9565 } 9566 } 9567 } 9568 9569 namespace { 9570 enum class Comparison { Equal, Better, Worse }; 9571 } 9572 9573 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9574 /// overload resolution. 9575 /// 9576 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9577 /// Cand1's first N enable_if attributes have precisely the same conditions as 9578 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9579 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9580 /// 9581 /// Note that you can have a pair of candidates such that Cand1's enable_if 9582 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9583 /// worse than Cand1's. 9584 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9585 const FunctionDecl *Cand2) { 9586 // Common case: One (or both) decls don't have enable_if attrs. 9587 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9588 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9589 if (!Cand1Attr || !Cand2Attr) { 9590 if (Cand1Attr == Cand2Attr) 9591 return Comparison::Equal; 9592 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9593 } 9594 9595 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9596 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9597 9598 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9599 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9600 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9601 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9602 9603 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9604 // has fewer enable_if attributes than Cand2, and vice versa. 9605 if (!Cand1A) 9606 return Comparison::Worse; 9607 if (!Cand2A) 9608 return Comparison::Better; 9609 9610 Cand1ID.clear(); 9611 Cand2ID.clear(); 9612 9613 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9614 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9615 if (Cand1ID != Cand2ID) 9616 return Comparison::Worse; 9617 } 9618 9619 return Comparison::Equal; 9620 } 9621 9622 static Comparison 9623 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9624 const OverloadCandidate &Cand2) { 9625 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9626 !Cand2.Function->isMultiVersion()) 9627 return Comparison::Equal; 9628 9629 // If both are invalid, they are equal. If one of them is invalid, the other 9630 // is better. 9631 if (Cand1.Function->isInvalidDecl()) { 9632 if (Cand2.Function->isInvalidDecl()) 9633 return Comparison::Equal; 9634 return Comparison::Worse; 9635 } 9636 if (Cand2.Function->isInvalidDecl()) 9637 return Comparison::Better; 9638 9639 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9640 // cpu_dispatch, else arbitrarily based on the identifiers. 9641 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9642 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9643 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9644 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9645 9646 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9647 return Comparison::Equal; 9648 9649 if (Cand1CPUDisp && !Cand2CPUDisp) 9650 return Comparison::Better; 9651 if (Cand2CPUDisp && !Cand1CPUDisp) 9652 return Comparison::Worse; 9653 9654 if (Cand1CPUSpec && Cand2CPUSpec) { 9655 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9656 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9657 ? Comparison::Better 9658 : Comparison::Worse; 9659 9660 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9661 FirstDiff = std::mismatch( 9662 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9663 Cand2CPUSpec->cpus_begin(), 9664 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9665 return LHS->getName() == RHS->getName(); 9666 }); 9667 9668 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9669 "Two different cpu-specific versions should not have the same " 9670 "identifier list, otherwise they'd be the same decl!"); 9671 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9672 ? Comparison::Better 9673 : Comparison::Worse; 9674 } 9675 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9676 } 9677 9678 /// Compute the type of the implicit object parameter for the given function, 9679 /// if any. Returns None if there is no implicit object parameter, and a null 9680 /// QualType if there is a 'matches anything' implicit object parameter. 9681 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9682 const FunctionDecl *F) { 9683 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9684 return llvm::None; 9685 9686 auto *M = cast<CXXMethodDecl>(F); 9687 // Static member functions' object parameters match all types. 9688 if (M->isStatic()) 9689 return QualType(); 9690 9691 QualType T = M->getThisObjectType(); 9692 if (M->getRefQualifier() == RQ_RValue) 9693 return Context.getRValueReferenceType(T); 9694 return Context.getLValueReferenceType(T); 9695 } 9696 9697 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9698 const FunctionDecl *F2, unsigned NumParams) { 9699 if (declaresSameEntity(F1, F2)) 9700 return true; 9701 9702 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9703 if (First) { 9704 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9705 return *T; 9706 } 9707 assert(I < F->getNumParams()); 9708 return F->getParamDecl(I++)->getType(); 9709 }; 9710 9711 unsigned I1 = 0, I2 = 0; 9712 for (unsigned I = 0; I != NumParams; ++I) { 9713 QualType T1 = NextParam(F1, I1, I == 0); 9714 QualType T2 = NextParam(F2, I2, I == 0); 9715 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 9716 if (!Context.hasSameUnqualifiedType(T1, T2)) 9717 return false; 9718 } 9719 return true; 9720 } 9721 9722 /// We're allowed to use constraints partial ordering only if the candidates 9723 /// have the same parameter types: 9724 /// [temp.func.order]p6.2.2 [...] or if the function parameters that 9725 /// positionally correspond between the two templates are not of the same type, 9726 /// neither template is more specialized than the other. 9727 /// [over.match.best]p2.6 9728 /// F1 and F2 are non-template functions with the same parameter-type-lists, 9729 /// and F1 is more constrained than F2 [...] 9730 static bool canCompareFunctionConstraints(Sema &S, 9731 const OverloadCandidate &Cand1, 9732 const OverloadCandidate &Cand2) { 9733 // FIXME: Per P2113R0 we also need to compare the template parameter lists 9734 // when comparing template functions. 9735 if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() && 9736 Cand2.Function->hasPrototype()) { 9737 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9738 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9739 if (PT1->getNumParams() == PT2->getNumParams() && 9740 PT1->isVariadic() == PT2->isVariadic() && 9741 S.FunctionParamTypesAreEqual(PT1, PT2, nullptr, 9742 Cand1.isReversed() ^ Cand2.isReversed())) 9743 return true; 9744 } 9745 return false; 9746 } 9747 9748 /// isBetterOverloadCandidate - Determines whether the first overload 9749 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9750 bool clang::isBetterOverloadCandidate( 9751 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9752 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9753 // Define viable functions to be better candidates than non-viable 9754 // functions. 9755 if (!Cand2.Viable) 9756 return Cand1.Viable; 9757 else if (!Cand1.Viable) 9758 return false; 9759 9760 // [CUDA] A function with 'never' preference is marked not viable, therefore 9761 // is never shown up here. The worst preference shown up here is 'wrong side', 9762 // e.g. an H function called by a HD function in device compilation. This is 9763 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9764 // function which is called only by an H function. A deferred diagnostic will 9765 // be triggered if it is emitted. However a wrong-sided function is still 9766 // a viable candidate here. 9767 // 9768 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9769 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9770 // can be emitted, Cand1 is not better than Cand2. This rule should have 9771 // precedence over other rules. 9772 // 9773 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9774 // other rules should be used to determine which is better. This is because 9775 // host/device based overloading resolution is mostly for determining 9776 // viability of a function. If two functions are both viable, other factors 9777 // should take precedence in preference, e.g. the standard-defined preferences 9778 // like argument conversion ranks or enable_if partial-ordering. The 9779 // preference for pass-object-size parameters is probably most similar to a 9780 // type-based-overloading decision and so should take priority. 9781 // 9782 // If other rules cannot determine which is better, CUDA preference will be 9783 // used again to determine which is better. 9784 // 9785 // TODO: Currently IdentifyCUDAPreference does not return correct values 9786 // for functions called in global variable initializers due to missing 9787 // correct context about device/host. Therefore we can only enforce this 9788 // rule when there is a caller. We should enforce this rule for functions 9789 // in global variable initializers once proper context is added. 9790 // 9791 // TODO: We can only enable the hostness based overloading resolution when 9792 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9793 // overloading resolution diagnostics. 9794 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9795 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9796 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { 9797 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9798 bool IsCand1ImplicitHD = 9799 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9800 bool IsCand2ImplicitHD = 9801 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9802 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9803 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9804 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9805 // The implicit HD function may be a function in a system header which 9806 // is forced by pragma. In device compilation, if we prefer HD candidates 9807 // over wrong-sided candidates, overloading resolution may change, which 9808 // may result in non-deferrable diagnostics. As a workaround, we let 9809 // implicit HD candidates take equal preference as wrong-sided candidates. 9810 // This will preserve the overloading resolution. 9811 // TODO: We still need special handling of implicit HD functions since 9812 // they may incur other diagnostics to be deferred. We should make all 9813 // host/device related diagnostics deferrable and remove special handling 9814 // of implicit HD functions. 9815 auto EmitThreshold = 9816 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9817 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9818 ? Sema::CFP_Never 9819 : Sema::CFP_WrongSide; 9820 auto Cand1Emittable = P1 > EmitThreshold; 9821 auto Cand2Emittable = P2 > EmitThreshold; 9822 if (Cand1Emittable && !Cand2Emittable) 9823 return true; 9824 if (!Cand1Emittable && Cand2Emittable) 9825 return false; 9826 } 9827 } 9828 9829 // C++ [over.match.best]p1: 9830 // 9831 // -- if F is a static member function, ICS1(F) is defined such 9832 // that ICS1(F) is neither better nor worse than ICS1(G) for 9833 // any function G, and, symmetrically, ICS1(G) is neither 9834 // better nor worse than ICS1(F). 9835 unsigned StartArg = 0; 9836 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9837 StartArg = 1; 9838 9839 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9840 // We don't allow incompatible pointer conversions in C++. 9841 if (!S.getLangOpts().CPlusPlus) 9842 return ICS.isStandard() && 9843 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9844 9845 // The only ill-formed conversion we allow in C++ is the string literal to 9846 // char* conversion, which is only considered ill-formed after C++11. 9847 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9848 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9849 }; 9850 9851 // Define functions that don't require ill-formed conversions for a given 9852 // argument to be better candidates than functions that do. 9853 unsigned NumArgs = Cand1.Conversions.size(); 9854 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9855 bool HasBetterConversion = false; 9856 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9857 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9858 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9859 if (Cand1Bad != Cand2Bad) { 9860 if (Cand1Bad) 9861 return false; 9862 HasBetterConversion = true; 9863 } 9864 } 9865 9866 if (HasBetterConversion) 9867 return true; 9868 9869 // C++ [over.match.best]p1: 9870 // A viable function F1 is defined to be a better function than another 9871 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9872 // conversion sequence than ICSi(F2), and then... 9873 bool HasWorseConversion = false; 9874 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9875 switch (CompareImplicitConversionSequences(S, Loc, 9876 Cand1.Conversions[ArgIdx], 9877 Cand2.Conversions[ArgIdx])) { 9878 case ImplicitConversionSequence::Better: 9879 // Cand1 has a better conversion sequence. 9880 HasBetterConversion = true; 9881 break; 9882 9883 case ImplicitConversionSequence::Worse: 9884 if (Cand1.Function && Cand2.Function && 9885 Cand1.isReversed() != Cand2.isReversed() && 9886 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9887 NumArgs)) { 9888 // Work around large-scale breakage caused by considering reversed 9889 // forms of operator== in C++20: 9890 // 9891 // When comparing a function against a reversed function with the same 9892 // parameter types, if we have a better conversion for one argument and 9893 // a worse conversion for the other, the implicit conversion sequences 9894 // are treated as being equally good. 9895 // 9896 // This prevents a comparison function from being considered ambiguous 9897 // with a reversed form that is written in the same way. 9898 // 9899 // We diagnose this as an extension from CreateOverloadedBinOp. 9900 HasWorseConversion = true; 9901 break; 9902 } 9903 9904 // Cand1 can't be better than Cand2. 9905 return false; 9906 9907 case ImplicitConversionSequence::Indistinguishable: 9908 // Do nothing. 9909 break; 9910 } 9911 } 9912 9913 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9914 // ICSj(F2), or, if not that, 9915 if (HasBetterConversion && !HasWorseConversion) 9916 return true; 9917 9918 // -- the context is an initialization by user-defined conversion 9919 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9920 // from the return type of F1 to the destination type (i.e., 9921 // the type of the entity being initialized) is a better 9922 // conversion sequence than the standard conversion sequence 9923 // from the return type of F2 to the destination type. 9924 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9925 Cand1.Function && Cand2.Function && 9926 isa<CXXConversionDecl>(Cand1.Function) && 9927 isa<CXXConversionDecl>(Cand2.Function)) { 9928 // First check whether we prefer one of the conversion functions over the 9929 // other. This only distinguishes the results in non-standard, extension 9930 // cases such as the conversion from a lambda closure type to a function 9931 // pointer or block. 9932 ImplicitConversionSequence::CompareKind Result = 9933 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9934 if (Result == ImplicitConversionSequence::Indistinguishable) 9935 Result = CompareStandardConversionSequences(S, Loc, 9936 Cand1.FinalConversion, 9937 Cand2.FinalConversion); 9938 9939 if (Result != ImplicitConversionSequence::Indistinguishable) 9940 return Result == ImplicitConversionSequence::Better; 9941 9942 // FIXME: Compare kind of reference binding if conversion functions 9943 // convert to a reference type used in direct reference binding, per 9944 // C++14 [over.match.best]p1 section 2 bullet 3. 9945 } 9946 9947 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9948 // as combined with the resolution to CWG issue 243. 9949 // 9950 // When the context is initialization by constructor ([over.match.ctor] or 9951 // either phase of [over.match.list]), a constructor is preferred over 9952 // a conversion function. 9953 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9954 Cand1.Function && Cand2.Function && 9955 isa<CXXConstructorDecl>(Cand1.Function) != 9956 isa<CXXConstructorDecl>(Cand2.Function)) 9957 return isa<CXXConstructorDecl>(Cand1.Function); 9958 9959 // -- F1 is a non-template function and F2 is a function template 9960 // specialization, or, if not that, 9961 bool Cand1IsSpecialization = Cand1.Function && 9962 Cand1.Function->getPrimaryTemplate(); 9963 bool Cand2IsSpecialization = Cand2.Function && 9964 Cand2.Function->getPrimaryTemplate(); 9965 if (Cand1IsSpecialization != Cand2IsSpecialization) 9966 return Cand2IsSpecialization; 9967 9968 // -- F1 and F2 are function template specializations, and the function 9969 // template for F1 is more specialized than the template for F2 9970 // according to the partial ordering rules described in 14.5.5.2, or, 9971 // if not that, 9972 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9973 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9974 Cand1.Function->getPrimaryTemplate(), 9975 Cand2.Function->getPrimaryTemplate(), Loc, 9976 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9977 : TPOC_Call, 9978 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9979 Cand1.isReversed() ^ Cand2.isReversed(), 9980 canCompareFunctionConstraints(S, Cand1, Cand2))) 9981 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9982 } 9983 9984 // -— F1 and F2 are non-template functions with the same 9985 // parameter-type-lists, and F1 is more constrained than F2 [...], 9986 if (!Cand1IsSpecialization && !Cand2IsSpecialization && 9987 canCompareFunctionConstraints(S, Cand1, Cand2)) { 9988 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9989 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9990 if (RC1 && RC2) { 9991 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9992 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2}, 9993 AtLeastAsConstrained1) || 9994 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1}, 9995 AtLeastAsConstrained2)) 9996 return false; 9997 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9998 return AtLeastAsConstrained1; 9999 } else if (RC1 || RC2) { 10000 return RC1 != nullptr; 10001 } 10002 } 10003 10004 // -- F1 is a constructor for a class D, F2 is a constructor for a base 10005 // class B of D, and for all arguments the corresponding parameters of 10006 // F1 and F2 have the same type. 10007 // FIXME: Implement the "all parameters have the same type" check. 10008 bool Cand1IsInherited = 10009 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 10010 bool Cand2IsInherited = 10011 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 10012 if (Cand1IsInherited != Cand2IsInherited) 10013 return Cand2IsInherited; 10014 else if (Cand1IsInherited) { 10015 assert(Cand2IsInherited); 10016 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 10017 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 10018 if (Cand1Class->isDerivedFrom(Cand2Class)) 10019 return true; 10020 if (Cand2Class->isDerivedFrom(Cand1Class)) 10021 return false; 10022 // Inherited from sibling base classes: still ambiguous. 10023 } 10024 10025 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 10026 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 10027 // with reversed order of parameters and F1 is not 10028 // 10029 // We rank reversed + different operator as worse than just reversed, but 10030 // that comparison can never happen, because we only consider reversing for 10031 // the maximally-rewritten operator (== or <=>). 10032 if (Cand1.RewriteKind != Cand2.RewriteKind) 10033 return Cand1.RewriteKind < Cand2.RewriteKind; 10034 10035 // Check C++17 tie-breakers for deduction guides. 10036 { 10037 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 10038 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 10039 if (Guide1 && Guide2) { 10040 // -- F1 is generated from a deduction-guide and F2 is not 10041 if (Guide1->isImplicit() != Guide2->isImplicit()) 10042 return Guide2->isImplicit(); 10043 10044 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 10045 if (Guide1->isCopyDeductionCandidate()) 10046 return true; 10047 } 10048 } 10049 10050 // Check for enable_if value-based overload resolution. 10051 if (Cand1.Function && Cand2.Function) { 10052 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 10053 if (Cmp != Comparison::Equal) 10054 return Cmp == Comparison::Better; 10055 } 10056 10057 bool HasPS1 = Cand1.Function != nullptr && 10058 functionHasPassObjectSizeParams(Cand1.Function); 10059 bool HasPS2 = Cand2.Function != nullptr && 10060 functionHasPassObjectSizeParams(Cand2.Function); 10061 if (HasPS1 != HasPS2 && HasPS1) 10062 return true; 10063 10064 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 10065 if (MV == Comparison::Better) 10066 return true; 10067 if (MV == Comparison::Worse) 10068 return false; 10069 10070 // If other rules cannot determine which is better, CUDA preference is used 10071 // to determine which is better. 10072 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 10073 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10074 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 10075 S.IdentifyCUDAPreference(Caller, Cand2.Function); 10076 } 10077 10078 // General member function overloading is handled above, so this only handles 10079 // constructors with address spaces. 10080 // This only handles address spaces since C++ has no other 10081 // qualifier that can be used with constructors. 10082 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 10083 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 10084 if (CD1 && CD2) { 10085 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 10086 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 10087 if (AS1 != AS2) { 10088 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10089 return true; 10090 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10091 return false; 10092 } 10093 } 10094 10095 return false; 10096 } 10097 10098 /// Determine whether two declarations are "equivalent" for the purposes of 10099 /// name lookup and overload resolution. This applies when the same internal/no 10100 /// linkage entity is defined by two modules (probably by textually including 10101 /// the same header). In such a case, we don't consider the declarations to 10102 /// declare the same entity, but we also don't want lookups with both 10103 /// declarations visible to be ambiguous in some cases (this happens when using 10104 /// a modularized libstdc++). 10105 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10106 const NamedDecl *B) { 10107 auto *VA = dyn_cast_or_null<ValueDecl>(A); 10108 auto *VB = dyn_cast_or_null<ValueDecl>(B); 10109 if (!VA || !VB) 10110 return false; 10111 10112 // The declarations must be declaring the same name as an internal linkage 10113 // entity in different modules. 10114 if (!VA->getDeclContext()->getRedeclContext()->Equals( 10115 VB->getDeclContext()->getRedeclContext()) || 10116 getOwningModule(VA) == getOwningModule(VB) || 10117 VA->isExternallyVisible() || VB->isExternallyVisible()) 10118 return false; 10119 10120 // Check that the declarations appear to be equivalent. 10121 // 10122 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 10123 // For constants and functions, we should check the initializer or body is 10124 // the same. For non-constant variables, we shouldn't allow it at all. 10125 if (Context.hasSameType(VA->getType(), VB->getType())) 10126 return true; 10127 10128 // Enum constants within unnamed enumerations will have different types, but 10129 // may still be similar enough to be interchangeable for our purposes. 10130 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 10131 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 10132 // Only handle anonymous enums. If the enumerations were named and 10133 // equivalent, they would have been merged to the same type. 10134 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 10135 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 10136 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 10137 !Context.hasSameType(EnumA->getIntegerType(), 10138 EnumB->getIntegerType())) 10139 return false; 10140 // Allow this only if the value is the same for both enumerators. 10141 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 10142 } 10143 } 10144 10145 // Nothing else is sufficiently similar. 10146 return false; 10147 } 10148 10149 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10150 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10151 assert(D && "Unknown declaration"); 10152 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10153 10154 Module *M = getOwningModule(D); 10155 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10156 << !M << (M ? M->getFullModuleName() : ""); 10157 10158 for (auto *E : Equiv) { 10159 Module *M = getOwningModule(E); 10160 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10161 << !M << (M ? M->getFullModuleName() : ""); 10162 } 10163 } 10164 10165 /// Computes the best viable function (C++ 13.3.3) 10166 /// within an overload candidate set. 10167 /// 10168 /// \param Loc The location of the function name (or operator symbol) for 10169 /// which overload resolution occurs. 10170 /// 10171 /// \param Best If overload resolution was successful or found a deleted 10172 /// function, \p Best points to the candidate function found. 10173 /// 10174 /// \returns The result of overload resolution. 10175 OverloadingResult 10176 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10177 iterator &Best) { 10178 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10179 std::transform(begin(), end(), std::back_inserter(Candidates), 10180 [](OverloadCandidate &Cand) { return &Cand; }); 10181 10182 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10183 // are accepted by both clang and NVCC. However, during a particular 10184 // compilation mode only one call variant is viable. We need to 10185 // exclude non-viable overload candidates from consideration based 10186 // only on their host/device attributes. Specifically, if one 10187 // candidate call is WrongSide and the other is SameSide, we ignore 10188 // the WrongSide candidate. 10189 // We only need to remove wrong-sided candidates here if 10190 // -fgpu-exclude-wrong-side-overloads is off. When 10191 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10192 // uniformly in isBetterOverloadCandidate. 10193 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10194 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10195 bool ContainsSameSideCandidate = 10196 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10197 // Check viable function only. 10198 return Cand->Viable && Cand->Function && 10199 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10200 Sema::CFP_SameSide; 10201 }); 10202 if (ContainsSameSideCandidate) { 10203 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10204 // Check viable function only to avoid unnecessary data copying/moving. 10205 return Cand->Viable && Cand->Function && 10206 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10207 Sema::CFP_WrongSide; 10208 }; 10209 llvm::erase_if(Candidates, IsWrongSideCandidate); 10210 } 10211 } 10212 10213 // Find the best viable function. 10214 Best = end(); 10215 for (auto *Cand : Candidates) { 10216 Cand->Best = false; 10217 if (Cand->Viable) 10218 if (Best == end() || 10219 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10220 Best = Cand; 10221 } 10222 10223 // If we didn't find any viable functions, abort. 10224 if (Best == end()) 10225 return OR_No_Viable_Function; 10226 10227 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10228 10229 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10230 PendingBest.push_back(&*Best); 10231 Best->Best = true; 10232 10233 // Make sure that this function is better than every other viable 10234 // function. If not, we have an ambiguity. 10235 while (!PendingBest.empty()) { 10236 auto *Curr = PendingBest.pop_back_val(); 10237 for (auto *Cand : Candidates) { 10238 if (Cand->Viable && !Cand->Best && 10239 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10240 PendingBest.push_back(Cand); 10241 Cand->Best = true; 10242 10243 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10244 Curr->Function)) 10245 EquivalentCands.push_back(Cand->Function); 10246 else 10247 Best = end(); 10248 } 10249 } 10250 } 10251 10252 // If we found more than one best candidate, this is ambiguous. 10253 if (Best == end()) 10254 return OR_Ambiguous; 10255 10256 // Best is the best viable function. 10257 if (Best->Function && Best->Function->isDeleted()) 10258 return OR_Deleted; 10259 10260 if (!EquivalentCands.empty()) 10261 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10262 EquivalentCands); 10263 10264 return OR_Success; 10265 } 10266 10267 namespace { 10268 10269 enum OverloadCandidateKind { 10270 oc_function, 10271 oc_method, 10272 oc_reversed_binary_operator, 10273 oc_constructor, 10274 oc_implicit_default_constructor, 10275 oc_implicit_copy_constructor, 10276 oc_implicit_move_constructor, 10277 oc_implicit_copy_assignment, 10278 oc_implicit_move_assignment, 10279 oc_implicit_equality_comparison, 10280 oc_inherited_constructor 10281 }; 10282 10283 enum OverloadCandidateSelect { 10284 ocs_non_template, 10285 ocs_template, 10286 ocs_described_template, 10287 }; 10288 10289 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10290 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10291 OverloadCandidateRewriteKind CRK, 10292 std::string &Description) { 10293 10294 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10295 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10296 isTemplate = true; 10297 Description = S.getTemplateArgumentBindingsText( 10298 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10299 } 10300 10301 OverloadCandidateSelect Select = [&]() { 10302 if (!Description.empty()) 10303 return ocs_described_template; 10304 return isTemplate ? ocs_template : ocs_non_template; 10305 }(); 10306 10307 OverloadCandidateKind Kind = [&]() { 10308 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10309 return oc_implicit_equality_comparison; 10310 10311 if (CRK & CRK_Reversed) 10312 return oc_reversed_binary_operator; 10313 10314 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10315 if (!Ctor->isImplicit()) { 10316 if (isa<ConstructorUsingShadowDecl>(Found)) 10317 return oc_inherited_constructor; 10318 else 10319 return oc_constructor; 10320 } 10321 10322 if (Ctor->isDefaultConstructor()) 10323 return oc_implicit_default_constructor; 10324 10325 if (Ctor->isMoveConstructor()) 10326 return oc_implicit_move_constructor; 10327 10328 assert(Ctor->isCopyConstructor() && 10329 "unexpected sort of implicit constructor"); 10330 return oc_implicit_copy_constructor; 10331 } 10332 10333 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10334 // This actually gets spelled 'candidate function' for now, but 10335 // it doesn't hurt to split it out. 10336 if (!Meth->isImplicit()) 10337 return oc_method; 10338 10339 if (Meth->isMoveAssignmentOperator()) 10340 return oc_implicit_move_assignment; 10341 10342 if (Meth->isCopyAssignmentOperator()) 10343 return oc_implicit_copy_assignment; 10344 10345 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10346 return oc_method; 10347 } 10348 10349 return oc_function; 10350 }(); 10351 10352 return std::make_pair(Kind, Select); 10353 } 10354 10355 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10356 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10357 // set. 10358 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10359 S.Diag(FoundDecl->getLocation(), 10360 diag::note_ovl_candidate_inherited_constructor) 10361 << Shadow->getNominatedBaseClass(); 10362 } 10363 10364 } // end anonymous namespace 10365 10366 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10367 const FunctionDecl *FD) { 10368 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10369 bool AlwaysTrue; 10370 if (EnableIf->getCond()->isValueDependent() || 10371 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10372 return false; 10373 if (!AlwaysTrue) 10374 return false; 10375 } 10376 return true; 10377 } 10378 10379 /// Returns true if we can take the address of the function. 10380 /// 10381 /// \param Complain - If true, we'll emit a diagnostic 10382 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10383 /// we in overload resolution? 10384 /// \param Loc - The location of the statement we're complaining about. Ignored 10385 /// if we're not complaining, or if we're in overload resolution. 10386 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10387 bool Complain, 10388 bool InOverloadResolution, 10389 SourceLocation Loc) { 10390 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10391 if (Complain) { 10392 if (InOverloadResolution) 10393 S.Diag(FD->getBeginLoc(), 10394 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10395 else 10396 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10397 } 10398 return false; 10399 } 10400 10401 if (FD->getTrailingRequiresClause()) { 10402 ConstraintSatisfaction Satisfaction; 10403 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10404 return false; 10405 if (!Satisfaction.IsSatisfied) { 10406 if (Complain) { 10407 if (InOverloadResolution) { 10408 SmallString<128> TemplateArgString; 10409 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 10410 TemplateArgString += " "; 10411 TemplateArgString += S.getTemplateArgumentBindingsText( 10412 FunTmpl->getTemplateParameters(), 10413 *FD->getTemplateSpecializationArgs()); 10414 } 10415 10416 S.Diag(FD->getBeginLoc(), 10417 diag::note_ovl_candidate_unsatisfied_constraints) 10418 << TemplateArgString; 10419 } else 10420 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10421 << FD; 10422 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10423 } 10424 return false; 10425 } 10426 } 10427 10428 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10429 return P->hasAttr<PassObjectSizeAttr>(); 10430 }); 10431 if (I == FD->param_end()) 10432 return true; 10433 10434 if (Complain) { 10435 // Add one to ParamNo because it's user-facing 10436 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10437 if (InOverloadResolution) 10438 S.Diag(FD->getLocation(), 10439 diag::note_ovl_candidate_has_pass_object_size_params) 10440 << ParamNo; 10441 else 10442 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10443 << FD << ParamNo; 10444 } 10445 return false; 10446 } 10447 10448 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10449 const FunctionDecl *FD) { 10450 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10451 /*InOverloadResolution=*/true, 10452 /*Loc=*/SourceLocation()); 10453 } 10454 10455 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10456 bool Complain, 10457 SourceLocation Loc) { 10458 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10459 /*InOverloadResolution=*/false, 10460 Loc); 10461 } 10462 10463 // Don't print candidates other than the one that matches the calling 10464 // convention of the call operator, since that is guaranteed to exist. 10465 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10466 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10467 10468 if (!ConvD) 10469 return false; 10470 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10471 if (!RD->isLambda()) 10472 return false; 10473 10474 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10475 CallingConv CallOpCC = 10476 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10477 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10478 CallingConv ConvToCC = 10479 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10480 10481 return ConvToCC != CallOpCC; 10482 } 10483 10484 // Notes the location of an overload candidate. 10485 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10486 OverloadCandidateRewriteKind RewriteKind, 10487 QualType DestType, bool TakingAddress) { 10488 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10489 return; 10490 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10491 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10492 return; 10493 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10494 return; 10495 10496 std::string FnDesc; 10497 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10498 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10499 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10500 << (unsigned)KSPair.first << (unsigned)KSPair.second 10501 << Fn << FnDesc; 10502 10503 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10504 Diag(Fn->getLocation(), PD); 10505 MaybeEmitInheritedConstructorNote(*this, Found); 10506 } 10507 10508 static void 10509 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10510 // Perhaps the ambiguity was caused by two atomic constraints that are 10511 // 'identical' but not equivalent: 10512 // 10513 // void foo() requires (sizeof(T) > 4) { } // #1 10514 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10515 // 10516 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10517 // #2 to subsume #1, but these constraint are not considered equivalent 10518 // according to the subsumption rules because they are not the same 10519 // source-level construct. This behavior is quite confusing and we should try 10520 // to help the user figure out what happened. 10521 10522 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10523 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10524 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10525 if (!I->Function) 10526 continue; 10527 SmallVector<const Expr *, 3> AC; 10528 if (auto *Template = I->Function->getPrimaryTemplate()) 10529 Template->getAssociatedConstraints(AC); 10530 else 10531 I->Function->getAssociatedConstraints(AC); 10532 if (AC.empty()) 10533 continue; 10534 if (FirstCand == nullptr) { 10535 FirstCand = I->Function; 10536 FirstAC = AC; 10537 } else if (SecondCand == nullptr) { 10538 SecondCand = I->Function; 10539 SecondAC = AC; 10540 } else { 10541 // We have more than one pair of constrained functions - this check is 10542 // expensive and we'd rather not try to diagnose it. 10543 return; 10544 } 10545 } 10546 if (!SecondCand) 10547 return; 10548 // The diagnostic can only happen if there are associated constraints on 10549 // both sides (there needs to be some identical atomic constraint). 10550 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10551 SecondCand, SecondAC)) 10552 // Just show the user one diagnostic, they'll probably figure it out 10553 // from here. 10554 return; 10555 } 10556 10557 // Notes the location of all overload candidates designated through 10558 // OverloadedExpr 10559 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10560 bool TakingAddress) { 10561 assert(OverloadedExpr->getType() == Context.OverloadTy); 10562 10563 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10564 OverloadExpr *OvlExpr = Ovl.Expression; 10565 10566 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10567 IEnd = OvlExpr->decls_end(); 10568 I != IEnd; ++I) { 10569 if (FunctionTemplateDecl *FunTmpl = 10570 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10571 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10572 TakingAddress); 10573 } else if (FunctionDecl *Fun 10574 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10575 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10576 } 10577 } 10578 } 10579 10580 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10581 /// "lead" diagnostic; it will be given two arguments, the source and 10582 /// target types of the conversion. 10583 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10584 Sema &S, 10585 SourceLocation CaretLoc, 10586 const PartialDiagnostic &PDiag) const { 10587 S.Diag(CaretLoc, PDiag) 10588 << Ambiguous.getFromType() << Ambiguous.getToType(); 10589 unsigned CandsShown = 0; 10590 AmbiguousConversionSequence::const_iterator I, E; 10591 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10592 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10593 break; 10594 ++CandsShown; 10595 S.NoteOverloadCandidate(I->first, I->second); 10596 } 10597 S.Diags.overloadCandidatesShown(CandsShown); 10598 if (I != E) 10599 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10600 } 10601 10602 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10603 unsigned I, bool TakingCandidateAddress) { 10604 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10605 assert(Conv.isBad()); 10606 assert(Cand->Function && "for now, candidate must be a function"); 10607 FunctionDecl *Fn = Cand->Function; 10608 10609 // There's a conversion slot for the object argument if this is a 10610 // non-constructor method. Note that 'I' corresponds the 10611 // conversion-slot index. 10612 bool isObjectArgument = false; 10613 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10614 if (I == 0) 10615 isObjectArgument = true; 10616 else 10617 I--; 10618 } 10619 10620 std::string FnDesc; 10621 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10622 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10623 FnDesc); 10624 10625 Expr *FromExpr = Conv.Bad.FromExpr; 10626 QualType FromTy = Conv.Bad.getFromType(); 10627 QualType ToTy = Conv.Bad.getToType(); 10628 10629 if (FromTy == S.Context.OverloadTy) { 10630 assert(FromExpr && "overload set argument came from implicit argument?"); 10631 Expr *E = FromExpr->IgnoreParens(); 10632 if (isa<UnaryOperator>(E)) 10633 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10634 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10635 10636 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10637 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10638 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10639 << Name << I + 1; 10640 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10641 return; 10642 } 10643 10644 // Do some hand-waving analysis to see if the non-viability is due 10645 // to a qualifier mismatch. 10646 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10647 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10648 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10649 CToTy = RT->getPointeeType(); 10650 else { 10651 // TODO: detect and diagnose the full richness of const mismatches. 10652 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10653 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10654 CFromTy = FromPT->getPointeeType(); 10655 CToTy = ToPT->getPointeeType(); 10656 } 10657 } 10658 10659 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10660 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10661 Qualifiers FromQs = CFromTy.getQualifiers(); 10662 Qualifiers ToQs = CToTy.getQualifiers(); 10663 10664 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10665 if (isObjectArgument) 10666 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10667 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10668 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10669 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10670 else 10671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10672 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10673 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10674 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10675 << ToTy->isReferenceType() << I + 1; 10676 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10677 return; 10678 } 10679 10680 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10682 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10683 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10684 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10685 << (unsigned)isObjectArgument << I + 1; 10686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10687 return; 10688 } 10689 10690 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10692 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10693 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10694 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10695 << (unsigned)isObjectArgument << I + 1; 10696 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10697 return; 10698 } 10699 10700 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10702 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10704 << FromQs.hasUnaligned() << I + 1; 10705 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10706 return; 10707 } 10708 10709 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10710 assert(CVR && "expected qualifiers mismatch"); 10711 10712 if (isObjectArgument) { 10713 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10714 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10715 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10716 << (CVR - 1); 10717 } else { 10718 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10719 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10720 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10721 << (CVR - 1) << I + 1; 10722 } 10723 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10724 return; 10725 } 10726 10727 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10728 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10729 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10730 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10731 << (unsigned)isObjectArgument << I + 1 10732 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10733 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10734 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10735 return; 10736 } 10737 10738 // Special diagnostic for failure to convert an initializer list, since 10739 // telling the user that it has type void is not useful. 10740 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10741 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10742 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10743 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10744 << ToTy << (unsigned)isObjectArgument << I + 1 10745 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 10746 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 10747 ? 2 10748 : 0); 10749 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10750 return; 10751 } 10752 10753 // Diagnose references or pointers to incomplete types differently, 10754 // since it's far from impossible that the incompleteness triggered 10755 // the failure. 10756 QualType TempFromTy = FromTy.getNonReferenceType(); 10757 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10758 TempFromTy = PTy->getPointeeType(); 10759 if (TempFromTy->isIncompleteType()) { 10760 // Emit the generic diagnostic and, optionally, add the hints to it. 10761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10762 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10763 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10764 << ToTy << (unsigned)isObjectArgument << I + 1 10765 << (unsigned)(Cand->Fix.Kind); 10766 10767 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10768 return; 10769 } 10770 10771 // Diagnose base -> derived pointer conversions. 10772 unsigned BaseToDerivedConversion = 0; 10773 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10774 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10775 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10776 FromPtrTy->getPointeeType()) && 10777 !FromPtrTy->getPointeeType()->isIncompleteType() && 10778 !ToPtrTy->getPointeeType()->isIncompleteType() && 10779 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10780 FromPtrTy->getPointeeType())) 10781 BaseToDerivedConversion = 1; 10782 } 10783 } else if (const ObjCObjectPointerType *FromPtrTy 10784 = FromTy->getAs<ObjCObjectPointerType>()) { 10785 if (const ObjCObjectPointerType *ToPtrTy 10786 = ToTy->getAs<ObjCObjectPointerType>()) 10787 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10788 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10789 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10790 FromPtrTy->getPointeeType()) && 10791 FromIface->isSuperClassOf(ToIface)) 10792 BaseToDerivedConversion = 2; 10793 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10794 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10795 !FromTy->isIncompleteType() && 10796 !ToRefTy->getPointeeType()->isIncompleteType() && 10797 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10798 BaseToDerivedConversion = 3; 10799 } 10800 } 10801 10802 if (BaseToDerivedConversion) { 10803 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10804 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10805 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10806 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10807 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10808 return; 10809 } 10810 10811 if (isa<ObjCObjectPointerType>(CFromTy) && 10812 isa<PointerType>(CToTy)) { 10813 Qualifiers FromQs = CFromTy.getQualifiers(); 10814 Qualifiers ToQs = CToTy.getQualifiers(); 10815 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10816 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10817 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10818 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10819 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10820 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10821 return; 10822 } 10823 } 10824 10825 if (TakingCandidateAddress && 10826 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10827 return; 10828 10829 // Emit the generic diagnostic and, optionally, add the hints to it. 10830 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10831 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10832 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10833 << ToTy << (unsigned)isObjectArgument << I + 1 10834 << (unsigned)(Cand->Fix.Kind); 10835 10836 // If we can fix the conversion, suggest the FixIts. 10837 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10838 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10839 FDiag << *HI; 10840 S.Diag(Fn->getLocation(), FDiag); 10841 10842 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10843 } 10844 10845 /// Additional arity mismatch diagnosis specific to a function overload 10846 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10847 /// over a candidate in any candidate set. 10848 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10849 unsigned NumArgs) { 10850 FunctionDecl *Fn = Cand->Function; 10851 unsigned MinParams = Fn->getMinRequiredArguments(); 10852 10853 // With invalid overloaded operators, it's possible that we think we 10854 // have an arity mismatch when in fact it looks like we have the 10855 // right number of arguments, because only overloaded operators have 10856 // the weird behavior of overloading member and non-member functions. 10857 // Just don't report anything. 10858 if (Fn->isInvalidDecl() && 10859 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10860 return true; 10861 10862 if (NumArgs < MinParams) { 10863 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10864 (Cand->FailureKind == ovl_fail_bad_deduction && 10865 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10866 } else { 10867 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10868 (Cand->FailureKind == ovl_fail_bad_deduction && 10869 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10870 } 10871 10872 return false; 10873 } 10874 10875 /// General arity mismatch diagnosis over a candidate in a candidate set. 10876 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10877 unsigned NumFormalArgs) { 10878 assert(isa<FunctionDecl>(D) && 10879 "The templated declaration should at least be a function" 10880 " when diagnosing bad template argument deduction due to too many" 10881 " or too few arguments"); 10882 10883 FunctionDecl *Fn = cast<FunctionDecl>(D); 10884 10885 // TODO: treat calls to a missing default constructor as a special case 10886 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10887 unsigned MinParams = Fn->getMinRequiredArguments(); 10888 10889 // at least / at most / exactly 10890 unsigned mode, modeCount; 10891 if (NumFormalArgs < MinParams) { 10892 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10893 FnTy->isTemplateVariadic()) 10894 mode = 0; // "at least" 10895 else 10896 mode = 2; // "exactly" 10897 modeCount = MinParams; 10898 } else { 10899 if (MinParams != FnTy->getNumParams()) 10900 mode = 1; // "at most" 10901 else 10902 mode = 2; // "exactly" 10903 modeCount = FnTy->getNumParams(); 10904 } 10905 10906 std::string Description; 10907 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10908 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10909 10910 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10911 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10912 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10913 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10914 else 10915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10916 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10917 << Description << mode << modeCount << NumFormalArgs; 10918 10919 MaybeEmitInheritedConstructorNote(S, Found); 10920 } 10921 10922 /// Arity mismatch diagnosis specific to a function overload candidate. 10923 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10924 unsigned NumFormalArgs) { 10925 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10926 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10927 } 10928 10929 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10930 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10931 return TD; 10932 llvm_unreachable("Unsupported: Getting the described template declaration" 10933 " for bad deduction diagnosis"); 10934 } 10935 10936 /// Diagnose a failed template-argument deduction. 10937 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10938 DeductionFailureInfo &DeductionFailure, 10939 unsigned NumArgs, 10940 bool TakingCandidateAddress) { 10941 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10942 NamedDecl *ParamD; 10943 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10944 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10945 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10946 switch (DeductionFailure.Result) { 10947 case Sema::TDK_Success: 10948 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10949 10950 case Sema::TDK_Incomplete: { 10951 assert(ParamD && "no parameter found for incomplete deduction result"); 10952 S.Diag(Templated->getLocation(), 10953 diag::note_ovl_candidate_incomplete_deduction) 10954 << ParamD->getDeclName(); 10955 MaybeEmitInheritedConstructorNote(S, Found); 10956 return; 10957 } 10958 10959 case Sema::TDK_IncompletePack: { 10960 assert(ParamD && "no parameter found for incomplete deduction result"); 10961 S.Diag(Templated->getLocation(), 10962 diag::note_ovl_candidate_incomplete_deduction_pack) 10963 << ParamD->getDeclName() 10964 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10965 << *DeductionFailure.getFirstArg(); 10966 MaybeEmitInheritedConstructorNote(S, Found); 10967 return; 10968 } 10969 10970 case Sema::TDK_Underqualified: { 10971 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10972 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10973 10974 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10975 10976 // Param will have been canonicalized, but it should just be a 10977 // qualified version of ParamD, so move the qualifiers to that. 10978 QualifierCollector Qs; 10979 Qs.strip(Param); 10980 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10981 assert(S.Context.hasSameType(Param, NonCanonParam)); 10982 10983 // Arg has also been canonicalized, but there's nothing we can do 10984 // about that. It also doesn't matter as much, because it won't 10985 // have any template parameters in it (because deduction isn't 10986 // done on dependent types). 10987 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10988 10989 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10990 << ParamD->getDeclName() << Arg << NonCanonParam; 10991 MaybeEmitInheritedConstructorNote(S, Found); 10992 return; 10993 } 10994 10995 case Sema::TDK_Inconsistent: { 10996 assert(ParamD && "no parameter found for inconsistent deduction result"); 10997 int which = 0; 10998 if (isa<TemplateTypeParmDecl>(ParamD)) 10999 which = 0; 11000 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 11001 // Deduction might have failed because we deduced arguments of two 11002 // different types for a non-type template parameter. 11003 // FIXME: Use a different TDK value for this. 11004 QualType T1 = 11005 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 11006 QualType T2 = 11007 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 11008 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 11009 S.Diag(Templated->getLocation(), 11010 diag::note_ovl_candidate_inconsistent_deduction_types) 11011 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 11012 << *DeductionFailure.getSecondArg() << T2; 11013 MaybeEmitInheritedConstructorNote(S, Found); 11014 return; 11015 } 11016 11017 which = 1; 11018 } else { 11019 which = 2; 11020 } 11021 11022 // Tweak the diagnostic if the problem is that we deduced packs of 11023 // different arities. We'll print the actual packs anyway in case that 11024 // includes additional useful information. 11025 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 11026 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 11027 DeductionFailure.getFirstArg()->pack_size() != 11028 DeductionFailure.getSecondArg()->pack_size()) { 11029 which = 3; 11030 } 11031 11032 S.Diag(Templated->getLocation(), 11033 diag::note_ovl_candidate_inconsistent_deduction) 11034 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 11035 << *DeductionFailure.getSecondArg(); 11036 MaybeEmitInheritedConstructorNote(S, Found); 11037 return; 11038 } 11039 11040 case Sema::TDK_InvalidExplicitArguments: 11041 assert(ParamD && "no parameter found for invalid explicit arguments"); 11042 if (ParamD->getDeclName()) 11043 S.Diag(Templated->getLocation(), 11044 diag::note_ovl_candidate_explicit_arg_mismatch_named) 11045 << ParamD->getDeclName(); 11046 else { 11047 int index = 0; 11048 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 11049 index = TTP->getIndex(); 11050 else if (NonTypeTemplateParmDecl *NTTP 11051 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 11052 index = NTTP->getIndex(); 11053 else 11054 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 11055 S.Diag(Templated->getLocation(), 11056 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 11057 << (index + 1); 11058 } 11059 MaybeEmitInheritedConstructorNote(S, Found); 11060 return; 11061 11062 case Sema::TDK_ConstraintsNotSatisfied: { 11063 // Format the template argument list into the argument string. 11064 SmallString<128> TemplateArgString; 11065 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 11066 TemplateArgString = " "; 11067 TemplateArgString += S.getTemplateArgumentBindingsText( 11068 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11069 if (TemplateArgString.size() == 1) 11070 TemplateArgString.clear(); 11071 S.Diag(Templated->getLocation(), 11072 diag::note_ovl_candidate_unsatisfied_constraints) 11073 << TemplateArgString; 11074 11075 S.DiagnoseUnsatisfiedConstraint( 11076 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 11077 return; 11078 } 11079 case Sema::TDK_TooManyArguments: 11080 case Sema::TDK_TooFewArguments: 11081 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 11082 return; 11083 11084 case Sema::TDK_InstantiationDepth: 11085 S.Diag(Templated->getLocation(), 11086 diag::note_ovl_candidate_instantiation_depth); 11087 MaybeEmitInheritedConstructorNote(S, Found); 11088 return; 11089 11090 case Sema::TDK_SubstitutionFailure: { 11091 // Format the template argument list into the argument string. 11092 SmallString<128> TemplateArgString; 11093 if (TemplateArgumentList *Args = 11094 DeductionFailure.getTemplateArgumentList()) { 11095 TemplateArgString = " "; 11096 TemplateArgString += S.getTemplateArgumentBindingsText( 11097 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11098 if (TemplateArgString.size() == 1) 11099 TemplateArgString.clear(); 11100 } 11101 11102 // If this candidate was disabled by enable_if, say so. 11103 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 11104 if (PDiag && PDiag->second.getDiagID() == 11105 diag::err_typename_nested_not_found_enable_if) { 11106 // FIXME: Use the source range of the condition, and the fully-qualified 11107 // name of the enable_if template. These are both present in PDiag. 11108 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 11109 << "'enable_if'" << TemplateArgString; 11110 return; 11111 } 11112 11113 // We found a specific requirement that disabled the enable_if. 11114 if (PDiag && PDiag->second.getDiagID() == 11115 diag::err_typename_nested_not_found_requirement) { 11116 S.Diag(Templated->getLocation(), 11117 diag::note_ovl_candidate_disabled_by_requirement) 11118 << PDiag->second.getStringArg(0) << TemplateArgString; 11119 return; 11120 } 11121 11122 // Format the SFINAE diagnostic into the argument string. 11123 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 11124 // formatted message in another diagnostic. 11125 SmallString<128> SFINAEArgString; 11126 SourceRange R; 11127 if (PDiag) { 11128 SFINAEArgString = ": "; 11129 R = SourceRange(PDiag->first, PDiag->first); 11130 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 11131 } 11132 11133 S.Diag(Templated->getLocation(), 11134 diag::note_ovl_candidate_substitution_failure) 11135 << TemplateArgString << SFINAEArgString << R; 11136 MaybeEmitInheritedConstructorNote(S, Found); 11137 return; 11138 } 11139 11140 case Sema::TDK_DeducedMismatch: 11141 case Sema::TDK_DeducedMismatchNested: { 11142 // Format the template argument list into the argument string. 11143 SmallString<128> TemplateArgString; 11144 if (TemplateArgumentList *Args = 11145 DeductionFailure.getTemplateArgumentList()) { 11146 TemplateArgString = " "; 11147 TemplateArgString += S.getTemplateArgumentBindingsText( 11148 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11149 if (TemplateArgString.size() == 1) 11150 TemplateArgString.clear(); 11151 } 11152 11153 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11154 << (*DeductionFailure.getCallArgIndex() + 1) 11155 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11156 << TemplateArgString 11157 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11158 break; 11159 } 11160 11161 case Sema::TDK_NonDeducedMismatch: { 11162 // FIXME: Provide a source location to indicate what we couldn't match. 11163 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11164 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11165 if (FirstTA.getKind() == TemplateArgument::Template && 11166 SecondTA.getKind() == TemplateArgument::Template) { 11167 TemplateName FirstTN = FirstTA.getAsTemplate(); 11168 TemplateName SecondTN = SecondTA.getAsTemplate(); 11169 if (FirstTN.getKind() == TemplateName::Template && 11170 SecondTN.getKind() == TemplateName::Template) { 11171 if (FirstTN.getAsTemplateDecl()->getName() == 11172 SecondTN.getAsTemplateDecl()->getName()) { 11173 // FIXME: This fixes a bad diagnostic where both templates are named 11174 // the same. This particular case is a bit difficult since: 11175 // 1) It is passed as a string to the diagnostic printer. 11176 // 2) The diagnostic printer only attempts to find a better 11177 // name for types, not decls. 11178 // Ideally, this should folded into the diagnostic printer. 11179 S.Diag(Templated->getLocation(), 11180 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11181 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11182 return; 11183 } 11184 } 11185 } 11186 11187 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11188 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11189 return; 11190 11191 // FIXME: For generic lambda parameters, check if the function is a lambda 11192 // call operator, and if so, emit a prettier and more informative 11193 // diagnostic that mentions 'auto' and lambda in addition to 11194 // (or instead of?) the canonical template type parameters. 11195 S.Diag(Templated->getLocation(), 11196 diag::note_ovl_candidate_non_deduced_mismatch) 11197 << FirstTA << SecondTA; 11198 return; 11199 } 11200 // TODO: diagnose these individually, then kill off 11201 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11202 case Sema::TDK_MiscellaneousDeductionFailure: 11203 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11204 MaybeEmitInheritedConstructorNote(S, Found); 11205 return; 11206 case Sema::TDK_CUDATargetMismatch: 11207 S.Diag(Templated->getLocation(), 11208 diag::note_cuda_ovl_candidate_target_mismatch); 11209 return; 11210 } 11211 } 11212 11213 /// Diagnose a failed template-argument deduction, for function calls. 11214 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11215 unsigned NumArgs, 11216 bool TakingCandidateAddress) { 11217 unsigned TDK = Cand->DeductionFailure.Result; 11218 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11219 if (CheckArityMismatch(S, Cand, NumArgs)) 11220 return; 11221 } 11222 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11223 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11224 } 11225 11226 /// CUDA: diagnose an invalid call across targets. 11227 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11228 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 11229 FunctionDecl *Callee = Cand->Function; 11230 11231 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11232 CalleeTarget = S.IdentifyCUDATarget(Callee); 11233 11234 std::string FnDesc; 11235 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11236 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11237 Cand->getRewriteKind(), FnDesc); 11238 11239 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11240 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11241 << FnDesc /* Ignored */ 11242 << CalleeTarget << CallerTarget; 11243 11244 // This could be an implicit constructor for which we could not infer the 11245 // target due to a collsion. Diagnose that case. 11246 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11247 if (Meth != nullptr && Meth->isImplicit()) { 11248 CXXRecordDecl *ParentClass = Meth->getParent(); 11249 Sema::CXXSpecialMember CSM; 11250 11251 switch (FnKindPair.first) { 11252 default: 11253 return; 11254 case oc_implicit_default_constructor: 11255 CSM = Sema::CXXDefaultConstructor; 11256 break; 11257 case oc_implicit_copy_constructor: 11258 CSM = Sema::CXXCopyConstructor; 11259 break; 11260 case oc_implicit_move_constructor: 11261 CSM = Sema::CXXMoveConstructor; 11262 break; 11263 case oc_implicit_copy_assignment: 11264 CSM = Sema::CXXCopyAssignment; 11265 break; 11266 case oc_implicit_move_assignment: 11267 CSM = Sema::CXXMoveAssignment; 11268 break; 11269 }; 11270 11271 bool ConstRHS = false; 11272 if (Meth->getNumParams()) { 11273 if (const ReferenceType *RT = 11274 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11275 ConstRHS = RT->getPointeeType().isConstQualified(); 11276 } 11277 } 11278 11279 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11280 /* ConstRHS */ ConstRHS, 11281 /* Diagnose */ true); 11282 } 11283 } 11284 11285 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11286 FunctionDecl *Callee = Cand->Function; 11287 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11288 11289 S.Diag(Callee->getLocation(), 11290 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11291 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11292 } 11293 11294 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11295 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11296 assert(ES.isExplicit() && "not an explicit candidate"); 11297 11298 unsigned Kind; 11299 switch (Cand->Function->getDeclKind()) { 11300 case Decl::Kind::CXXConstructor: 11301 Kind = 0; 11302 break; 11303 case Decl::Kind::CXXConversion: 11304 Kind = 1; 11305 break; 11306 case Decl::Kind::CXXDeductionGuide: 11307 Kind = Cand->Function->isImplicit() ? 0 : 2; 11308 break; 11309 default: 11310 llvm_unreachable("invalid Decl"); 11311 } 11312 11313 // Note the location of the first (in-class) declaration; a redeclaration 11314 // (particularly an out-of-class definition) will typically lack the 11315 // 'explicit' specifier. 11316 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11317 FunctionDecl *First = Cand->Function->getFirstDecl(); 11318 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11319 First = Pattern->getFirstDecl(); 11320 11321 S.Diag(First->getLocation(), 11322 diag::note_ovl_candidate_explicit) 11323 << Kind << (ES.getExpr() ? 1 : 0) 11324 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11325 } 11326 11327 /// Generates a 'note' diagnostic for an overload candidate. We've 11328 /// already generated a primary error at the call site. 11329 /// 11330 /// It really does need to be a single diagnostic with its caret 11331 /// pointed at the candidate declaration. Yes, this creates some 11332 /// major challenges of technical writing. Yes, this makes pointing 11333 /// out problems with specific arguments quite awkward. It's still 11334 /// better than generating twenty screens of text for every failed 11335 /// overload. 11336 /// 11337 /// It would be great to be able to express per-candidate problems 11338 /// more richly for those diagnostic clients that cared, but we'd 11339 /// still have to be just as careful with the default diagnostics. 11340 /// \param CtorDestAS Addr space of object being constructed (for ctor 11341 /// candidates only). 11342 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11343 unsigned NumArgs, 11344 bool TakingCandidateAddress, 11345 LangAS CtorDestAS = LangAS::Default) { 11346 FunctionDecl *Fn = Cand->Function; 11347 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11348 return; 11349 11350 // There is no physical candidate declaration to point to for OpenCL builtins. 11351 // Except for failed conversions, the notes are identical for each candidate, 11352 // so do not generate such notes. 11353 if (S.getLangOpts().OpenCL && Fn->isImplicit() && 11354 Cand->FailureKind != ovl_fail_bad_conversion) 11355 return; 11356 11357 // Note deleted candidates, but only if they're viable. 11358 if (Cand->Viable) { 11359 if (Fn->isDeleted()) { 11360 std::string FnDesc; 11361 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11362 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11363 Cand->getRewriteKind(), FnDesc); 11364 11365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11366 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11367 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11368 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11369 return; 11370 } 11371 11372 // We don't really have anything else to say about viable candidates. 11373 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11374 return; 11375 } 11376 11377 switch (Cand->FailureKind) { 11378 case ovl_fail_too_many_arguments: 11379 case ovl_fail_too_few_arguments: 11380 return DiagnoseArityMismatch(S, Cand, NumArgs); 11381 11382 case ovl_fail_bad_deduction: 11383 return DiagnoseBadDeduction(S, Cand, NumArgs, 11384 TakingCandidateAddress); 11385 11386 case ovl_fail_illegal_constructor: { 11387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11388 << (Fn->getPrimaryTemplate() ? 1 : 0); 11389 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11390 return; 11391 } 11392 11393 case ovl_fail_object_addrspace_mismatch: { 11394 Qualifiers QualsForPrinting; 11395 QualsForPrinting.setAddressSpace(CtorDestAS); 11396 S.Diag(Fn->getLocation(), 11397 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11398 << QualsForPrinting; 11399 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11400 return; 11401 } 11402 11403 case ovl_fail_trivial_conversion: 11404 case ovl_fail_bad_final_conversion: 11405 case ovl_fail_final_conversion_not_exact: 11406 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11407 11408 case ovl_fail_bad_conversion: { 11409 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11410 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11411 if (Cand->Conversions[I].isBad()) 11412 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11413 11414 // FIXME: this currently happens when we're called from SemaInit 11415 // when user-conversion overload fails. Figure out how to handle 11416 // those conditions and diagnose them well. 11417 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11418 } 11419 11420 case ovl_fail_bad_target: 11421 return DiagnoseBadTarget(S, Cand); 11422 11423 case ovl_fail_enable_if: 11424 return DiagnoseFailedEnableIfAttr(S, Cand); 11425 11426 case ovl_fail_explicit: 11427 return DiagnoseFailedExplicitSpec(S, Cand); 11428 11429 case ovl_fail_inhctor_slice: 11430 // It's generally not interesting to note copy/move constructors here. 11431 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11432 return; 11433 S.Diag(Fn->getLocation(), 11434 diag::note_ovl_candidate_inherited_constructor_slice) 11435 << (Fn->getPrimaryTemplate() ? 1 : 0) 11436 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11437 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11438 return; 11439 11440 case ovl_fail_addr_not_available: { 11441 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11442 (void)Available; 11443 assert(!Available); 11444 break; 11445 } 11446 case ovl_non_default_multiversion_function: 11447 // Do nothing, these should simply be ignored. 11448 break; 11449 11450 case ovl_fail_constraints_not_satisfied: { 11451 std::string FnDesc; 11452 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11453 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11454 Cand->getRewriteKind(), FnDesc); 11455 11456 S.Diag(Fn->getLocation(), 11457 diag::note_ovl_candidate_constraints_not_satisfied) 11458 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11459 << FnDesc /* Ignored */; 11460 ConstraintSatisfaction Satisfaction; 11461 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11462 break; 11463 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11464 } 11465 } 11466 } 11467 11468 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11469 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11470 return; 11471 11472 // Desugar the type of the surrogate down to a function type, 11473 // retaining as many typedefs as possible while still showing 11474 // the function type (and, therefore, its parameter types). 11475 QualType FnType = Cand->Surrogate->getConversionType(); 11476 bool isLValueReference = false; 11477 bool isRValueReference = false; 11478 bool isPointer = false; 11479 if (const LValueReferenceType *FnTypeRef = 11480 FnType->getAs<LValueReferenceType>()) { 11481 FnType = FnTypeRef->getPointeeType(); 11482 isLValueReference = true; 11483 } else if (const RValueReferenceType *FnTypeRef = 11484 FnType->getAs<RValueReferenceType>()) { 11485 FnType = FnTypeRef->getPointeeType(); 11486 isRValueReference = true; 11487 } 11488 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11489 FnType = FnTypePtr->getPointeeType(); 11490 isPointer = true; 11491 } 11492 // Desugar down to a function type. 11493 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11494 // Reconstruct the pointer/reference as appropriate. 11495 if (isPointer) FnType = S.Context.getPointerType(FnType); 11496 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11497 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11498 11499 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11500 << FnType; 11501 } 11502 11503 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11504 SourceLocation OpLoc, 11505 OverloadCandidate *Cand) { 11506 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11507 std::string TypeStr("operator"); 11508 TypeStr += Opc; 11509 TypeStr += "("; 11510 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11511 if (Cand->Conversions.size() == 1) { 11512 TypeStr += ")"; 11513 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11514 } else { 11515 TypeStr += ", "; 11516 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11517 TypeStr += ")"; 11518 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11519 } 11520 } 11521 11522 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11523 OverloadCandidate *Cand) { 11524 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11525 if (ICS.isBad()) break; // all meaningless after first invalid 11526 if (!ICS.isAmbiguous()) continue; 11527 11528 ICS.DiagnoseAmbiguousConversion( 11529 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11530 } 11531 } 11532 11533 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11534 if (Cand->Function) 11535 return Cand->Function->getLocation(); 11536 if (Cand->IsSurrogate) 11537 return Cand->Surrogate->getLocation(); 11538 return SourceLocation(); 11539 } 11540 11541 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11542 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11543 case Sema::TDK_Success: 11544 case Sema::TDK_NonDependentConversionFailure: 11545 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11546 11547 case Sema::TDK_Invalid: 11548 case Sema::TDK_Incomplete: 11549 case Sema::TDK_IncompletePack: 11550 return 1; 11551 11552 case Sema::TDK_Underqualified: 11553 case Sema::TDK_Inconsistent: 11554 return 2; 11555 11556 case Sema::TDK_SubstitutionFailure: 11557 case Sema::TDK_DeducedMismatch: 11558 case Sema::TDK_ConstraintsNotSatisfied: 11559 case Sema::TDK_DeducedMismatchNested: 11560 case Sema::TDK_NonDeducedMismatch: 11561 case Sema::TDK_MiscellaneousDeductionFailure: 11562 case Sema::TDK_CUDATargetMismatch: 11563 return 3; 11564 11565 case Sema::TDK_InstantiationDepth: 11566 return 4; 11567 11568 case Sema::TDK_InvalidExplicitArguments: 11569 return 5; 11570 11571 case Sema::TDK_TooManyArguments: 11572 case Sema::TDK_TooFewArguments: 11573 return 6; 11574 } 11575 llvm_unreachable("Unhandled deduction result"); 11576 } 11577 11578 namespace { 11579 struct CompareOverloadCandidatesForDisplay { 11580 Sema &S; 11581 SourceLocation Loc; 11582 size_t NumArgs; 11583 OverloadCandidateSet::CandidateSetKind CSK; 11584 11585 CompareOverloadCandidatesForDisplay( 11586 Sema &S, SourceLocation Loc, size_t NArgs, 11587 OverloadCandidateSet::CandidateSetKind CSK) 11588 : S(S), NumArgs(NArgs), CSK(CSK) {} 11589 11590 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11591 // If there are too many or too few arguments, that's the high-order bit we 11592 // want to sort by, even if the immediate failure kind was something else. 11593 if (C->FailureKind == ovl_fail_too_many_arguments || 11594 C->FailureKind == ovl_fail_too_few_arguments) 11595 return static_cast<OverloadFailureKind>(C->FailureKind); 11596 11597 if (C->Function) { 11598 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11599 return ovl_fail_too_many_arguments; 11600 if (NumArgs < C->Function->getMinRequiredArguments()) 11601 return ovl_fail_too_few_arguments; 11602 } 11603 11604 return static_cast<OverloadFailureKind>(C->FailureKind); 11605 } 11606 11607 bool operator()(const OverloadCandidate *L, 11608 const OverloadCandidate *R) { 11609 // Fast-path this check. 11610 if (L == R) return false; 11611 11612 // Order first by viability. 11613 if (L->Viable) { 11614 if (!R->Viable) return true; 11615 11616 // TODO: introduce a tri-valued comparison for overload 11617 // candidates. Would be more worthwhile if we had a sort 11618 // that could exploit it. 11619 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11620 return true; 11621 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11622 return false; 11623 } else if (R->Viable) 11624 return false; 11625 11626 assert(L->Viable == R->Viable); 11627 11628 // Criteria by which we can sort non-viable candidates: 11629 if (!L->Viable) { 11630 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11631 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11632 11633 // 1. Arity mismatches come after other candidates. 11634 if (LFailureKind == ovl_fail_too_many_arguments || 11635 LFailureKind == ovl_fail_too_few_arguments) { 11636 if (RFailureKind == ovl_fail_too_many_arguments || 11637 RFailureKind == ovl_fail_too_few_arguments) { 11638 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11639 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11640 if (LDist == RDist) { 11641 if (LFailureKind == RFailureKind) 11642 // Sort non-surrogates before surrogates. 11643 return !L->IsSurrogate && R->IsSurrogate; 11644 // Sort candidates requiring fewer parameters than there were 11645 // arguments given after candidates requiring more parameters 11646 // than there were arguments given. 11647 return LFailureKind == ovl_fail_too_many_arguments; 11648 } 11649 return LDist < RDist; 11650 } 11651 return false; 11652 } 11653 if (RFailureKind == ovl_fail_too_many_arguments || 11654 RFailureKind == ovl_fail_too_few_arguments) 11655 return true; 11656 11657 // 2. Bad conversions come first and are ordered by the number 11658 // of bad conversions and quality of good conversions. 11659 if (LFailureKind == ovl_fail_bad_conversion) { 11660 if (RFailureKind != ovl_fail_bad_conversion) 11661 return true; 11662 11663 // The conversion that can be fixed with a smaller number of changes, 11664 // comes first. 11665 unsigned numLFixes = L->Fix.NumConversionsFixed; 11666 unsigned numRFixes = R->Fix.NumConversionsFixed; 11667 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11668 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11669 if (numLFixes != numRFixes) { 11670 return numLFixes < numRFixes; 11671 } 11672 11673 // If there's any ordering between the defined conversions... 11674 // FIXME: this might not be transitive. 11675 assert(L->Conversions.size() == R->Conversions.size()); 11676 11677 int leftBetter = 0; 11678 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11679 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11680 switch (CompareImplicitConversionSequences(S, Loc, 11681 L->Conversions[I], 11682 R->Conversions[I])) { 11683 case ImplicitConversionSequence::Better: 11684 leftBetter++; 11685 break; 11686 11687 case ImplicitConversionSequence::Worse: 11688 leftBetter--; 11689 break; 11690 11691 case ImplicitConversionSequence::Indistinguishable: 11692 break; 11693 } 11694 } 11695 if (leftBetter > 0) return true; 11696 if (leftBetter < 0) return false; 11697 11698 } else if (RFailureKind == ovl_fail_bad_conversion) 11699 return false; 11700 11701 if (LFailureKind == ovl_fail_bad_deduction) { 11702 if (RFailureKind != ovl_fail_bad_deduction) 11703 return true; 11704 11705 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11706 return RankDeductionFailure(L->DeductionFailure) 11707 < RankDeductionFailure(R->DeductionFailure); 11708 } else if (RFailureKind == ovl_fail_bad_deduction) 11709 return false; 11710 11711 // TODO: others? 11712 } 11713 11714 // Sort everything else by location. 11715 SourceLocation LLoc = GetLocationForCandidate(L); 11716 SourceLocation RLoc = GetLocationForCandidate(R); 11717 11718 // Put candidates without locations (e.g. builtins) at the end. 11719 if (LLoc.isInvalid()) return false; 11720 if (RLoc.isInvalid()) return true; 11721 11722 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11723 } 11724 }; 11725 } 11726 11727 /// CompleteNonViableCandidate - Normally, overload resolution only 11728 /// computes up to the first bad conversion. Produces the FixIt set if 11729 /// possible. 11730 static void 11731 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11732 ArrayRef<Expr *> Args, 11733 OverloadCandidateSet::CandidateSetKind CSK) { 11734 assert(!Cand->Viable); 11735 11736 // Don't do anything on failures other than bad conversion. 11737 if (Cand->FailureKind != ovl_fail_bad_conversion) 11738 return; 11739 11740 // We only want the FixIts if all the arguments can be corrected. 11741 bool Unfixable = false; 11742 // Use a implicit copy initialization to check conversion fixes. 11743 Cand->Fix.setConversionChecker(TryCopyInitialization); 11744 11745 // Attempt to fix the bad conversion. 11746 unsigned ConvCount = Cand->Conversions.size(); 11747 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11748 ++ConvIdx) { 11749 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11750 if (Cand->Conversions[ConvIdx].isInitialized() && 11751 Cand->Conversions[ConvIdx].isBad()) { 11752 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11753 break; 11754 } 11755 } 11756 11757 // FIXME: this should probably be preserved from the overload 11758 // operation somehow. 11759 bool SuppressUserConversions = false; 11760 11761 unsigned ConvIdx = 0; 11762 unsigned ArgIdx = 0; 11763 ArrayRef<QualType> ParamTypes; 11764 bool Reversed = Cand->isReversed(); 11765 11766 if (Cand->IsSurrogate) { 11767 QualType ConvType 11768 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11769 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11770 ConvType = ConvPtrType->getPointeeType(); 11771 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11772 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11773 ConvIdx = 1; 11774 } else if (Cand->Function) { 11775 ParamTypes = 11776 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11777 if (isa<CXXMethodDecl>(Cand->Function) && 11778 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11779 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11780 ConvIdx = 1; 11781 if (CSK == OverloadCandidateSet::CSK_Operator && 11782 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 11783 Cand->Function->getDeclName().getCXXOverloadedOperator() != 11784 OO_Subscript) 11785 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11786 ArgIdx = 1; 11787 } 11788 } else { 11789 // Builtin operator. 11790 assert(ConvCount <= 3); 11791 ParamTypes = Cand->BuiltinParamTypes; 11792 } 11793 11794 // Fill in the rest of the conversions. 11795 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11796 ConvIdx != ConvCount; 11797 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11798 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11799 if (Cand->Conversions[ConvIdx].isInitialized()) { 11800 // We've already checked this conversion. 11801 } else if (ParamIdx < ParamTypes.size()) { 11802 if (ParamTypes[ParamIdx]->isDependentType()) 11803 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11804 Args[ArgIdx]->getType()); 11805 else { 11806 Cand->Conversions[ConvIdx] = 11807 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11808 SuppressUserConversions, 11809 /*InOverloadResolution=*/true, 11810 /*AllowObjCWritebackConversion=*/ 11811 S.getLangOpts().ObjCAutoRefCount); 11812 // Store the FixIt in the candidate if it exists. 11813 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11814 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11815 } 11816 } else 11817 Cand->Conversions[ConvIdx].setEllipsis(); 11818 } 11819 } 11820 11821 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11822 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11823 SourceLocation OpLoc, 11824 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11825 // Sort the candidates by viability and position. Sorting directly would 11826 // be prohibitive, so we make a set of pointers and sort those. 11827 SmallVector<OverloadCandidate*, 32> Cands; 11828 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11829 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11830 if (!Filter(*Cand)) 11831 continue; 11832 switch (OCD) { 11833 case OCD_AllCandidates: 11834 if (!Cand->Viable) { 11835 if (!Cand->Function && !Cand->IsSurrogate) { 11836 // This a non-viable builtin candidate. We do not, in general, 11837 // want to list every possible builtin candidate. 11838 continue; 11839 } 11840 CompleteNonViableCandidate(S, Cand, Args, Kind); 11841 } 11842 break; 11843 11844 case OCD_ViableCandidates: 11845 if (!Cand->Viable) 11846 continue; 11847 break; 11848 11849 case OCD_AmbiguousCandidates: 11850 if (!Cand->Best) 11851 continue; 11852 break; 11853 } 11854 11855 Cands.push_back(Cand); 11856 } 11857 11858 llvm::stable_sort( 11859 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11860 11861 return Cands; 11862 } 11863 11864 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11865 SourceLocation OpLoc) { 11866 bool DeferHint = false; 11867 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11868 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11869 // host device candidates. 11870 auto WrongSidedCands = 11871 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11872 return (Cand.Viable == false && 11873 Cand.FailureKind == ovl_fail_bad_target) || 11874 (Cand.Function && 11875 Cand.Function->template hasAttr<CUDAHostAttr>() && 11876 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11877 }); 11878 DeferHint = !WrongSidedCands.empty(); 11879 } 11880 return DeferHint; 11881 } 11882 11883 /// When overload resolution fails, prints diagnostic messages containing the 11884 /// candidates in the candidate set. 11885 void OverloadCandidateSet::NoteCandidates( 11886 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11887 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11888 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11889 11890 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11891 11892 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11893 11894 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11895 11896 if (OCD == OCD_AmbiguousCandidates) 11897 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11898 } 11899 11900 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11901 ArrayRef<OverloadCandidate *> Cands, 11902 StringRef Opc, SourceLocation OpLoc) { 11903 bool ReportedAmbiguousConversions = false; 11904 11905 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11906 unsigned CandsShown = 0; 11907 auto I = Cands.begin(), E = Cands.end(); 11908 for (; I != E; ++I) { 11909 OverloadCandidate *Cand = *I; 11910 11911 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11912 ShowOverloads == Ovl_Best) { 11913 break; 11914 } 11915 ++CandsShown; 11916 11917 if (Cand->Function) 11918 NoteFunctionCandidate(S, Cand, Args.size(), 11919 /*TakingCandidateAddress=*/false, DestAS); 11920 else if (Cand->IsSurrogate) 11921 NoteSurrogateCandidate(S, Cand); 11922 else { 11923 assert(Cand->Viable && 11924 "Non-viable built-in candidates are not added to Cands."); 11925 // Generally we only see ambiguities including viable builtin 11926 // operators if overload resolution got screwed up by an 11927 // ambiguous user-defined conversion. 11928 // 11929 // FIXME: It's quite possible for different conversions to see 11930 // different ambiguities, though. 11931 if (!ReportedAmbiguousConversions) { 11932 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11933 ReportedAmbiguousConversions = true; 11934 } 11935 11936 // If this is a viable builtin, print it. 11937 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11938 } 11939 } 11940 11941 // Inform S.Diags that we've shown an overload set with N elements. This may 11942 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11943 S.Diags.overloadCandidatesShown(CandsShown); 11944 11945 if (I != E) 11946 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11947 shouldDeferDiags(S, Args, OpLoc)) 11948 << int(E - I); 11949 } 11950 11951 static SourceLocation 11952 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11953 return Cand->Specialization ? Cand->Specialization->getLocation() 11954 : SourceLocation(); 11955 } 11956 11957 namespace { 11958 struct CompareTemplateSpecCandidatesForDisplay { 11959 Sema &S; 11960 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11961 11962 bool operator()(const TemplateSpecCandidate *L, 11963 const TemplateSpecCandidate *R) { 11964 // Fast-path this check. 11965 if (L == R) 11966 return false; 11967 11968 // Assuming that both candidates are not matches... 11969 11970 // Sort by the ranking of deduction failures. 11971 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11972 return RankDeductionFailure(L->DeductionFailure) < 11973 RankDeductionFailure(R->DeductionFailure); 11974 11975 // Sort everything else by location. 11976 SourceLocation LLoc = GetLocationForCandidate(L); 11977 SourceLocation RLoc = GetLocationForCandidate(R); 11978 11979 // Put candidates without locations (e.g. builtins) at the end. 11980 if (LLoc.isInvalid()) 11981 return false; 11982 if (RLoc.isInvalid()) 11983 return true; 11984 11985 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11986 } 11987 }; 11988 } 11989 11990 /// Diagnose a template argument deduction failure. 11991 /// We are treating these failures as overload failures due to bad 11992 /// deductions. 11993 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11994 bool ForTakingAddress) { 11995 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11996 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11997 } 11998 11999 void TemplateSpecCandidateSet::destroyCandidates() { 12000 for (iterator i = begin(), e = end(); i != e; ++i) { 12001 i->DeductionFailure.Destroy(); 12002 } 12003 } 12004 12005 void TemplateSpecCandidateSet::clear() { 12006 destroyCandidates(); 12007 Candidates.clear(); 12008 } 12009 12010 /// NoteCandidates - When no template specialization match is found, prints 12011 /// diagnostic messages containing the non-matching specializations that form 12012 /// the candidate set. 12013 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 12014 /// OCD == OCD_AllCandidates and Cand->Viable == false. 12015 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 12016 // Sort the candidates by position (assuming no candidate is a match). 12017 // Sorting directly would be prohibitive, so we make a set of pointers 12018 // and sort those. 12019 SmallVector<TemplateSpecCandidate *, 32> Cands; 12020 Cands.reserve(size()); 12021 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12022 if (Cand->Specialization) 12023 Cands.push_back(Cand); 12024 // Otherwise, this is a non-matching builtin candidate. We do not, 12025 // in general, want to list every possible builtin candidate. 12026 } 12027 12028 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 12029 12030 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 12031 // for generalization purposes (?). 12032 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12033 12034 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 12035 unsigned CandsShown = 0; 12036 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 12037 TemplateSpecCandidate *Cand = *I; 12038 12039 // Set an arbitrary limit on the number of candidates we'll spam 12040 // the user with. FIXME: This limit should depend on details of the 12041 // candidate list. 12042 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 12043 break; 12044 ++CandsShown; 12045 12046 assert(Cand->Specialization && 12047 "Non-matching built-in candidates are not added to Cands."); 12048 Cand->NoteDeductionFailure(S, ForTakingAddress); 12049 } 12050 12051 if (I != E) 12052 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 12053 } 12054 12055 // [PossiblyAFunctionType] --> [Return] 12056 // NonFunctionType --> NonFunctionType 12057 // R (A) --> R(A) 12058 // R (*)(A) --> R (A) 12059 // R (&)(A) --> R (A) 12060 // R (S::*)(A) --> R (A) 12061 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 12062 QualType Ret = PossiblyAFunctionType; 12063 if (const PointerType *ToTypePtr = 12064 PossiblyAFunctionType->getAs<PointerType>()) 12065 Ret = ToTypePtr->getPointeeType(); 12066 else if (const ReferenceType *ToTypeRef = 12067 PossiblyAFunctionType->getAs<ReferenceType>()) 12068 Ret = ToTypeRef->getPointeeType(); 12069 else if (const MemberPointerType *MemTypePtr = 12070 PossiblyAFunctionType->getAs<MemberPointerType>()) 12071 Ret = MemTypePtr->getPointeeType(); 12072 Ret = 12073 Context.getCanonicalType(Ret).getUnqualifiedType(); 12074 return Ret; 12075 } 12076 12077 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 12078 bool Complain = true) { 12079 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 12080 S.DeduceReturnType(FD, Loc, Complain)) 12081 return true; 12082 12083 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 12084 if (S.getLangOpts().CPlusPlus17 && 12085 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 12086 !S.ResolveExceptionSpec(Loc, FPT)) 12087 return true; 12088 12089 return false; 12090 } 12091 12092 namespace { 12093 // A helper class to help with address of function resolution 12094 // - allows us to avoid passing around all those ugly parameters 12095 class AddressOfFunctionResolver { 12096 Sema& S; 12097 Expr* SourceExpr; 12098 const QualType& TargetType; 12099 QualType TargetFunctionType; // Extracted function type from target type 12100 12101 bool Complain; 12102 //DeclAccessPair& ResultFunctionAccessPair; 12103 ASTContext& Context; 12104 12105 bool TargetTypeIsNonStaticMemberFunction; 12106 bool FoundNonTemplateFunction; 12107 bool StaticMemberFunctionFromBoundPointer; 12108 bool HasComplained; 12109 12110 OverloadExpr::FindResult OvlExprInfo; 12111 OverloadExpr *OvlExpr; 12112 TemplateArgumentListInfo OvlExplicitTemplateArgs; 12113 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 12114 TemplateSpecCandidateSet FailedCandidates; 12115 12116 public: 12117 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 12118 const QualType &TargetType, bool Complain) 12119 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 12120 Complain(Complain), Context(S.getASTContext()), 12121 TargetTypeIsNonStaticMemberFunction( 12122 !!TargetType->getAs<MemberPointerType>()), 12123 FoundNonTemplateFunction(false), 12124 StaticMemberFunctionFromBoundPointer(false), 12125 HasComplained(false), 12126 OvlExprInfo(OverloadExpr::find(SourceExpr)), 12127 OvlExpr(OvlExprInfo.Expression), 12128 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 12129 ExtractUnqualifiedFunctionTypeFromTargetType(); 12130 12131 if (TargetFunctionType->isFunctionType()) { 12132 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 12133 if (!UME->isImplicitAccess() && 12134 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 12135 StaticMemberFunctionFromBoundPointer = true; 12136 } else if (OvlExpr->hasExplicitTemplateArgs()) { 12137 DeclAccessPair dap; 12138 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 12139 OvlExpr, false, &dap)) { 12140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 12141 if (!Method->isStatic()) { 12142 // If the target type is a non-function type and the function found 12143 // is a non-static member function, pretend as if that was the 12144 // target, it's the only possible type to end up with. 12145 TargetTypeIsNonStaticMemberFunction = true; 12146 12147 // And skip adding the function if its not in the proper form. 12148 // We'll diagnose this due to an empty set of functions. 12149 if (!OvlExprInfo.HasFormOfMemberPointer) 12150 return; 12151 } 12152 12153 Matches.push_back(std::make_pair(dap, Fn)); 12154 } 12155 return; 12156 } 12157 12158 if (OvlExpr->hasExplicitTemplateArgs()) 12159 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 12160 12161 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 12162 // C++ [over.over]p4: 12163 // If more than one function is selected, [...] 12164 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12165 if (FoundNonTemplateFunction) 12166 EliminateAllTemplateMatches(); 12167 else 12168 EliminateAllExceptMostSpecializedTemplate(); 12169 } 12170 } 12171 12172 if (S.getLangOpts().CUDA && Matches.size() > 1) 12173 EliminateSuboptimalCudaMatches(); 12174 } 12175 12176 bool hasComplained() const { return HasComplained; } 12177 12178 private: 12179 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12180 QualType Discard; 12181 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12182 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12183 } 12184 12185 /// \return true if A is considered a better overload candidate for the 12186 /// desired type than B. 12187 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12188 // If A doesn't have exactly the correct type, we don't want to classify it 12189 // as "better" than anything else. This way, the user is required to 12190 // disambiguate for us if there are multiple candidates and no exact match. 12191 return candidateHasExactlyCorrectType(A) && 12192 (!candidateHasExactlyCorrectType(B) || 12193 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12194 } 12195 12196 /// \return true if we were able to eliminate all but one overload candidate, 12197 /// false otherwise. 12198 bool eliminiateSuboptimalOverloadCandidates() { 12199 // Same algorithm as overload resolution -- one pass to pick the "best", 12200 // another pass to be sure that nothing is better than the best. 12201 auto Best = Matches.begin(); 12202 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12203 if (isBetterCandidate(I->second, Best->second)) 12204 Best = I; 12205 12206 const FunctionDecl *BestFn = Best->second; 12207 auto IsBestOrInferiorToBest = [this, BestFn]( 12208 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12209 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12210 }; 12211 12212 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12213 // option, so we can potentially give the user a better error 12214 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12215 return false; 12216 Matches[0] = *Best; 12217 Matches.resize(1); 12218 return true; 12219 } 12220 12221 bool isTargetTypeAFunction() const { 12222 return TargetFunctionType->isFunctionType(); 12223 } 12224 12225 // [ToType] [Return] 12226 12227 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12228 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12229 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12230 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12231 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12232 } 12233 12234 // return true if any matching specializations were found 12235 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12236 const DeclAccessPair& CurAccessFunPair) { 12237 if (CXXMethodDecl *Method 12238 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12239 // Skip non-static function templates when converting to pointer, and 12240 // static when converting to member pointer. 12241 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12242 return false; 12243 } 12244 else if (TargetTypeIsNonStaticMemberFunction) 12245 return false; 12246 12247 // C++ [over.over]p2: 12248 // If the name is a function template, template argument deduction is 12249 // done (14.8.2.2), and if the argument deduction succeeds, the 12250 // resulting template argument list is used to generate a single 12251 // function template specialization, which is added to the set of 12252 // overloaded functions considered. 12253 FunctionDecl *Specialization = nullptr; 12254 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12255 if (Sema::TemplateDeductionResult Result 12256 = S.DeduceTemplateArguments(FunctionTemplate, 12257 &OvlExplicitTemplateArgs, 12258 TargetFunctionType, Specialization, 12259 Info, /*IsAddressOfFunction*/true)) { 12260 // Make a note of the failed deduction for diagnostics. 12261 FailedCandidates.addCandidate() 12262 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12263 MakeDeductionFailureInfo(Context, Result, Info)); 12264 return false; 12265 } 12266 12267 // Template argument deduction ensures that we have an exact match or 12268 // compatible pointer-to-function arguments that would be adjusted by ICS. 12269 // This function template specicalization works. 12270 assert(S.isSameOrCompatibleFunctionType( 12271 Context.getCanonicalType(Specialization->getType()), 12272 Context.getCanonicalType(TargetFunctionType))); 12273 12274 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12275 return false; 12276 12277 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12278 return true; 12279 } 12280 12281 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12282 const DeclAccessPair& CurAccessFunPair) { 12283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12284 // Skip non-static functions when converting to pointer, and static 12285 // when converting to member pointer. 12286 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12287 return false; 12288 } 12289 else if (TargetTypeIsNonStaticMemberFunction) 12290 return false; 12291 12292 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12293 if (S.getLangOpts().CUDA) 12294 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) 12295 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12296 return false; 12297 if (FunDecl->isMultiVersion()) { 12298 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12299 if (TA && !TA->isDefaultVersion()) 12300 return false; 12301 } 12302 12303 // If any candidate has a placeholder return type, trigger its deduction 12304 // now. 12305 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12306 Complain)) { 12307 HasComplained |= Complain; 12308 return false; 12309 } 12310 12311 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12312 return false; 12313 12314 // If we're in C, we need to support types that aren't exactly identical. 12315 if (!S.getLangOpts().CPlusPlus || 12316 candidateHasExactlyCorrectType(FunDecl)) { 12317 Matches.push_back(std::make_pair( 12318 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12319 FoundNonTemplateFunction = true; 12320 return true; 12321 } 12322 } 12323 12324 return false; 12325 } 12326 12327 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12328 bool Ret = false; 12329 12330 // If the overload expression doesn't have the form of a pointer to 12331 // member, don't try to convert it to a pointer-to-member type. 12332 if (IsInvalidFormOfPointerToMemberFunction()) 12333 return false; 12334 12335 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12336 E = OvlExpr->decls_end(); 12337 I != E; ++I) { 12338 // Look through any using declarations to find the underlying function. 12339 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12340 12341 // C++ [over.over]p3: 12342 // Non-member functions and static member functions match 12343 // targets of type "pointer-to-function" or "reference-to-function." 12344 // Nonstatic member functions match targets of 12345 // type "pointer-to-member-function." 12346 // Note that according to DR 247, the containing class does not matter. 12347 if (FunctionTemplateDecl *FunctionTemplate 12348 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12349 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12350 Ret = true; 12351 } 12352 // If we have explicit template arguments supplied, skip non-templates. 12353 else if (!OvlExpr->hasExplicitTemplateArgs() && 12354 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12355 Ret = true; 12356 } 12357 assert(Ret || Matches.empty()); 12358 return Ret; 12359 } 12360 12361 void EliminateAllExceptMostSpecializedTemplate() { 12362 // [...] and any given function template specialization F1 is 12363 // eliminated if the set contains a second function template 12364 // specialization whose function template is more specialized 12365 // than the function template of F1 according to the partial 12366 // ordering rules of 14.5.5.2. 12367 12368 // The algorithm specified above is quadratic. We instead use a 12369 // two-pass algorithm (similar to the one used to identify the 12370 // best viable function in an overload set) that identifies the 12371 // best function template (if it exists). 12372 12373 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12374 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12375 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12376 12377 // TODO: It looks like FailedCandidates does not serve much purpose 12378 // here, since the no_viable diagnostic has index 0. 12379 UnresolvedSetIterator Result = S.getMostSpecialized( 12380 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12381 SourceExpr->getBeginLoc(), S.PDiag(), 12382 S.PDiag(diag::err_addr_ovl_ambiguous) 12383 << Matches[0].second->getDeclName(), 12384 S.PDiag(diag::note_ovl_candidate) 12385 << (unsigned)oc_function << (unsigned)ocs_described_template, 12386 Complain, TargetFunctionType); 12387 12388 if (Result != MatchesCopy.end()) { 12389 // Make it the first and only element 12390 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12391 Matches[0].second = cast<FunctionDecl>(*Result); 12392 Matches.resize(1); 12393 } else 12394 HasComplained |= Complain; 12395 } 12396 12397 void EliminateAllTemplateMatches() { 12398 // [...] any function template specializations in the set are 12399 // eliminated if the set also contains a non-template function, [...] 12400 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12401 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12402 ++I; 12403 else { 12404 Matches[I] = Matches[--N]; 12405 Matches.resize(N); 12406 } 12407 } 12408 } 12409 12410 void EliminateSuboptimalCudaMatches() { 12411 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), 12412 Matches); 12413 } 12414 12415 public: 12416 void ComplainNoMatchesFound() const { 12417 assert(Matches.empty()); 12418 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12419 << OvlExpr->getName() << TargetFunctionType 12420 << OvlExpr->getSourceRange(); 12421 if (FailedCandidates.empty()) 12422 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12423 /*TakingAddress=*/true); 12424 else { 12425 // We have some deduction failure messages. Use them to diagnose 12426 // the function templates, and diagnose the non-template candidates 12427 // normally. 12428 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12429 IEnd = OvlExpr->decls_end(); 12430 I != IEnd; ++I) 12431 if (FunctionDecl *Fun = 12432 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12433 if (!functionHasPassObjectSizeParams(Fun)) 12434 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12435 /*TakingAddress=*/true); 12436 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12437 } 12438 } 12439 12440 bool IsInvalidFormOfPointerToMemberFunction() const { 12441 return TargetTypeIsNonStaticMemberFunction && 12442 !OvlExprInfo.HasFormOfMemberPointer; 12443 } 12444 12445 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12446 // TODO: Should we condition this on whether any functions might 12447 // have matched, or is it more appropriate to do that in callers? 12448 // TODO: a fixit wouldn't hurt. 12449 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12450 << TargetType << OvlExpr->getSourceRange(); 12451 } 12452 12453 bool IsStaticMemberFunctionFromBoundPointer() const { 12454 return StaticMemberFunctionFromBoundPointer; 12455 } 12456 12457 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12458 S.Diag(OvlExpr->getBeginLoc(), 12459 diag::err_invalid_form_pointer_member_function) 12460 << OvlExpr->getSourceRange(); 12461 } 12462 12463 void ComplainOfInvalidConversion() const { 12464 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12465 << OvlExpr->getName() << TargetType; 12466 } 12467 12468 void ComplainMultipleMatchesFound() const { 12469 assert(Matches.size() > 1); 12470 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12471 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12472 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12473 /*TakingAddress=*/true); 12474 } 12475 12476 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12477 12478 int getNumMatches() const { return Matches.size(); } 12479 12480 FunctionDecl* getMatchingFunctionDecl() const { 12481 if (Matches.size() != 1) return nullptr; 12482 return Matches[0].second; 12483 } 12484 12485 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12486 if (Matches.size() != 1) return nullptr; 12487 return &Matches[0].first; 12488 } 12489 }; 12490 } 12491 12492 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12493 /// an overloaded function (C++ [over.over]), where @p From is an 12494 /// expression with overloaded function type and @p ToType is the type 12495 /// we're trying to resolve to. For example: 12496 /// 12497 /// @code 12498 /// int f(double); 12499 /// int f(int); 12500 /// 12501 /// int (*pfd)(double) = f; // selects f(double) 12502 /// @endcode 12503 /// 12504 /// This routine returns the resulting FunctionDecl if it could be 12505 /// resolved, and NULL otherwise. When @p Complain is true, this 12506 /// routine will emit diagnostics if there is an error. 12507 FunctionDecl * 12508 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12509 QualType TargetType, 12510 bool Complain, 12511 DeclAccessPair &FoundResult, 12512 bool *pHadMultipleCandidates) { 12513 assert(AddressOfExpr->getType() == Context.OverloadTy); 12514 12515 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12516 Complain); 12517 int NumMatches = Resolver.getNumMatches(); 12518 FunctionDecl *Fn = nullptr; 12519 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12520 if (NumMatches == 0 && ShouldComplain) { 12521 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12522 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12523 else 12524 Resolver.ComplainNoMatchesFound(); 12525 } 12526 else if (NumMatches > 1 && ShouldComplain) 12527 Resolver.ComplainMultipleMatchesFound(); 12528 else if (NumMatches == 1) { 12529 Fn = Resolver.getMatchingFunctionDecl(); 12530 assert(Fn); 12531 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12532 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12533 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12534 if (Complain) { 12535 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12536 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12537 else 12538 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12539 } 12540 } 12541 12542 if (pHadMultipleCandidates) 12543 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12544 return Fn; 12545 } 12546 12547 /// Given an expression that refers to an overloaded function, try to 12548 /// resolve that function to a single function that can have its address taken. 12549 /// This will modify `Pair` iff it returns non-null. 12550 /// 12551 /// This routine can only succeed if from all of the candidates in the overload 12552 /// set for SrcExpr that can have their addresses taken, there is one candidate 12553 /// that is more constrained than the rest. 12554 FunctionDecl * 12555 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12556 OverloadExpr::FindResult R = OverloadExpr::find(E); 12557 OverloadExpr *Ovl = R.Expression; 12558 bool IsResultAmbiguous = false; 12559 FunctionDecl *Result = nullptr; 12560 DeclAccessPair DAP; 12561 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12562 12563 auto CheckMoreConstrained = 12564 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12565 SmallVector<const Expr *, 1> AC1, AC2; 12566 FD1->getAssociatedConstraints(AC1); 12567 FD2->getAssociatedConstraints(AC2); 12568 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12569 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12570 return None; 12571 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12572 return None; 12573 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12574 return None; 12575 return AtLeastAsConstrained1; 12576 }; 12577 12578 // Don't use the AddressOfResolver because we're specifically looking for 12579 // cases where we have one overload candidate that lacks 12580 // enable_if/pass_object_size/... 12581 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12582 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12583 if (!FD) 12584 return nullptr; 12585 12586 if (!checkAddressOfFunctionIsAvailable(FD)) 12587 continue; 12588 12589 // We have more than one result - see if it is more constrained than the 12590 // previous one. 12591 if (Result) { 12592 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12593 Result); 12594 if (!MoreConstrainedThanPrevious) { 12595 IsResultAmbiguous = true; 12596 AmbiguousDecls.push_back(FD); 12597 continue; 12598 } 12599 if (!*MoreConstrainedThanPrevious) 12600 continue; 12601 // FD is more constrained - replace Result with it. 12602 } 12603 IsResultAmbiguous = false; 12604 DAP = I.getPair(); 12605 Result = FD; 12606 } 12607 12608 if (IsResultAmbiguous) 12609 return nullptr; 12610 12611 if (Result) { 12612 SmallVector<const Expr *, 1> ResultAC; 12613 // We skipped over some ambiguous declarations which might be ambiguous with 12614 // the selected result. 12615 for (FunctionDecl *Skipped : AmbiguousDecls) 12616 if (!CheckMoreConstrained(Skipped, Result)) 12617 return nullptr; 12618 Pair = DAP; 12619 } 12620 return Result; 12621 } 12622 12623 /// Given an overloaded function, tries to turn it into a non-overloaded 12624 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12625 /// will perform access checks, diagnose the use of the resultant decl, and, if 12626 /// requested, potentially perform a function-to-pointer decay. 12627 /// 12628 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12629 /// Otherwise, returns true. This may emit diagnostics and return true. 12630 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12631 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12632 Expr *E = SrcExpr.get(); 12633 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12634 12635 DeclAccessPair DAP; 12636 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12637 if (!Found || Found->isCPUDispatchMultiVersion() || 12638 Found->isCPUSpecificMultiVersion()) 12639 return false; 12640 12641 // Emitting multiple diagnostics for a function that is both inaccessible and 12642 // unavailable is consistent with our behavior elsewhere. So, always check 12643 // for both. 12644 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12645 CheckAddressOfMemberAccess(E, DAP); 12646 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12647 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12648 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12649 else 12650 SrcExpr = Fixed; 12651 return true; 12652 } 12653 12654 /// Given an expression that refers to an overloaded function, try to 12655 /// resolve that overloaded function expression down to a single function. 12656 /// 12657 /// This routine can only resolve template-ids that refer to a single function 12658 /// template, where that template-id refers to a single template whose template 12659 /// arguments are either provided by the template-id or have defaults, 12660 /// as described in C++0x [temp.arg.explicit]p3. 12661 /// 12662 /// If no template-ids are found, no diagnostics are emitted and NULL is 12663 /// returned. 12664 FunctionDecl * 12665 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12666 bool Complain, 12667 DeclAccessPair *FoundResult) { 12668 // C++ [over.over]p1: 12669 // [...] [Note: any redundant set of parentheses surrounding the 12670 // overloaded function name is ignored (5.1). ] 12671 // C++ [over.over]p1: 12672 // [...] The overloaded function name can be preceded by the & 12673 // operator. 12674 12675 // If we didn't actually find any template-ids, we're done. 12676 if (!ovl->hasExplicitTemplateArgs()) 12677 return nullptr; 12678 12679 TemplateArgumentListInfo ExplicitTemplateArgs; 12680 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12681 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12682 12683 // Look through all of the overloaded functions, searching for one 12684 // whose type matches exactly. 12685 FunctionDecl *Matched = nullptr; 12686 for (UnresolvedSetIterator I = ovl->decls_begin(), 12687 E = ovl->decls_end(); I != E; ++I) { 12688 // C++0x [temp.arg.explicit]p3: 12689 // [...] In contexts where deduction is done and fails, or in contexts 12690 // where deduction is not done, if a template argument list is 12691 // specified and it, along with any default template arguments, 12692 // identifies a single function template specialization, then the 12693 // template-id is an lvalue for the function template specialization. 12694 FunctionTemplateDecl *FunctionTemplate 12695 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12696 12697 // C++ [over.over]p2: 12698 // If the name is a function template, template argument deduction is 12699 // done (14.8.2.2), and if the argument deduction succeeds, the 12700 // resulting template argument list is used to generate a single 12701 // function template specialization, which is added to the set of 12702 // overloaded functions considered. 12703 FunctionDecl *Specialization = nullptr; 12704 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12705 if (TemplateDeductionResult Result 12706 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12707 Specialization, Info, 12708 /*IsAddressOfFunction*/true)) { 12709 // Make a note of the failed deduction for diagnostics. 12710 // TODO: Actually use the failed-deduction info? 12711 FailedCandidates.addCandidate() 12712 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12713 MakeDeductionFailureInfo(Context, Result, Info)); 12714 continue; 12715 } 12716 12717 assert(Specialization && "no specialization and no error?"); 12718 12719 // Multiple matches; we can't resolve to a single declaration. 12720 if (Matched) { 12721 if (Complain) { 12722 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12723 << ovl->getName(); 12724 NoteAllOverloadCandidates(ovl); 12725 } 12726 return nullptr; 12727 } 12728 12729 Matched = Specialization; 12730 if (FoundResult) *FoundResult = I.getPair(); 12731 } 12732 12733 if (Matched && 12734 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12735 return nullptr; 12736 12737 return Matched; 12738 } 12739 12740 // Resolve and fix an overloaded expression that can be resolved 12741 // because it identifies a single function template specialization. 12742 // 12743 // Last three arguments should only be supplied if Complain = true 12744 // 12745 // Return true if it was logically possible to so resolve the 12746 // expression, regardless of whether or not it succeeded. Always 12747 // returns true if 'complain' is set. 12748 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12749 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12750 bool complain, SourceRange OpRangeForComplaining, 12751 QualType DestTypeForComplaining, 12752 unsigned DiagIDForComplaining) { 12753 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12754 12755 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12756 12757 DeclAccessPair found; 12758 ExprResult SingleFunctionExpression; 12759 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12760 ovl.Expression, /*complain*/ false, &found)) { 12761 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12762 SrcExpr = ExprError(); 12763 return true; 12764 } 12765 12766 // It is only correct to resolve to an instance method if we're 12767 // resolving a form that's permitted to be a pointer to member. 12768 // Otherwise we'll end up making a bound member expression, which 12769 // is illegal in all the contexts we resolve like this. 12770 if (!ovl.HasFormOfMemberPointer && 12771 isa<CXXMethodDecl>(fn) && 12772 cast<CXXMethodDecl>(fn)->isInstance()) { 12773 if (!complain) return false; 12774 12775 Diag(ovl.Expression->getExprLoc(), 12776 diag::err_bound_member_function) 12777 << 0 << ovl.Expression->getSourceRange(); 12778 12779 // TODO: I believe we only end up here if there's a mix of 12780 // static and non-static candidates (otherwise the expression 12781 // would have 'bound member' type, not 'overload' type). 12782 // Ideally we would note which candidate was chosen and why 12783 // the static candidates were rejected. 12784 SrcExpr = ExprError(); 12785 return true; 12786 } 12787 12788 // Fix the expression to refer to 'fn'. 12789 SingleFunctionExpression = 12790 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12791 12792 // If desired, do function-to-pointer decay. 12793 if (doFunctionPointerConverion) { 12794 SingleFunctionExpression = 12795 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12796 if (SingleFunctionExpression.isInvalid()) { 12797 SrcExpr = ExprError(); 12798 return true; 12799 } 12800 } 12801 } 12802 12803 if (!SingleFunctionExpression.isUsable()) { 12804 if (complain) { 12805 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12806 << ovl.Expression->getName() 12807 << DestTypeForComplaining 12808 << OpRangeForComplaining 12809 << ovl.Expression->getQualifierLoc().getSourceRange(); 12810 NoteAllOverloadCandidates(SrcExpr.get()); 12811 12812 SrcExpr = ExprError(); 12813 return true; 12814 } 12815 12816 return false; 12817 } 12818 12819 SrcExpr = SingleFunctionExpression; 12820 return true; 12821 } 12822 12823 /// Add a single candidate to the overload set. 12824 static void AddOverloadedCallCandidate(Sema &S, 12825 DeclAccessPair FoundDecl, 12826 TemplateArgumentListInfo *ExplicitTemplateArgs, 12827 ArrayRef<Expr *> Args, 12828 OverloadCandidateSet &CandidateSet, 12829 bool PartialOverloading, 12830 bool KnownValid) { 12831 NamedDecl *Callee = FoundDecl.getDecl(); 12832 if (isa<UsingShadowDecl>(Callee)) 12833 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12834 12835 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12836 if (ExplicitTemplateArgs) { 12837 assert(!KnownValid && "Explicit template arguments?"); 12838 return; 12839 } 12840 // Prevent ill-formed function decls to be added as overload candidates. 12841 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12842 return; 12843 12844 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12845 /*SuppressUserConversions=*/false, 12846 PartialOverloading); 12847 return; 12848 } 12849 12850 if (FunctionTemplateDecl *FuncTemplate 12851 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12852 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12853 ExplicitTemplateArgs, Args, CandidateSet, 12854 /*SuppressUserConversions=*/false, 12855 PartialOverloading); 12856 return; 12857 } 12858 12859 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12860 } 12861 12862 /// Add the overload candidates named by callee and/or found by argument 12863 /// dependent lookup to the given overload set. 12864 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12865 ArrayRef<Expr *> Args, 12866 OverloadCandidateSet &CandidateSet, 12867 bool PartialOverloading) { 12868 12869 #ifndef NDEBUG 12870 // Verify that ArgumentDependentLookup is consistent with the rules 12871 // in C++0x [basic.lookup.argdep]p3: 12872 // 12873 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12874 // and let Y be the lookup set produced by argument dependent 12875 // lookup (defined as follows). If X contains 12876 // 12877 // -- a declaration of a class member, or 12878 // 12879 // -- a block-scope function declaration that is not a 12880 // using-declaration, or 12881 // 12882 // -- a declaration that is neither a function or a function 12883 // template 12884 // 12885 // then Y is empty. 12886 12887 if (ULE->requiresADL()) { 12888 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12889 E = ULE->decls_end(); I != E; ++I) { 12890 assert(!(*I)->getDeclContext()->isRecord()); 12891 assert(isa<UsingShadowDecl>(*I) || 12892 !(*I)->getDeclContext()->isFunctionOrMethod()); 12893 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12894 } 12895 } 12896 #endif 12897 12898 // It would be nice to avoid this copy. 12899 TemplateArgumentListInfo TABuffer; 12900 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12901 if (ULE->hasExplicitTemplateArgs()) { 12902 ULE->copyTemplateArgumentsInto(TABuffer); 12903 ExplicitTemplateArgs = &TABuffer; 12904 } 12905 12906 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12907 E = ULE->decls_end(); I != E; ++I) 12908 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12909 CandidateSet, PartialOverloading, 12910 /*KnownValid*/ true); 12911 12912 if (ULE->requiresADL()) 12913 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12914 Args, ExplicitTemplateArgs, 12915 CandidateSet, PartialOverloading); 12916 } 12917 12918 /// Add the call candidates from the given set of lookup results to the given 12919 /// overload set. Non-function lookup results are ignored. 12920 void Sema::AddOverloadedCallCandidates( 12921 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12922 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12923 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12924 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12925 CandidateSet, false, /*KnownValid*/ false); 12926 } 12927 12928 /// Determine whether a declaration with the specified name could be moved into 12929 /// a different namespace. 12930 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12931 switch (Name.getCXXOverloadedOperator()) { 12932 case OO_New: case OO_Array_New: 12933 case OO_Delete: case OO_Array_Delete: 12934 return false; 12935 12936 default: 12937 return true; 12938 } 12939 } 12940 12941 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12942 /// template, where the non-dependent name was declared after the template 12943 /// was defined. This is common in code written for a compilers which do not 12944 /// correctly implement two-stage name lookup. 12945 /// 12946 /// Returns true if a viable candidate was found and a diagnostic was issued. 12947 static bool DiagnoseTwoPhaseLookup( 12948 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12949 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12950 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12951 CXXRecordDecl **FoundInClass = nullptr) { 12952 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12953 return false; 12954 12955 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12956 if (DC->isTransparentContext()) 12957 continue; 12958 12959 SemaRef.LookupQualifiedName(R, DC); 12960 12961 if (!R.empty()) { 12962 R.suppressDiagnostics(); 12963 12964 OverloadCandidateSet Candidates(FnLoc, CSK); 12965 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12966 Candidates); 12967 12968 OverloadCandidateSet::iterator Best; 12969 OverloadingResult OR = 12970 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12971 12972 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12973 // We either found non-function declarations or a best viable function 12974 // at class scope. A class-scope lookup result disables ADL. Don't 12975 // look past this, but let the caller know that we found something that 12976 // either is, or might be, usable in this class. 12977 if (FoundInClass) { 12978 *FoundInClass = RD; 12979 if (OR == OR_Success) { 12980 R.clear(); 12981 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12982 R.resolveKind(); 12983 } 12984 } 12985 return false; 12986 } 12987 12988 if (OR != OR_Success) { 12989 // There wasn't a unique best function or function template. 12990 return false; 12991 } 12992 12993 // Find the namespaces where ADL would have looked, and suggest 12994 // declaring the function there instead. 12995 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12996 Sema::AssociatedClassSet AssociatedClasses; 12997 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12998 AssociatedNamespaces, 12999 AssociatedClasses); 13000 Sema::AssociatedNamespaceSet SuggestedNamespaces; 13001 if (canBeDeclaredInNamespace(R.getLookupName())) { 13002 DeclContext *Std = SemaRef.getStdNamespace(); 13003 for (Sema::AssociatedNamespaceSet::iterator 13004 it = AssociatedNamespaces.begin(), 13005 end = AssociatedNamespaces.end(); it != end; ++it) { 13006 // Never suggest declaring a function within namespace 'std'. 13007 if (Std && Std->Encloses(*it)) 13008 continue; 13009 13010 // Never suggest declaring a function within a namespace with a 13011 // reserved name, like __gnu_cxx. 13012 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 13013 if (NS && 13014 NS->getQualifiedNameAsString().find("__") != std::string::npos) 13015 continue; 13016 13017 SuggestedNamespaces.insert(*it); 13018 } 13019 } 13020 13021 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 13022 << R.getLookupName(); 13023 if (SuggestedNamespaces.empty()) { 13024 SemaRef.Diag(Best->Function->getLocation(), 13025 diag::note_not_found_by_two_phase_lookup) 13026 << R.getLookupName() << 0; 13027 } else if (SuggestedNamespaces.size() == 1) { 13028 SemaRef.Diag(Best->Function->getLocation(), 13029 diag::note_not_found_by_two_phase_lookup) 13030 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 13031 } else { 13032 // FIXME: It would be useful to list the associated namespaces here, 13033 // but the diagnostics infrastructure doesn't provide a way to produce 13034 // a localized representation of a list of items. 13035 SemaRef.Diag(Best->Function->getLocation(), 13036 diag::note_not_found_by_two_phase_lookup) 13037 << R.getLookupName() << 2; 13038 } 13039 13040 // Try to recover by calling this function. 13041 return true; 13042 } 13043 13044 R.clear(); 13045 } 13046 13047 return false; 13048 } 13049 13050 /// Attempt to recover from ill-formed use of a non-dependent operator in a 13051 /// template, where the non-dependent operator was declared after the template 13052 /// was defined. 13053 /// 13054 /// Returns true if a viable candidate was found and a diagnostic was issued. 13055 static bool 13056 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 13057 SourceLocation OpLoc, 13058 ArrayRef<Expr *> Args) { 13059 DeclarationName OpName = 13060 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 13061 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 13062 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 13063 OverloadCandidateSet::CSK_Operator, 13064 /*ExplicitTemplateArgs=*/nullptr, Args); 13065 } 13066 13067 namespace { 13068 class BuildRecoveryCallExprRAII { 13069 Sema &SemaRef; 13070 public: 13071 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 13072 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 13073 SemaRef.IsBuildingRecoveryCallExpr = true; 13074 } 13075 13076 ~BuildRecoveryCallExprRAII() { 13077 SemaRef.IsBuildingRecoveryCallExpr = false; 13078 } 13079 }; 13080 13081 } 13082 13083 /// Attempts to recover from a call where no functions were found. 13084 /// 13085 /// This function will do one of three things: 13086 /// * Diagnose, recover, and return a recovery expression. 13087 /// * Diagnose, fail to recover, and return ExprError(). 13088 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 13089 /// expected to diagnose as appropriate. 13090 static ExprResult 13091 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13092 UnresolvedLookupExpr *ULE, 13093 SourceLocation LParenLoc, 13094 MutableArrayRef<Expr *> Args, 13095 SourceLocation RParenLoc, 13096 bool EmptyLookup, bool AllowTypoCorrection) { 13097 // Do not try to recover if it is already building a recovery call. 13098 // This stops infinite loops for template instantiations like 13099 // 13100 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 13101 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 13102 if (SemaRef.IsBuildingRecoveryCallExpr) 13103 return ExprResult(); 13104 BuildRecoveryCallExprRAII RCE(SemaRef); 13105 13106 CXXScopeSpec SS; 13107 SS.Adopt(ULE->getQualifierLoc()); 13108 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 13109 13110 TemplateArgumentListInfo TABuffer; 13111 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13112 if (ULE->hasExplicitTemplateArgs()) { 13113 ULE->copyTemplateArgumentsInto(TABuffer); 13114 ExplicitTemplateArgs = &TABuffer; 13115 } 13116 13117 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 13118 Sema::LookupOrdinaryName); 13119 CXXRecordDecl *FoundInClass = nullptr; 13120 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 13121 OverloadCandidateSet::CSK_Normal, 13122 ExplicitTemplateArgs, Args, &FoundInClass)) { 13123 // OK, diagnosed a two-phase lookup issue. 13124 } else if (EmptyLookup) { 13125 // Try to recover from an empty lookup with typo correction. 13126 R.clear(); 13127 NoTypoCorrectionCCC NoTypoValidator{}; 13128 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 13129 ExplicitTemplateArgs != nullptr, 13130 dyn_cast<MemberExpr>(Fn)); 13131 CorrectionCandidateCallback &Validator = 13132 AllowTypoCorrection 13133 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 13134 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 13135 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 13136 Args)) 13137 return ExprError(); 13138 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 13139 // We found a usable declaration of the name in a dependent base of some 13140 // enclosing class. 13141 // FIXME: We should also explain why the candidates found by name lookup 13142 // were not viable. 13143 if (SemaRef.DiagnoseDependentMemberLookup(R)) 13144 return ExprError(); 13145 } else { 13146 // We had viable candidates and couldn't recover; let the caller diagnose 13147 // this. 13148 return ExprResult(); 13149 } 13150 13151 // If we get here, we should have issued a diagnostic and formed a recovery 13152 // lookup result. 13153 assert(!R.empty() && "lookup results empty despite recovery"); 13154 13155 // If recovery created an ambiguity, just bail out. 13156 if (R.isAmbiguous()) { 13157 R.suppressDiagnostics(); 13158 return ExprError(); 13159 } 13160 13161 // Build an implicit member call if appropriate. Just drop the 13162 // casts and such from the call, we don't really care. 13163 ExprResult NewFn = ExprError(); 13164 if ((*R.begin())->isCXXClassMember()) 13165 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13166 ExplicitTemplateArgs, S); 13167 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13168 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13169 ExplicitTemplateArgs); 13170 else 13171 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13172 13173 if (NewFn.isInvalid()) 13174 return ExprError(); 13175 13176 // This shouldn't cause an infinite loop because we're giving it 13177 // an expression with viable lookup results, which should never 13178 // end up here. 13179 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13180 MultiExprArg(Args.data(), Args.size()), 13181 RParenLoc); 13182 } 13183 13184 /// Constructs and populates an OverloadedCandidateSet from 13185 /// the given function. 13186 /// \returns true when an the ExprResult output parameter has been set. 13187 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13188 UnresolvedLookupExpr *ULE, 13189 MultiExprArg Args, 13190 SourceLocation RParenLoc, 13191 OverloadCandidateSet *CandidateSet, 13192 ExprResult *Result) { 13193 #ifndef NDEBUG 13194 if (ULE->requiresADL()) { 13195 // To do ADL, we must have found an unqualified name. 13196 assert(!ULE->getQualifier() && "qualified name with ADL"); 13197 13198 // We don't perform ADL for implicit declarations of builtins. 13199 // Verify that this was correctly set up. 13200 FunctionDecl *F; 13201 if (ULE->decls_begin() != ULE->decls_end() && 13202 ULE->decls_begin() + 1 == ULE->decls_end() && 13203 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13204 F->getBuiltinID() && F->isImplicit()) 13205 llvm_unreachable("performing ADL for builtin"); 13206 13207 // We don't perform ADL in C. 13208 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13209 } 13210 #endif 13211 13212 UnbridgedCastsSet UnbridgedCasts; 13213 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13214 *Result = ExprError(); 13215 return true; 13216 } 13217 13218 // Add the functions denoted by the callee to the set of candidate 13219 // functions, including those from argument-dependent lookup. 13220 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13221 13222 if (getLangOpts().MSVCCompat && 13223 CurContext->isDependentContext() && !isSFINAEContext() && 13224 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13225 13226 OverloadCandidateSet::iterator Best; 13227 if (CandidateSet->empty() || 13228 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13229 OR_No_Viable_Function) { 13230 // In Microsoft mode, if we are inside a template class member function 13231 // then create a type dependent CallExpr. The goal is to postpone name 13232 // lookup to instantiation time to be able to search into type dependent 13233 // base classes. 13234 CallExpr *CE = 13235 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13236 RParenLoc, CurFPFeatureOverrides()); 13237 CE->markDependentForPostponedNameLookup(); 13238 *Result = CE; 13239 return true; 13240 } 13241 } 13242 13243 if (CandidateSet->empty()) 13244 return false; 13245 13246 UnbridgedCasts.restore(); 13247 return false; 13248 } 13249 13250 // Guess at what the return type for an unresolvable overload should be. 13251 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13252 OverloadCandidateSet::iterator *Best) { 13253 llvm::Optional<QualType> Result; 13254 // Adjust Type after seeing a candidate. 13255 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13256 if (!Candidate.Function) 13257 return; 13258 if (Candidate.Function->isInvalidDecl()) 13259 return; 13260 QualType T = Candidate.Function->getReturnType(); 13261 if (T.isNull()) 13262 return; 13263 if (!Result) 13264 Result = T; 13265 else if (Result != T) 13266 Result = QualType(); 13267 }; 13268 13269 // Look for an unambiguous type from a progressively larger subset. 13270 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13271 // 13272 // First, consider only the best candidate. 13273 if (Best && *Best != CS.end()) 13274 ConsiderCandidate(**Best); 13275 // Next, consider only viable candidates. 13276 if (!Result) 13277 for (const auto &C : CS) 13278 if (C.Viable) 13279 ConsiderCandidate(C); 13280 // Finally, consider all candidates. 13281 if (!Result) 13282 for (const auto &C : CS) 13283 ConsiderCandidate(C); 13284 13285 if (!Result) 13286 return QualType(); 13287 auto Value = *Result; 13288 if (Value.isNull() || Value->isUndeducedType()) 13289 return QualType(); 13290 return Value; 13291 } 13292 13293 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13294 /// the completed call expression. If overload resolution fails, emits 13295 /// diagnostics and returns ExprError() 13296 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13297 UnresolvedLookupExpr *ULE, 13298 SourceLocation LParenLoc, 13299 MultiExprArg Args, 13300 SourceLocation RParenLoc, 13301 Expr *ExecConfig, 13302 OverloadCandidateSet *CandidateSet, 13303 OverloadCandidateSet::iterator *Best, 13304 OverloadingResult OverloadResult, 13305 bool AllowTypoCorrection) { 13306 switch (OverloadResult) { 13307 case OR_Success: { 13308 FunctionDecl *FDecl = (*Best)->Function; 13309 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13310 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13311 return ExprError(); 13312 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13313 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13314 ExecConfig, /*IsExecConfig=*/false, 13315 (*Best)->IsADLCandidate); 13316 } 13317 13318 case OR_No_Viable_Function: { 13319 // Try to recover by looking for viable functions which the user might 13320 // have meant to call. 13321 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13322 Args, RParenLoc, 13323 CandidateSet->empty(), 13324 AllowTypoCorrection); 13325 if (Recovery.isInvalid() || Recovery.isUsable()) 13326 return Recovery; 13327 13328 // If the user passes in a function that we can't take the address of, we 13329 // generally end up emitting really bad error messages. Here, we attempt to 13330 // emit better ones. 13331 for (const Expr *Arg : Args) { 13332 if (!Arg->getType()->isFunctionType()) 13333 continue; 13334 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13335 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13336 if (FD && 13337 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13338 Arg->getExprLoc())) 13339 return ExprError(); 13340 } 13341 } 13342 13343 CandidateSet->NoteCandidates( 13344 PartialDiagnosticAt( 13345 Fn->getBeginLoc(), 13346 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13347 << ULE->getName() << Fn->getSourceRange()), 13348 SemaRef, OCD_AllCandidates, Args); 13349 break; 13350 } 13351 13352 case OR_Ambiguous: 13353 CandidateSet->NoteCandidates( 13354 PartialDiagnosticAt(Fn->getBeginLoc(), 13355 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13356 << ULE->getName() << Fn->getSourceRange()), 13357 SemaRef, OCD_AmbiguousCandidates, Args); 13358 break; 13359 13360 case OR_Deleted: { 13361 CandidateSet->NoteCandidates( 13362 PartialDiagnosticAt(Fn->getBeginLoc(), 13363 SemaRef.PDiag(diag::err_ovl_deleted_call) 13364 << ULE->getName() << Fn->getSourceRange()), 13365 SemaRef, OCD_AllCandidates, Args); 13366 13367 // We emitted an error for the unavailable/deleted function call but keep 13368 // the call in the AST. 13369 FunctionDecl *FDecl = (*Best)->Function; 13370 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13371 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13372 ExecConfig, /*IsExecConfig=*/false, 13373 (*Best)->IsADLCandidate); 13374 } 13375 } 13376 13377 // Overload resolution failed, try to recover. 13378 SmallVector<Expr *, 8> SubExprs = {Fn}; 13379 SubExprs.append(Args.begin(), Args.end()); 13380 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13381 chooseRecoveryType(*CandidateSet, Best)); 13382 } 13383 13384 static void markUnaddressableCandidatesUnviable(Sema &S, 13385 OverloadCandidateSet &CS) { 13386 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13387 if (I->Viable && 13388 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13389 I->Viable = false; 13390 I->FailureKind = ovl_fail_addr_not_available; 13391 } 13392 } 13393 } 13394 13395 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13396 /// (which eventually refers to the declaration Func) and the call 13397 /// arguments Args/NumArgs, attempt to resolve the function call down 13398 /// to a specific function. If overload resolution succeeds, returns 13399 /// the call expression produced by overload resolution. 13400 /// Otherwise, emits diagnostics and returns ExprError. 13401 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13402 UnresolvedLookupExpr *ULE, 13403 SourceLocation LParenLoc, 13404 MultiExprArg Args, 13405 SourceLocation RParenLoc, 13406 Expr *ExecConfig, 13407 bool AllowTypoCorrection, 13408 bool CalleesAddressIsTaken) { 13409 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13410 OverloadCandidateSet::CSK_Normal); 13411 ExprResult result; 13412 13413 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13414 &result)) 13415 return result; 13416 13417 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13418 // functions that aren't addressible are considered unviable. 13419 if (CalleesAddressIsTaken) 13420 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13421 13422 OverloadCandidateSet::iterator Best; 13423 OverloadingResult OverloadResult = 13424 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13425 13426 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13427 ExecConfig, &CandidateSet, &Best, 13428 OverloadResult, AllowTypoCorrection); 13429 } 13430 13431 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13432 return Functions.size() > 1 || 13433 (Functions.size() == 1 && 13434 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13435 } 13436 13437 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13438 NestedNameSpecifierLoc NNSLoc, 13439 DeclarationNameInfo DNI, 13440 const UnresolvedSetImpl &Fns, 13441 bool PerformADL) { 13442 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13443 PerformADL, IsOverloaded(Fns), 13444 Fns.begin(), Fns.end()); 13445 } 13446 13447 /// Create a unary operation that may resolve to an overloaded 13448 /// operator. 13449 /// 13450 /// \param OpLoc The location of the operator itself (e.g., '*'). 13451 /// 13452 /// \param Opc The UnaryOperatorKind that describes this operator. 13453 /// 13454 /// \param Fns The set of non-member functions that will be 13455 /// considered by overload resolution. The caller needs to build this 13456 /// set based on the context using, e.g., 13457 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13458 /// set should not contain any member functions; those will be added 13459 /// by CreateOverloadedUnaryOp(). 13460 /// 13461 /// \param Input The input argument. 13462 ExprResult 13463 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13464 const UnresolvedSetImpl &Fns, 13465 Expr *Input, bool PerformADL) { 13466 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13467 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13468 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13469 // TODO: provide better source location info. 13470 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13471 13472 if (checkPlaceholderForOverload(*this, Input)) 13473 return ExprError(); 13474 13475 Expr *Args[2] = { Input, nullptr }; 13476 unsigned NumArgs = 1; 13477 13478 // For post-increment and post-decrement, add the implicit '0' as 13479 // the second argument, so that we know this is a post-increment or 13480 // post-decrement. 13481 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13482 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13483 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13484 SourceLocation()); 13485 NumArgs = 2; 13486 } 13487 13488 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13489 13490 if (Input->isTypeDependent()) { 13491 if (Fns.empty()) 13492 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13493 VK_PRValue, OK_Ordinary, OpLoc, false, 13494 CurFPFeatureOverrides()); 13495 13496 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13497 ExprResult Fn = CreateUnresolvedLookupExpr( 13498 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13499 if (Fn.isInvalid()) 13500 return ExprError(); 13501 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13502 Context.DependentTy, VK_PRValue, OpLoc, 13503 CurFPFeatureOverrides()); 13504 } 13505 13506 // Build an empty overload set. 13507 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13508 13509 // Add the candidates from the given function set. 13510 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13511 13512 // Add operator candidates that are member functions. 13513 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13514 13515 // Add candidates from ADL. 13516 if (PerformADL) { 13517 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13518 /*ExplicitTemplateArgs*/nullptr, 13519 CandidateSet); 13520 } 13521 13522 // Add builtin operator candidates. 13523 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13524 13525 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13526 13527 // Perform overload resolution. 13528 OverloadCandidateSet::iterator Best; 13529 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13530 case OR_Success: { 13531 // We found a built-in operator or an overloaded operator. 13532 FunctionDecl *FnDecl = Best->Function; 13533 13534 if (FnDecl) { 13535 Expr *Base = nullptr; 13536 // We matched an overloaded operator. Build a call to that 13537 // operator. 13538 13539 // Convert the arguments. 13540 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13541 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13542 13543 ExprResult InputRes = 13544 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13545 Best->FoundDecl, Method); 13546 if (InputRes.isInvalid()) 13547 return ExprError(); 13548 Base = Input = InputRes.get(); 13549 } else { 13550 // Convert the arguments. 13551 ExprResult InputInit 13552 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13553 Context, 13554 FnDecl->getParamDecl(0)), 13555 SourceLocation(), 13556 Input); 13557 if (InputInit.isInvalid()) 13558 return ExprError(); 13559 Input = InputInit.get(); 13560 } 13561 13562 // Build the actual expression node. 13563 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13564 Base, HadMultipleCandidates, 13565 OpLoc); 13566 if (FnExpr.isInvalid()) 13567 return ExprError(); 13568 13569 // Determine the result type. 13570 QualType ResultTy = FnDecl->getReturnType(); 13571 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13572 ResultTy = ResultTy.getNonLValueExprType(Context); 13573 13574 Args[0] = Input; 13575 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13576 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13577 CurFPFeatureOverrides(), Best->IsADLCandidate); 13578 13579 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13580 return ExprError(); 13581 13582 if (CheckFunctionCall(FnDecl, TheCall, 13583 FnDecl->getType()->castAs<FunctionProtoType>())) 13584 return ExprError(); 13585 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13586 } else { 13587 // We matched a built-in operator. Convert the arguments, then 13588 // break out so that we will build the appropriate built-in 13589 // operator node. 13590 ExprResult InputRes = PerformImplicitConversion( 13591 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13592 CCK_ForBuiltinOverloadedOp); 13593 if (InputRes.isInvalid()) 13594 return ExprError(); 13595 Input = InputRes.get(); 13596 break; 13597 } 13598 } 13599 13600 case OR_No_Viable_Function: 13601 // This is an erroneous use of an operator which can be overloaded by 13602 // a non-member function. Check for non-member operators which were 13603 // defined too late to be candidates. 13604 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13605 // FIXME: Recover by calling the found function. 13606 return ExprError(); 13607 13608 // No viable function; fall through to handling this as a 13609 // built-in operator, which will produce an error message for us. 13610 break; 13611 13612 case OR_Ambiguous: 13613 CandidateSet.NoteCandidates( 13614 PartialDiagnosticAt(OpLoc, 13615 PDiag(diag::err_ovl_ambiguous_oper_unary) 13616 << UnaryOperator::getOpcodeStr(Opc) 13617 << Input->getType() << Input->getSourceRange()), 13618 *this, OCD_AmbiguousCandidates, ArgsArray, 13619 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13620 return ExprError(); 13621 13622 case OR_Deleted: 13623 CandidateSet.NoteCandidates( 13624 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13625 << UnaryOperator::getOpcodeStr(Opc) 13626 << Input->getSourceRange()), 13627 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13628 OpLoc); 13629 return ExprError(); 13630 } 13631 13632 // Either we found no viable overloaded operator or we matched a 13633 // built-in operator. In either case, fall through to trying to 13634 // build a built-in operation. 13635 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13636 } 13637 13638 /// Perform lookup for an overloaded binary operator. 13639 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13640 OverloadedOperatorKind Op, 13641 const UnresolvedSetImpl &Fns, 13642 ArrayRef<Expr *> Args, bool PerformADL) { 13643 SourceLocation OpLoc = CandidateSet.getLocation(); 13644 13645 OverloadedOperatorKind ExtraOp = 13646 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13647 ? getRewrittenOverloadedOperator(Op) 13648 : OO_None; 13649 13650 // Add the candidates from the given function set. This also adds the 13651 // rewritten candidates using these functions if necessary. 13652 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13653 13654 // Add operator candidates that are member functions. 13655 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13656 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13657 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13658 OverloadCandidateParamOrder::Reversed); 13659 13660 // In C++20, also add any rewritten member candidates. 13661 if (ExtraOp) { 13662 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13663 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13664 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13665 CandidateSet, 13666 OverloadCandidateParamOrder::Reversed); 13667 } 13668 13669 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13670 // performed for an assignment operator (nor for operator[] nor operator->, 13671 // which don't get here). 13672 if (Op != OO_Equal && PerformADL) { 13673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13674 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13675 /*ExplicitTemplateArgs*/ nullptr, 13676 CandidateSet); 13677 if (ExtraOp) { 13678 DeclarationName ExtraOpName = 13679 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13680 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13681 /*ExplicitTemplateArgs*/ nullptr, 13682 CandidateSet); 13683 } 13684 } 13685 13686 // Add builtin operator candidates. 13687 // 13688 // FIXME: We don't add any rewritten candidates here. This is strictly 13689 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13690 // resulting in our selecting a rewritten builtin candidate. For example: 13691 // 13692 // enum class E { e }; 13693 // bool operator!=(E, E) requires false; 13694 // bool k = E::e != E::e; 13695 // 13696 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13697 // it seems unreasonable to consider rewritten builtin candidates. A core 13698 // issue has been filed proposing to removed this requirement. 13699 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13700 } 13701 13702 /// Create a binary operation that may resolve to an overloaded 13703 /// operator. 13704 /// 13705 /// \param OpLoc The location of the operator itself (e.g., '+'). 13706 /// 13707 /// \param Opc The BinaryOperatorKind that describes this operator. 13708 /// 13709 /// \param Fns The set of non-member functions that will be 13710 /// considered by overload resolution. The caller needs to build this 13711 /// set based on the context using, e.g., 13712 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13713 /// set should not contain any member functions; those will be added 13714 /// by CreateOverloadedBinOp(). 13715 /// 13716 /// \param LHS Left-hand argument. 13717 /// \param RHS Right-hand argument. 13718 /// \param PerformADL Whether to consider operator candidates found by ADL. 13719 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13720 /// C++20 operator rewrites. 13721 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13722 /// the function in question. Such a function is never a candidate in 13723 /// our overload resolution. This also enables synthesizing a three-way 13724 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13725 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13726 BinaryOperatorKind Opc, 13727 const UnresolvedSetImpl &Fns, Expr *LHS, 13728 Expr *RHS, bool PerformADL, 13729 bool AllowRewrittenCandidates, 13730 FunctionDecl *DefaultedFn) { 13731 Expr *Args[2] = { LHS, RHS }; 13732 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13733 13734 if (!getLangOpts().CPlusPlus20) 13735 AllowRewrittenCandidates = false; 13736 13737 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13738 13739 // If either side is type-dependent, create an appropriate dependent 13740 // expression. 13741 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13742 if (Fns.empty()) { 13743 // If there are no functions to store, just build a dependent 13744 // BinaryOperator or CompoundAssignment. 13745 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13746 return CompoundAssignOperator::Create( 13747 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13748 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13749 Context.DependentTy); 13750 return BinaryOperator::Create( 13751 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 13752 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13753 } 13754 13755 // FIXME: save results of ADL from here? 13756 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13757 // TODO: provide better source location info in DNLoc component. 13758 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13759 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13760 ExprResult Fn = CreateUnresolvedLookupExpr( 13761 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13762 if (Fn.isInvalid()) 13763 return ExprError(); 13764 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13765 Context.DependentTy, VK_PRValue, OpLoc, 13766 CurFPFeatureOverrides()); 13767 } 13768 13769 // Always do placeholder-like conversions on the RHS. 13770 if (checkPlaceholderForOverload(*this, Args[1])) 13771 return ExprError(); 13772 13773 // Do placeholder-like conversion on the LHS; note that we should 13774 // not get here with a PseudoObject LHS. 13775 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13776 if (checkPlaceholderForOverload(*this, Args[0])) 13777 return ExprError(); 13778 13779 // If this is the assignment operator, we only perform overload resolution 13780 // if the left-hand side is a class or enumeration type. This is actually 13781 // a hack. The standard requires that we do overload resolution between the 13782 // various built-in candidates, but as DR507 points out, this can lead to 13783 // problems. So we do it this way, which pretty much follows what GCC does. 13784 // Note that we go the traditional code path for compound assignment forms. 13785 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13786 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13787 13788 // If this is the .* operator, which is not overloadable, just 13789 // create a built-in binary operator. 13790 if (Opc == BO_PtrMemD) 13791 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13792 13793 // Build the overload set. 13794 OverloadCandidateSet CandidateSet( 13795 OpLoc, OverloadCandidateSet::CSK_Operator, 13796 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13797 if (DefaultedFn) 13798 CandidateSet.exclude(DefaultedFn); 13799 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13800 13801 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13802 13803 // Perform overload resolution. 13804 OverloadCandidateSet::iterator Best; 13805 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13806 case OR_Success: { 13807 // We found a built-in operator or an overloaded operator. 13808 FunctionDecl *FnDecl = Best->Function; 13809 13810 bool IsReversed = Best->isReversed(); 13811 if (IsReversed) 13812 std::swap(Args[0], Args[1]); 13813 13814 if (FnDecl) { 13815 Expr *Base = nullptr; 13816 // We matched an overloaded operator. Build a call to that 13817 // operator. 13818 13819 OverloadedOperatorKind ChosenOp = 13820 FnDecl->getDeclName().getCXXOverloadedOperator(); 13821 13822 // C++2a [over.match.oper]p9: 13823 // If a rewritten operator== candidate is selected by overload 13824 // resolution for an operator@, its return type shall be cv bool 13825 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13826 !FnDecl->getReturnType()->isBooleanType()) { 13827 bool IsExtension = 13828 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13829 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13830 : diag::err_ovl_rewrite_equalequal_not_bool) 13831 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13832 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13833 Diag(FnDecl->getLocation(), diag::note_declared_at); 13834 if (!IsExtension) 13835 return ExprError(); 13836 } 13837 13838 if (AllowRewrittenCandidates && !IsReversed && 13839 CandidateSet.getRewriteInfo().isReversible()) { 13840 // We could have reversed this operator, but didn't. Check if some 13841 // reversed form was a viable candidate, and if so, if it had a 13842 // better conversion for either parameter. If so, this call is 13843 // formally ambiguous, and allowing it is an extension. 13844 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13845 for (OverloadCandidate &Cand : CandidateSet) { 13846 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13847 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13848 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13849 if (CompareImplicitConversionSequences( 13850 *this, OpLoc, Cand.Conversions[ArgIdx], 13851 Best->Conversions[ArgIdx]) == 13852 ImplicitConversionSequence::Better) { 13853 AmbiguousWith.push_back(Cand.Function); 13854 break; 13855 } 13856 } 13857 } 13858 } 13859 13860 if (!AmbiguousWith.empty()) { 13861 bool AmbiguousWithSelf = 13862 AmbiguousWith.size() == 1 && 13863 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13864 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13865 << BinaryOperator::getOpcodeStr(Opc) 13866 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13867 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13868 if (AmbiguousWithSelf) { 13869 Diag(FnDecl->getLocation(), 13870 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13871 } else { 13872 Diag(FnDecl->getLocation(), 13873 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13874 for (auto *F : AmbiguousWith) 13875 Diag(F->getLocation(), 13876 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13877 } 13878 } 13879 } 13880 13881 // Convert the arguments. 13882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13883 // Best->Access is only meaningful for class members. 13884 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13885 13886 ExprResult Arg1 = 13887 PerformCopyInitialization( 13888 InitializedEntity::InitializeParameter(Context, 13889 FnDecl->getParamDecl(0)), 13890 SourceLocation(), Args[1]); 13891 if (Arg1.isInvalid()) 13892 return ExprError(); 13893 13894 ExprResult Arg0 = 13895 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13896 Best->FoundDecl, Method); 13897 if (Arg0.isInvalid()) 13898 return ExprError(); 13899 Base = Args[0] = Arg0.getAs<Expr>(); 13900 Args[1] = RHS = Arg1.getAs<Expr>(); 13901 } else { 13902 // Convert the arguments. 13903 ExprResult Arg0 = PerformCopyInitialization( 13904 InitializedEntity::InitializeParameter(Context, 13905 FnDecl->getParamDecl(0)), 13906 SourceLocation(), Args[0]); 13907 if (Arg0.isInvalid()) 13908 return ExprError(); 13909 13910 ExprResult Arg1 = 13911 PerformCopyInitialization( 13912 InitializedEntity::InitializeParameter(Context, 13913 FnDecl->getParamDecl(1)), 13914 SourceLocation(), Args[1]); 13915 if (Arg1.isInvalid()) 13916 return ExprError(); 13917 Args[0] = LHS = Arg0.getAs<Expr>(); 13918 Args[1] = RHS = Arg1.getAs<Expr>(); 13919 } 13920 13921 // Build the actual expression node. 13922 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13923 Best->FoundDecl, Base, 13924 HadMultipleCandidates, OpLoc); 13925 if (FnExpr.isInvalid()) 13926 return ExprError(); 13927 13928 // Determine the result type. 13929 QualType ResultTy = FnDecl->getReturnType(); 13930 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13931 ResultTy = ResultTy.getNonLValueExprType(Context); 13932 13933 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13934 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13935 CurFPFeatureOverrides(), Best->IsADLCandidate); 13936 13937 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13938 FnDecl)) 13939 return ExprError(); 13940 13941 ArrayRef<const Expr *> ArgsArray(Args, 2); 13942 const Expr *ImplicitThis = nullptr; 13943 // Cut off the implicit 'this'. 13944 if (isa<CXXMethodDecl>(FnDecl)) { 13945 ImplicitThis = ArgsArray[0]; 13946 ArgsArray = ArgsArray.slice(1); 13947 } 13948 13949 // Check for a self move. 13950 if (Op == OO_Equal) 13951 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13952 13953 if (ImplicitThis) { 13954 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13955 QualType ThisTypeFromDecl = Context.getPointerType( 13956 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13957 13958 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13959 ThisTypeFromDecl); 13960 } 13961 13962 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13963 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13964 VariadicDoesNotApply); 13965 13966 ExprResult R = MaybeBindToTemporary(TheCall); 13967 if (R.isInvalid()) 13968 return ExprError(); 13969 13970 R = CheckForImmediateInvocation(R, FnDecl); 13971 if (R.isInvalid()) 13972 return ExprError(); 13973 13974 // For a rewritten candidate, we've already reversed the arguments 13975 // if needed. Perform the rest of the rewrite now. 13976 if ((Best->RewriteKind & CRK_DifferentOperator) || 13977 (Op == OO_Spaceship && IsReversed)) { 13978 if (Op == OO_ExclaimEqual) { 13979 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13980 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13981 } else { 13982 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13983 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13984 Expr *ZeroLiteral = 13985 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13986 13987 Sema::CodeSynthesisContext Ctx; 13988 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13989 Ctx.Entity = FnDecl; 13990 pushCodeSynthesisContext(Ctx); 13991 13992 R = CreateOverloadedBinOp( 13993 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13994 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13995 /*AllowRewrittenCandidates=*/false); 13996 13997 popCodeSynthesisContext(); 13998 } 13999 if (R.isInvalid()) 14000 return ExprError(); 14001 } else { 14002 assert(ChosenOp == Op && "unexpected operator name"); 14003 } 14004 14005 // Make a note in the AST if we did any rewriting. 14006 if (Best->RewriteKind != CRK_None) 14007 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 14008 14009 return R; 14010 } else { 14011 // We matched a built-in operator. Convert the arguments, then 14012 // break out so that we will build the appropriate built-in 14013 // operator node. 14014 ExprResult ArgsRes0 = PerformImplicitConversion( 14015 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14016 AA_Passing, CCK_ForBuiltinOverloadedOp); 14017 if (ArgsRes0.isInvalid()) 14018 return ExprError(); 14019 Args[0] = ArgsRes0.get(); 14020 14021 ExprResult ArgsRes1 = PerformImplicitConversion( 14022 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14023 AA_Passing, CCK_ForBuiltinOverloadedOp); 14024 if (ArgsRes1.isInvalid()) 14025 return ExprError(); 14026 Args[1] = ArgsRes1.get(); 14027 break; 14028 } 14029 } 14030 14031 case OR_No_Viable_Function: { 14032 // C++ [over.match.oper]p9: 14033 // If the operator is the operator , [...] and there are no 14034 // viable functions, then the operator is assumed to be the 14035 // built-in operator and interpreted according to clause 5. 14036 if (Opc == BO_Comma) 14037 break; 14038 14039 // When defaulting an 'operator<=>', we can try to synthesize a three-way 14040 // compare result using '==' and '<'. 14041 if (DefaultedFn && Opc == BO_Cmp) { 14042 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 14043 Args[1], DefaultedFn); 14044 if (E.isInvalid() || E.isUsable()) 14045 return E; 14046 } 14047 14048 // For class as left operand for assignment or compound assignment 14049 // operator do not fall through to handling in built-in, but report that 14050 // no overloaded assignment operator found 14051 ExprResult Result = ExprError(); 14052 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 14053 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 14054 Args, OpLoc); 14055 DeferDiagsRAII DDR(*this, 14056 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 14057 if (Args[0]->getType()->isRecordType() && 14058 Opc >= BO_Assign && Opc <= BO_OrAssign) { 14059 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14060 << BinaryOperator::getOpcodeStr(Opc) 14061 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14062 if (Args[0]->getType()->isIncompleteType()) { 14063 Diag(OpLoc, diag::note_assign_lhs_incomplete) 14064 << Args[0]->getType() 14065 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14066 } 14067 } else { 14068 // This is an erroneous use of an operator which can be overloaded by 14069 // a non-member function. Check for non-member operators which were 14070 // defined too late to be candidates. 14071 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 14072 // FIXME: Recover by calling the found function. 14073 return ExprError(); 14074 14075 // No viable function; try to create a built-in operation, which will 14076 // produce an error. Then, show the non-viable candidates. 14077 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14078 } 14079 assert(Result.isInvalid() && 14080 "C++ binary operator overloading is missing candidates!"); 14081 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 14082 return Result; 14083 } 14084 14085 case OR_Ambiguous: 14086 CandidateSet.NoteCandidates( 14087 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14088 << BinaryOperator::getOpcodeStr(Opc) 14089 << Args[0]->getType() 14090 << Args[1]->getType() 14091 << Args[0]->getSourceRange() 14092 << Args[1]->getSourceRange()), 14093 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14094 OpLoc); 14095 return ExprError(); 14096 14097 case OR_Deleted: 14098 if (isImplicitlyDeleted(Best->Function)) { 14099 FunctionDecl *DeletedFD = Best->Function; 14100 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 14101 if (DFK.isSpecialMember()) { 14102 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 14103 << Args[0]->getType() << DFK.asSpecialMember(); 14104 } else { 14105 assert(DFK.isComparison()); 14106 Diag(OpLoc, diag::err_ovl_deleted_comparison) 14107 << Args[0]->getType() << DeletedFD; 14108 } 14109 14110 // The user probably meant to call this special member. Just 14111 // explain why it's deleted. 14112 NoteDeletedFunction(DeletedFD); 14113 return ExprError(); 14114 } 14115 CandidateSet.NoteCandidates( 14116 PartialDiagnosticAt( 14117 OpLoc, PDiag(diag::err_ovl_deleted_oper) 14118 << getOperatorSpelling(Best->Function->getDeclName() 14119 .getCXXOverloadedOperator()) 14120 << Args[0]->getSourceRange() 14121 << Args[1]->getSourceRange()), 14122 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14123 OpLoc); 14124 return ExprError(); 14125 } 14126 14127 // We matched a built-in operator; build it. 14128 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14129 } 14130 14131 ExprResult Sema::BuildSynthesizedThreeWayComparison( 14132 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 14133 FunctionDecl *DefaultedFn) { 14134 const ComparisonCategoryInfo *Info = 14135 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 14136 // If we're not producing a known comparison category type, we can't 14137 // synthesize a three-way comparison. Let the caller diagnose this. 14138 if (!Info) 14139 return ExprResult((Expr*)nullptr); 14140 14141 // If we ever want to perform this synthesis more generally, we will need to 14142 // apply the temporary materialization conversion to the operands. 14143 assert(LHS->isGLValue() && RHS->isGLValue() && 14144 "cannot use prvalue expressions more than once"); 14145 Expr *OrigLHS = LHS; 14146 Expr *OrigRHS = RHS; 14147 14148 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 14149 // each of them multiple times below. 14150 LHS = new (Context) 14151 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 14152 LHS->getObjectKind(), LHS); 14153 RHS = new (Context) 14154 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 14155 RHS->getObjectKind(), RHS); 14156 14157 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 14158 DefaultedFn); 14159 if (Eq.isInvalid()) 14160 return ExprError(); 14161 14162 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 14163 true, DefaultedFn); 14164 if (Less.isInvalid()) 14165 return ExprError(); 14166 14167 ExprResult Greater; 14168 if (Info->isPartial()) { 14169 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14170 DefaultedFn); 14171 if (Greater.isInvalid()) 14172 return ExprError(); 14173 } 14174 14175 // Form the list of comparisons we're going to perform. 14176 struct Comparison { 14177 ExprResult Cmp; 14178 ComparisonCategoryResult Result; 14179 } Comparisons[4] = 14180 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14181 : ComparisonCategoryResult::Equivalent}, 14182 {Less, ComparisonCategoryResult::Less}, 14183 {Greater, ComparisonCategoryResult::Greater}, 14184 {ExprResult(), ComparisonCategoryResult::Unordered}, 14185 }; 14186 14187 int I = Info->isPartial() ? 3 : 2; 14188 14189 // Combine the comparisons with suitable conditional expressions. 14190 ExprResult Result; 14191 for (; I >= 0; --I) { 14192 // Build a reference to the comparison category constant. 14193 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14194 // FIXME: Missing a constant for a comparison category. Diagnose this? 14195 if (!VI) 14196 return ExprResult((Expr*)nullptr); 14197 ExprResult ThisResult = 14198 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14199 if (ThisResult.isInvalid()) 14200 return ExprError(); 14201 14202 // Build a conditional unless this is the final case. 14203 if (Result.get()) { 14204 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14205 ThisResult.get(), Result.get()); 14206 if (Result.isInvalid()) 14207 return ExprError(); 14208 } else { 14209 Result = ThisResult; 14210 } 14211 } 14212 14213 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14214 // bind the OpaqueValueExprs before they're (repeatedly) used. 14215 Expr *SyntacticForm = BinaryOperator::Create( 14216 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14217 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14218 CurFPFeatureOverrides()); 14219 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14220 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14221 } 14222 14223 static bool PrepareArgumentsForCallToObjectOfClassType( 14224 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 14225 MultiExprArg Args, SourceLocation LParenLoc) { 14226 14227 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14228 unsigned NumParams = Proto->getNumParams(); 14229 unsigned NumArgsSlots = 14230 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 14231 // Build the full argument list for the method call (the implicit object 14232 // parameter is placed at the beginning of the list). 14233 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 14234 bool IsError = false; 14235 // Initialize the implicit object parameter. 14236 // Check the argument types. 14237 for (unsigned i = 0; i != NumParams; i++) { 14238 Expr *Arg; 14239 if (i < Args.size()) { 14240 Arg = Args[i]; 14241 ExprResult InputInit = 14242 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 14243 S.Context, Method->getParamDecl(i)), 14244 SourceLocation(), Arg); 14245 IsError |= InputInit.isInvalid(); 14246 Arg = InputInit.getAs<Expr>(); 14247 } else { 14248 ExprResult DefArg = 14249 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14250 if (DefArg.isInvalid()) { 14251 IsError = true; 14252 break; 14253 } 14254 Arg = DefArg.getAs<Expr>(); 14255 } 14256 14257 MethodArgs.push_back(Arg); 14258 } 14259 return IsError; 14260 } 14261 14262 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14263 SourceLocation RLoc, 14264 Expr *Base, 14265 MultiExprArg ArgExpr) { 14266 SmallVector<Expr *, 2> Args; 14267 Args.push_back(Base); 14268 for (auto e : ArgExpr) { 14269 Args.push_back(e); 14270 } 14271 DeclarationName OpName = 14272 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14273 14274 SourceRange Range = ArgExpr.empty() 14275 ? SourceRange{} 14276 : SourceRange(ArgExpr.front()->getBeginLoc(), 14277 ArgExpr.back()->getEndLoc()); 14278 14279 // If either side is type-dependent, create an appropriate dependent 14280 // expression. 14281 if (Expr::hasAnyTypeDependentArguments(Args)) { 14282 14283 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14284 // CHECKME: no 'operator' keyword? 14285 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14286 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14287 ExprResult Fn = CreateUnresolvedLookupExpr( 14288 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14289 if (Fn.isInvalid()) 14290 return ExprError(); 14291 // Can't add any actual overloads yet 14292 14293 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14294 Context.DependentTy, VK_PRValue, RLoc, 14295 CurFPFeatureOverrides()); 14296 } 14297 14298 // Handle placeholders 14299 UnbridgedCastsSet UnbridgedCasts; 14300 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 14301 return ExprError(); 14302 } 14303 // Build an empty overload set. 14304 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14305 14306 // Subscript can only be overloaded as a member function. 14307 14308 // Add operator candidates that are member functions. 14309 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14310 14311 // Add builtin operator candidates. 14312 if (Args.size() == 2) 14313 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14314 14315 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14316 14317 // Perform overload resolution. 14318 OverloadCandidateSet::iterator Best; 14319 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14320 case OR_Success: { 14321 // We found a built-in operator or an overloaded operator. 14322 FunctionDecl *FnDecl = Best->Function; 14323 14324 if (FnDecl) { 14325 // We matched an overloaded operator. Build a call to that 14326 // operator. 14327 14328 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 14329 14330 // Convert the arguments. 14331 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14332 SmallVector<Expr *, 2> MethodArgs; 14333 ExprResult Arg0 = PerformObjectArgumentInitialization( 14334 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14335 if (Arg0.isInvalid()) 14336 return ExprError(); 14337 14338 MethodArgs.push_back(Arg0.get()); 14339 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 14340 *this, MethodArgs, Method, ArgExpr, LLoc); 14341 if (IsError) 14342 return ExprError(); 14343 14344 // Build the actual expression node. 14345 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14346 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14347 ExprResult FnExpr = CreateFunctionRefExpr( 14348 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 14349 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 14350 if (FnExpr.isInvalid()) 14351 return ExprError(); 14352 14353 // Determine the result type 14354 QualType ResultTy = FnDecl->getReturnType(); 14355 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14356 ResultTy = ResultTy.getNonLValueExprType(Context); 14357 14358 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14359 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc, 14360 CurFPFeatureOverrides()); 14361 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14362 return ExprError(); 14363 14364 if (CheckFunctionCall(Method, TheCall, 14365 Method->getType()->castAs<FunctionProtoType>())) 14366 return ExprError(); 14367 14368 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14369 FnDecl); 14370 } else { 14371 // We matched a built-in operator. Convert the arguments, then 14372 // break out so that we will build the appropriate built-in 14373 // operator node. 14374 ExprResult ArgsRes0 = PerformImplicitConversion( 14375 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14376 AA_Passing, CCK_ForBuiltinOverloadedOp); 14377 if (ArgsRes0.isInvalid()) 14378 return ExprError(); 14379 Args[0] = ArgsRes0.get(); 14380 14381 ExprResult ArgsRes1 = PerformImplicitConversion( 14382 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14383 AA_Passing, CCK_ForBuiltinOverloadedOp); 14384 if (ArgsRes1.isInvalid()) 14385 return ExprError(); 14386 Args[1] = ArgsRes1.get(); 14387 14388 break; 14389 } 14390 } 14391 14392 case OR_No_Viable_Function: { 14393 PartialDiagnostic PD = 14394 CandidateSet.empty() 14395 ? (PDiag(diag::err_ovl_no_oper) 14396 << Args[0]->getType() << /*subscript*/ 0 14397 << Args[0]->getSourceRange() << Range) 14398 : (PDiag(diag::err_ovl_no_viable_subscript) 14399 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 14400 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14401 OCD_AllCandidates, ArgExpr, "[]", LLoc); 14402 return ExprError(); 14403 } 14404 14405 case OR_Ambiguous: 14406 if (Args.size() == 2) { 14407 CandidateSet.NoteCandidates( 14408 PartialDiagnosticAt( 14409 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14410 << "[]" << Args[0]->getType() << Args[1]->getType() 14411 << Args[0]->getSourceRange() << Range), 14412 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14413 } else { 14414 CandidateSet.NoteCandidates( 14415 PartialDiagnosticAt(LLoc, 14416 PDiag(diag::err_ovl_ambiguous_subscript_call) 14417 << Args[0]->getType() 14418 << Args[0]->getSourceRange() << Range), 14419 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14420 } 14421 return ExprError(); 14422 14423 case OR_Deleted: 14424 CandidateSet.NoteCandidates( 14425 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14426 << "[]" << Args[0]->getSourceRange() 14427 << Range), 14428 *this, OCD_AllCandidates, Args, "[]", LLoc); 14429 return ExprError(); 14430 } 14431 14432 // We matched a built-in operator; build it. 14433 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14434 } 14435 14436 /// BuildCallToMemberFunction - Build a call to a member 14437 /// function. MemExpr is the expression that refers to the member 14438 /// function (and includes the object parameter), Args/NumArgs are the 14439 /// arguments to the function call (not including the object 14440 /// parameter). The caller needs to validate that the member 14441 /// expression refers to a non-static member function or an overloaded 14442 /// member function. 14443 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14444 SourceLocation LParenLoc, 14445 MultiExprArg Args, 14446 SourceLocation RParenLoc, 14447 Expr *ExecConfig, bool IsExecConfig, 14448 bool AllowRecovery) { 14449 assert(MemExprE->getType() == Context.BoundMemberTy || 14450 MemExprE->getType() == Context.OverloadTy); 14451 14452 // Dig out the member expression. This holds both the object 14453 // argument and the member function we're referring to. 14454 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14455 14456 // Determine whether this is a call to a pointer-to-member function. 14457 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14458 assert(op->getType() == Context.BoundMemberTy); 14459 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14460 14461 QualType fnType = 14462 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14463 14464 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14465 QualType resultType = proto->getCallResultType(Context); 14466 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14467 14468 // Check that the object type isn't more qualified than the 14469 // member function we're calling. 14470 Qualifiers funcQuals = proto->getMethodQuals(); 14471 14472 QualType objectType = op->getLHS()->getType(); 14473 if (op->getOpcode() == BO_PtrMemI) 14474 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14475 Qualifiers objectQuals = objectType.getQualifiers(); 14476 14477 Qualifiers difference = objectQuals - funcQuals; 14478 difference.removeObjCGCAttr(); 14479 difference.removeAddressSpace(); 14480 if (difference) { 14481 std::string qualsString = difference.getAsString(); 14482 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14483 << fnType.getUnqualifiedType() 14484 << qualsString 14485 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14486 } 14487 14488 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14489 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14490 CurFPFeatureOverrides(), proto->getNumParams()); 14491 14492 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14493 call, nullptr)) 14494 return ExprError(); 14495 14496 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14497 return ExprError(); 14498 14499 if (CheckOtherCall(call, proto)) 14500 return ExprError(); 14501 14502 return MaybeBindToTemporary(call); 14503 } 14504 14505 // We only try to build a recovery expr at this level if we can preserve 14506 // the return type, otherwise we return ExprError() and let the caller 14507 // recover. 14508 auto BuildRecoveryExpr = [&](QualType Type) { 14509 if (!AllowRecovery) 14510 return ExprError(); 14511 std::vector<Expr *> SubExprs = {MemExprE}; 14512 llvm::append_range(SubExprs, Args); 14513 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14514 Type); 14515 }; 14516 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14517 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 14518 RParenLoc, CurFPFeatureOverrides()); 14519 14520 UnbridgedCastsSet UnbridgedCasts; 14521 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14522 return ExprError(); 14523 14524 MemberExpr *MemExpr; 14525 CXXMethodDecl *Method = nullptr; 14526 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14527 NestedNameSpecifier *Qualifier = nullptr; 14528 if (isa<MemberExpr>(NakedMemExpr)) { 14529 MemExpr = cast<MemberExpr>(NakedMemExpr); 14530 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14531 FoundDecl = MemExpr->getFoundDecl(); 14532 Qualifier = MemExpr->getQualifier(); 14533 UnbridgedCasts.restore(); 14534 } else { 14535 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14536 Qualifier = UnresExpr->getQualifier(); 14537 14538 QualType ObjectType = UnresExpr->getBaseType(); 14539 Expr::Classification ObjectClassification 14540 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14541 : UnresExpr->getBase()->Classify(Context); 14542 14543 // Add overload candidates 14544 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14545 OverloadCandidateSet::CSK_Normal); 14546 14547 // FIXME: avoid copy. 14548 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14549 if (UnresExpr->hasExplicitTemplateArgs()) { 14550 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14551 TemplateArgs = &TemplateArgsBuffer; 14552 } 14553 14554 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14555 E = UnresExpr->decls_end(); I != E; ++I) { 14556 14557 NamedDecl *Func = *I; 14558 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14559 if (isa<UsingShadowDecl>(Func)) 14560 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14561 14562 14563 // Microsoft supports direct constructor calls. 14564 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14565 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14566 CandidateSet, 14567 /*SuppressUserConversions*/ false); 14568 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14569 // If explicit template arguments were provided, we can't call a 14570 // non-template member function. 14571 if (TemplateArgs) 14572 continue; 14573 14574 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14575 ObjectClassification, Args, CandidateSet, 14576 /*SuppressUserConversions=*/false); 14577 } else { 14578 AddMethodTemplateCandidate( 14579 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14580 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14581 /*SuppressUserConversions=*/false); 14582 } 14583 } 14584 14585 DeclarationName DeclName = UnresExpr->getMemberName(); 14586 14587 UnbridgedCasts.restore(); 14588 14589 OverloadCandidateSet::iterator Best; 14590 bool Succeeded = false; 14591 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14592 Best)) { 14593 case OR_Success: 14594 Method = cast<CXXMethodDecl>(Best->Function); 14595 FoundDecl = Best->FoundDecl; 14596 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14597 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14598 break; 14599 // If FoundDecl is different from Method (such as if one is a template 14600 // and the other a specialization), make sure DiagnoseUseOfDecl is 14601 // called on both. 14602 // FIXME: This would be more comprehensively addressed by modifying 14603 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14604 // being used. 14605 if (Method != FoundDecl.getDecl() && 14606 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14607 break; 14608 Succeeded = true; 14609 break; 14610 14611 case OR_No_Viable_Function: 14612 CandidateSet.NoteCandidates( 14613 PartialDiagnosticAt( 14614 UnresExpr->getMemberLoc(), 14615 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14616 << DeclName << MemExprE->getSourceRange()), 14617 *this, OCD_AllCandidates, Args); 14618 break; 14619 case OR_Ambiguous: 14620 CandidateSet.NoteCandidates( 14621 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14622 PDiag(diag::err_ovl_ambiguous_member_call) 14623 << DeclName << MemExprE->getSourceRange()), 14624 *this, OCD_AmbiguousCandidates, Args); 14625 break; 14626 case OR_Deleted: 14627 CandidateSet.NoteCandidates( 14628 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14629 PDiag(diag::err_ovl_deleted_member_call) 14630 << DeclName << MemExprE->getSourceRange()), 14631 *this, OCD_AllCandidates, Args); 14632 break; 14633 } 14634 // Overload resolution fails, try to recover. 14635 if (!Succeeded) 14636 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14637 14638 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14639 14640 // If overload resolution picked a static member, build a 14641 // non-member call based on that function. 14642 if (Method->isStatic()) { 14643 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 14644 ExecConfig, IsExecConfig); 14645 } 14646 14647 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14648 } 14649 14650 QualType ResultType = Method->getReturnType(); 14651 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14652 ResultType = ResultType.getNonLValueExprType(Context); 14653 14654 assert(Method && "Member call to something that isn't a method?"); 14655 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14656 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14657 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14658 CurFPFeatureOverrides(), Proto->getNumParams()); 14659 14660 // Check for a valid return type. 14661 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14662 TheCall, Method)) 14663 return BuildRecoveryExpr(ResultType); 14664 14665 // Convert the object argument (for a non-static member function call). 14666 // We only need to do this if there was actually an overload; otherwise 14667 // it was done at lookup. 14668 if (!Method->isStatic()) { 14669 ExprResult ObjectArg = 14670 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14671 FoundDecl, Method); 14672 if (ObjectArg.isInvalid()) 14673 return ExprError(); 14674 MemExpr->setBase(ObjectArg.get()); 14675 } 14676 14677 // Convert the rest of the arguments 14678 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14679 RParenLoc)) 14680 return BuildRecoveryExpr(ResultType); 14681 14682 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14683 14684 if (CheckFunctionCall(Method, TheCall, Proto)) 14685 return ExprError(); 14686 14687 // In the case the method to call was not selected by the overloading 14688 // resolution process, we still need to handle the enable_if attribute. Do 14689 // that here, so it will not hide previous -- and more relevant -- errors. 14690 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14691 if (const EnableIfAttr *Attr = 14692 CheckEnableIf(Method, LParenLoc, Args, true)) { 14693 Diag(MemE->getMemberLoc(), 14694 diag::err_ovl_no_viable_member_function_in_call) 14695 << Method << Method->getSourceRange(); 14696 Diag(Method->getLocation(), 14697 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14698 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14699 return ExprError(); 14700 } 14701 } 14702 14703 if ((isa<CXXConstructorDecl>(CurContext) || 14704 isa<CXXDestructorDecl>(CurContext)) && 14705 TheCall->getMethodDecl()->isPure()) { 14706 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14707 14708 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14709 MemExpr->performsVirtualDispatch(getLangOpts())) { 14710 Diag(MemExpr->getBeginLoc(), 14711 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14712 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14713 << MD->getParent(); 14714 14715 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14716 if (getLangOpts().AppleKext) 14717 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14718 << MD->getParent() << MD->getDeclName(); 14719 } 14720 } 14721 14722 if (CXXDestructorDecl *DD = 14723 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14724 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14725 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14726 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14727 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14728 MemExpr->getMemberLoc()); 14729 } 14730 14731 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14732 TheCall->getMethodDecl()); 14733 } 14734 14735 /// BuildCallToObjectOfClassType - Build a call to an object of class 14736 /// type (C++ [over.call.object]), which can end up invoking an 14737 /// overloaded function call operator (@c operator()) or performing a 14738 /// user-defined conversion on the object argument. 14739 ExprResult 14740 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14741 SourceLocation LParenLoc, 14742 MultiExprArg Args, 14743 SourceLocation RParenLoc) { 14744 if (checkPlaceholderForOverload(*this, Obj)) 14745 return ExprError(); 14746 ExprResult Object = Obj; 14747 14748 UnbridgedCastsSet UnbridgedCasts; 14749 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14750 return ExprError(); 14751 14752 assert(Object.get()->getType()->isRecordType() && 14753 "Requires object type argument"); 14754 14755 // C++ [over.call.object]p1: 14756 // If the primary-expression E in the function call syntax 14757 // evaluates to a class object of type "cv T", then the set of 14758 // candidate functions includes at least the function call 14759 // operators of T. The function call operators of T are obtained by 14760 // ordinary lookup of the name operator() in the context of 14761 // (E).operator(). 14762 OverloadCandidateSet CandidateSet(LParenLoc, 14763 OverloadCandidateSet::CSK_Operator); 14764 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14765 14766 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14767 diag::err_incomplete_object_call, Object.get())) 14768 return true; 14769 14770 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14771 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14772 LookupQualifiedName(R, Record->getDecl()); 14773 R.suppressDiagnostics(); 14774 14775 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14776 Oper != OperEnd; ++Oper) { 14777 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14778 Object.get()->Classify(Context), Args, CandidateSet, 14779 /*SuppressUserConversion=*/false); 14780 } 14781 14782 // C++ [over.call.object]p2: 14783 // In addition, for each (non-explicit in C++0x) conversion function 14784 // declared in T of the form 14785 // 14786 // operator conversion-type-id () cv-qualifier; 14787 // 14788 // where cv-qualifier is the same cv-qualification as, or a 14789 // greater cv-qualification than, cv, and where conversion-type-id 14790 // denotes the type "pointer to function of (P1,...,Pn) returning 14791 // R", or the type "reference to pointer to function of 14792 // (P1,...,Pn) returning R", or the type "reference to function 14793 // of (P1,...,Pn) returning R", a surrogate call function [...] 14794 // is also considered as a candidate function. Similarly, 14795 // surrogate call functions are added to the set of candidate 14796 // functions for each conversion function declared in an 14797 // accessible base class provided the function is not hidden 14798 // within T by another intervening declaration. 14799 const auto &Conversions = 14800 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14801 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14802 NamedDecl *D = *I; 14803 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14804 if (isa<UsingShadowDecl>(D)) 14805 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14806 14807 // Skip over templated conversion functions; they aren't 14808 // surrogates. 14809 if (isa<FunctionTemplateDecl>(D)) 14810 continue; 14811 14812 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14813 if (!Conv->isExplicit()) { 14814 // Strip the reference type (if any) and then the pointer type (if 14815 // any) to get down to what might be a function type. 14816 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14817 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14818 ConvType = ConvPtrType->getPointeeType(); 14819 14820 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14821 { 14822 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14823 Object.get(), Args, CandidateSet); 14824 } 14825 } 14826 } 14827 14828 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14829 14830 // Perform overload resolution. 14831 OverloadCandidateSet::iterator Best; 14832 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14833 Best)) { 14834 case OR_Success: 14835 // Overload resolution succeeded; we'll build the appropriate call 14836 // below. 14837 break; 14838 14839 case OR_No_Viable_Function: { 14840 PartialDiagnostic PD = 14841 CandidateSet.empty() 14842 ? (PDiag(diag::err_ovl_no_oper) 14843 << Object.get()->getType() << /*call*/ 1 14844 << Object.get()->getSourceRange()) 14845 : (PDiag(diag::err_ovl_no_viable_object_call) 14846 << Object.get()->getType() << Object.get()->getSourceRange()); 14847 CandidateSet.NoteCandidates( 14848 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14849 OCD_AllCandidates, Args); 14850 break; 14851 } 14852 case OR_Ambiguous: 14853 CandidateSet.NoteCandidates( 14854 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14855 PDiag(diag::err_ovl_ambiguous_object_call) 14856 << Object.get()->getType() 14857 << Object.get()->getSourceRange()), 14858 *this, OCD_AmbiguousCandidates, Args); 14859 break; 14860 14861 case OR_Deleted: 14862 CandidateSet.NoteCandidates( 14863 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14864 PDiag(diag::err_ovl_deleted_object_call) 14865 << Object.get()->getType() 14866 << Object.get()->getSourceRange()), 14867 *this, OCD_AllCandidates, Args); 14868 break; 14869 } 14870 14871 if (Best == CandidateSet.end()) 14872 return true; 14873 14874 UnbridgedCasts.restore(); 14875 14876 if (Best->Function == nullptr) { 14877 // Since there is no function declaration, this is one of the 14878 // surrogate candidates. Dig out the conversion function. 14879 CXXConversionDecl *Conv 14880 = cast<CXXConversionDecl>( 14881 Best->Conversions[0].UserDefined.ConversionFunction); 14882 14883 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14884 Best->FoundDecl); 14885 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14886 return ExprError(); 14887 assert(Conv == Best->FoundDecl.getDecl() && 14888 "Found Decl & conversion-to-functionptr should be same, right?!"); 14889 // We selected one of the surrogate functions that converts the 14890 // object parameter to a function pointer. Perform the conversion 14891 // on the object argument, then let BuildCallExpr finish the job. 14892 14893 // Create an implicit member expr to refer to the conversion operator. 14894 // and then call it. 14895 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14896 Conv, HadMultipleCandidates); 14897 if (Call.isInvalid()) 14898 return ExprError(); 14899 // Record usage of conversion in an implicit cast. 14900 Call = ImplicitCastExpr::Create( 14901 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14902 nullptr, VK_PRValue, CurFPFeatureOverrides()); 14903 14904 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14905 } 14906 14907 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14908 14909 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14910 // that calls this method, using Object for the implicit object 14911 // parameter and passing along the remaining arguments. 14912 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14913 14914 // An error diagnostic has already been printed when parsing the declaration. 14915 if (Method->isInvalidDecl()) 14916 return ExprError(); 14917 14918 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14919 unsigned NumParams = Proto->getNumParams(); 14920 14921 DeclarationNameInfo OpLocInfo( 14922 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14923 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14924 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14925 Obj, HadMultipleCandidates, 14926 OpLocInfo.getLoc(), 14927 OpLocInfo.getInfo()); 14928 if (NewFn.isInvalid()) 14929 return true; 14930 14931 SmallVector<Expr *, 8> MethodArgs; 14932 MethodArgs.reserve(NumParams + 1); 14933 14934 bool IsError = false; 14935 14936 // Initialize the implicit object parameter. 14937 ExprResult ObjRes = 14938 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14939 Best->FoundDecl, Method); 14940 if (ObjRes.isInvalid()) 14941 IsError = true; 14942 else 14943 Object = ObjRes; 14944 MethodArgs.push_back(Object.get()); 14945 14946 IsError |= PrepareArgumentsForCallToObjectOfClassType( 14947 *this, MethodArgs, Method, Args, LParenLoc); 14948 14949 // If this is a variadic call, handle args passed through "...". 14950 if (Proto->isVariadic()) { 14951 // Promote the arguments (C99 6.5.2.2p7). 14952 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14953 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14954 nullptr); 14955 IsError |= Arg.isInvalid(); 14956 MethodArgs.push_back(Arg.get()); 14957 } 14958 } 14959 14960 if (IsError) 14961 return true; 14962 14963 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14964 14965 // Once we've built TheCall, all of the expressions are properly owned. 14966 QualType ResultTy = Method->getReturnType(); 14967 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14968 ResultTy = ResultTy.getNonLValueExprType(Context); 14969 14970 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14971 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14972 CurFPFeatureOverrides()); 14973 14974 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14975 return true; 14976 14977 if (CheckFunctionCall(Method, TheCall, Proto)) 14978 return true; 14979 14980 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14981 } 14982 14983 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14984 /// (if one exists), where @c Base is an expression of class type and 14985 /// @c Member is the name of the member we're trying to find. 14986 ExprResult 14987 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14988 bool *NoArrowOperatorFound) { 14989 assert(Base->getType()->isRecordType() && 14990 "left-hand side must have class type"); 14991 14992 if (checkPlaceholderForOverload(*this, Base)) 14993 return ExprError(); 14994 14995 SourceLocation Loc = Base->getExprLoc(); 14996 14997 // C++ [over.ref]p1: 14998 // 14999 // [...] An expression x->m is interpreted as (x.operator->())->m 15000 // for a class object x of type T if T::operator->() exists and if 15001 // the operator is selected as the best match function by the 15002 // overload resolution mechanism (13.3). 15003 DeclarationName OpName = 15004 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 15005 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 15006 15007 if (RequireCompleteType(Loc, Base->getType(), 15008 diag::err_typecheck_incomplete_tag, Base)) 15009 return ExprError(); 15010 15011 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 15012 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 15013 R.suppressDiagnostics(); 15014 15015 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 15016 Oper != OperEnd; ++Oper) { 15017 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 15018 None, CandidateSet, /*SuppressUserConversion=*/false); 15019 } 15020 15021 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15022 15023 // Perform overload resolution. 15024 OverloadCandidateSet::iterator Best; 15025 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 15026 case OR_Success: 15027 // Overload resolution succeeded; we'll build the call below. 15028 break; 15029 15030 case OR_No_Viable_Function: { 15031 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 15032 if (CandidateSet.empty()) { 15033 QualType BaseType = Base->getType(); 15034 if (NoArrowOperatorFound) { 15035 // Report this specific error to the caller instead of emitting a 15036 // diagnostic, as requested. 15037 *NoArrowOperatorFound = true; 15038 return ExprError(); 15039 } 15040 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 15041 << BaseType << Base->getSourceRange(); 15042 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 15043 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 15044 << FixItHint::CreateReplacement(OpLoc, "."); 15045 } 15046 } else 15047 Diag(OpLoc, diag::err_ovl_no_viable_oper) 15048 << "operator->" << Base->getSourceRange(); 15049 CandidateSet.NoteCandidates(*this, Base, Cands); 15050 return ExprError(); 15051 } 15052 case OR_Ambiguous: 15053 CandidateSet.NoteCandidates( 15054 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 15055 << "->" << Base->getType() 15056 << Base->getSourceRange()), 15057 *this, OCD_AmbiguousCandidates, Base); 15058 return ExprError(); 15059 15060 case OR_Deleted: 15061 CandidateSet.NoteCandidates( 15062 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 15063 << "->" << Base->getSourceRange()), 15064 *this, OCD_AllCandidates, Base); 15065 return ExprError(); 15066 } 15067 15068 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 15069 15070 // Convert the object parameter. 15071 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15072 ExprResult BaseResult = 15073 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 15074 Best->FoundDecl, Method); 15075 if (BaseResult.isInvalid()) 15076 return ExprError(); 15077 Base = BaseResult.get(); 15078 15079 // Build the operator call. 15080 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15081 Base, HadMultipleCandidates, OpLoc); 15082 if (FnExpr.isInvalid()) 15083 return ExprError(); 15084 15085 QualType ResultTy = Method->getReturnType(); 15086 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15087 ResultTy = ResultTy.getNonLValueExprType(Context); 15088 CXXOperatorCallExpr *TheCall = 15089 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 15090 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 15091 15092 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 15093 return ExprError(); 15094 15095 if (CheckFunctionCall(Method, TheCall, 15096 Method->getType()->castAs<FunctionProtoType>())) 15097 return ExprError(); 15098 15099 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15100 } 15101 15102 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 15103 /// a literal operator described by the provided lookup results. 15104 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 15105 DeclarationNameInfo &SuffixInfo, 15106 ArrayRef<Expr*> Args, 15107 SourceLocation LitEndLoc, 15108 TemplateArgumentListInfo *TemplateArgs) { 15109 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 15110 15111 OverloadCandidateSet CandidateSet(UDSuffixLoc, 15112 OverloadCandidateSet::CSK_Normal); 15113 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 15114 TemplateArgs); 15115 15116 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15117 15118 // Perform overload resolution. This will usually be trivial, but might need 15119 // to perform substitutions for a literal operator template. 15120 OverloadCandidateSet::iterator Best; 15121 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 15122 case OR_Success: 15123 case OR_Deleted: 15124 break; 15125 15126 case OR_No_Viable_Function: 15127 CandidateSet.NoteCandidates( 15128 PartialDiagnosticAt(UDSuffixLoc, 15129 PDiag(diag::err_ovl_no_viable_function_in_call) 15130 << R.getLookupName()), 15131 *this, OCD_AllCandidates, Args); 15132 return ExprError(); 15133 15134 case OR_Ambiguous: 15135 CandidateSet.NoteCandidates( 15136 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 15137 << R.getLookupName()), 15138 *this, OCD_AmbiguousCandidates, Args); 15139 return ExprError(); 15140 } 15141 15142 FunctionDecl *FD = Best->Function; 15143 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 15144 nullptr, HadMultipleCandidates, 15145 SuffixInfo.getLoc(), 15146 SuffixInfo.getInfo()); 15147 if (Fn.isInvalid()) 15148 return true; 15149 15150 // Check the argument types. This should almost always be a no-op, except 15151 // that array-to-pointer decay is applied to string literals. 15152 Expr *ConvArgs[2]; 15153 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 15154 ExprResult InputInit = PerformCopyInitialization( 15155 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 15156 SourceLocation(), Args[ArgIdx]); 15157 if (InputInit.isInvalid()) 15158 return true; 15159 ConvArgs[ArgIdx] = InputInit.get(); 15160 } 15161 15162 QualType ResultTy = FD->getReturnType(); 15163 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15164 ResultTy = ResultTy.getNonLValueExprType(Context); 15165 15166 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 15167 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 15168 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 15169 15170 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 15171 return ExprError(); 15172 15173 if (CheckFunctionCall(FD, UDL, nullptr)) 15174 return ExprError(); 15175 15176 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 15177 } 15178 15179 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 15180 /// given LookupResult is non-empty, it is assumed to describe a member which 15181 /// will be invoked. Otherwise, the function will be found via argument 15182 /// dependent lookup. 15183 /// CallExpr is set to a valid expression and FRS_Success returned on success, 15184 /// otherwise CallExpr is set to ExprError() and some non-success value 15185 /// is returned. 15186 Sema::ForRangeStatus 15187 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 15188 SourceLocation RangeLoc, 15189 const DeclarationNameInfo &NameInfo, 15190 LookupResult &MemberLookup, 15191 OverloadCandidateSet *CandidateSet, 15192 Expr *Range, ExprResult *CallExpr) { 15193 Scope *S = nullptr; 15194 15195 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 15196 if (!MemberLookup.empty()) { 15197 ExprResult MemberRef = 15198 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 15199 /*IsPtr=*/false, CXXScopeSpec(), 15200 /*TemplateKWLoc=*/SourceLocation(), 15201 /*FirstQualifierInScope=*/nullptr, 15202 MemberLookup, 15203 /*TemplateArgs=*/nullptr, S); 15204 if (MemberRef.isInvalid()) { 15205 *CallExpr = ExprError(); 15206 return FRS_DiagnosticIssued; 15207 } 15208 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 15209 if (CallExpr->isInvalid()) { 15210 *CallExpr = ExprError(); 15211 return FRS_DiagnosticIssued; 15212 } 15213 } else { 15214 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 15215 NestedNameSpecifierLoc(), 15216 NameInfo, UnresolvedSet<0>()); 15217 if (FnR.isInvalid()) 15218 return FRS_DiagnosticIssued; 15219 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 15220 15221 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 15222 CandidateSet, CallExpr); 15223 if (CandidateSet->empty() || CandidateSetError) { 15224 *CallExpr = ExprError(); 15225 return FRS_NoViableFunction; 15226 } 15227 OverloadCandidateSet::iterator Best; 15228 OverloadingResult OverloadResult = 15229 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 15230 15231 if (OverloadResult == OR_No_Viable_Function) { 15232 *CallExpr = ExprError(); 15233 return FRS_NoViableFunction; 15234 } 15235 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 15236 Loc, nullptr, CandidateSet, &Best, 15237 OverloadResult, 15238 /*AllowTypoCorrection=*/false); 15239 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 15240 *CallExpr = ExprError(); 15241 return FRS_DiagnosticIssued; 15242 } 15243 } 15244 return FRS_Success; 15245 } 15246 15247 15248 /// FixOverloadedFunctionReference - E is an expression that refers to 15249 /// a C++ overloaded function (possibly with some parentheses and 15250 /// perhaps a '&' around it). We have resolved the overloaded function 15251 /// to the function declaration Fn, so patch up the expression E to 15252 /// refer (possibly indirectly) to Fn. Returns the new expr. 15253 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15254 FunctionDecl *Fn) { 15255 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15256 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15257 Found, Fn); 15258 if (SubExpr == PE->getSubExpr()) 15259 return PE; 15260 15261 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15262 } 15263 15264 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15265 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15266 Found, Fn); 15267 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15268 SubExpr->getType()) && 15269 "Implicit cast type cannot be determined from overload"); 15270 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15271 if (SubExpr == ICE->getSubExpr()) 15272 return ICE; 15273 15274 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15275 SubExpr, nullptr, ICE->getValueKind(), 15276 CurFPFeatureOverrides()); 15277 } 15278 15279 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15280 if (!GSE->isResultDependent()) { 15281 Expr *SubExpr = 15282 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15283 if (SubExpr == GSE->getResultExpr()) 15284 return GSE; 15285 15286 // Replace the resulting type information before rebuilding the generic 15287 // selection expression. 15288 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15289 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15290 unsigned ResultIdx = GSE->getResultIndex(); 15291 AssocExprs[ResultIdx] = SubExpr; 15292 15293 return GenericSelectionExpr::Create( 15294 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15295 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15296 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15297 ResultIdx); 15298 } 15299 // Rather than fall through to the unreachable, return the original generic 15300 // selection expression. 15301 return GSE; 15302 } 15303 15304 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15305 assert(UnOp->getOpcode() == UO_AddrOf && 15306 "Can only take the address of an overloaded function"); 15307 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15308 if (Method->isStatic()) { 15309 // Do nothing: static member functions aren't any different 15310 // from non-member functions. 15311 } else { 15312 // Fix the subexpression, which really has to be an 15313 // UnresolvedLookupExpr holding an overloaded member function 15314 // or template. 15315 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15316 Found, Fn); 15317 if (SubExpr == UnOp->getSubExpr()) 15318 return UnOp; 15319 15320 assert(isa<DeclRefExpr>(SubExpr) 15321 && "fixed to something other than a decl ref"); 15322 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15323 && "fixed to a member ref with no nested name qualifier"); 15324 15325 // We have taken the address of a pointer to member 15326 // function. Perform the computation here so that we get the 15327 // appropriate pointer to member type. 15328 QualType ClassType 15329 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15330 QualType MemPtrType 15331 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15332 // Under the MS ABI, lock down the inheritance model now. 15333 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15334 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15335 15336 return UnaryOperator::Create( 15337 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, 15338 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15339 } 15340 } 15341 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15342 Found, Fn); 15343 if (SubExpr == UnOp->getSubExpr()) 15344 return UnOp; 15345 15346 // FIXME: This can't currently fail, but in principle it could. 15347 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr) 15348 .get(); 15349 } 15350 15351 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15352 // FIXME: avoid copy. 15353 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15354 if (ULE->hasExplicitTemplateArgs()) { 15355 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15356 TemplateArgs = &TemplateArgsBuffer; 15357 } 15358 15359 QualType Type = Fn->getType(); 15360 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; 15361 15362 // FIXME: Duplicated from BuildDeclarationNameExpr. 15363 if (unsigned BID = Fn->getBuiltinID()) { 15364 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 15365 Type = Context.BuiltinFnTy; 15366 ValueKind = VK_PRValue; 15367 } 15368 } 15369 15370 DeclRefExpr *DRE = BuildDeclRefExpr( 15371 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), 15372 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); 15373 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15374 return DRE; 15375 } 15376 15377 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15378 // FIXME: avoid copy. 15379 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15380 if (MemExpr->hasExplicitTemplateArgs()) { 15381 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15382 TemplateArgs = &TemplateArgsBuffer; 15383 } 15384 15385 Expr *Base; 15386 15387 // If we're filling in a static method where we used to have an 15388 // implicit member access, rewrite to a simple decl ref. 15389 if (MemExpr->isImplicitAccess()) { 15390 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15391 DeclRefExpr *DRE = BuildDeclRefExpr( 15392 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15393 MemExpr->getQualifierLoc(), Found.getDecl(), 15394 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15395 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15396 return DRE; 15397 } else { 15398 SourceLocation Loc = MemExpr->getMemberLoc(); 15399 if (MemExpr->getQualifier()) 15400 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15401 Base = 15402 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15403 } 15404 } else 15405 Base = MemExpr->getBase(); 15406 15407 ExprValueKind valueKind; 15408 QualType type; 15409 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15410 valueKind = VK_LValue; 15411 type = Fn->getType(); 15412 } else { 15413 valueKind = VK_PRValue; 15414 type = Context.BoundMemberTy; 15415 } 15416 15417 return BuildMemberExpr( 15418 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15419 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15420 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15421 type, valueKind, OK_Ordinary, TemplateArgs); 15422 } 15423 15424 llvm_unreachable("Invalid reference to overloaded function"); 15425 } 15426 15427 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15428 DeclAccessPair Found, 15429 FunctionDecl *Fn) { 15430 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15431 } 15432 15433 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 15434 FunctionDecl *Function) { 15435 if (!PartialOverloading || !Function) 15436 return true; 15437 if (Function->isVariadic()) 15438 return false; 15439 if (const auto *Proto = 15440 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 15441 if (Proto->isTemplateVariadic()) 15442 return false; 15443 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 15444 if (const auto *Proto = 15445 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 15446 if (Proto->isTemplateVariadic()) 15447 return false; 15448 return true; 15449 } 15450