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/ASTLambda.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/DependenceFlags.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/AST/Type.h" 23 #include "clang/AST/TypeOrdering.h" 24 #include "clang/Basic/Diagnostic.h" 25 #include "clang/Basic/DiagnosticOptions.h" 26 #include "clang/Basic/OperatorKinds.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/EnterExpressionEvaluationContext.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/Overload.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "clang/Sema/Template.h" 36 #include "clang/Sema/TemplateDeduction.h" 37 #include "llvm/ADT/DenseSet.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/SmallString.h" 41 #include "llvm/ADT/SmallVector.h" 42 #include "llvm/Support/Casting.h" 43 #include <algorithm> 44 #include <cstddef> 45 #include <cstdlib> 46 #include <optional> 47 48 using namespace clang; 49 using namespace sema; 50 51 using AllowedExplicit = Sema::AllowedExplicit; 52 53 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 54 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 55 return P->hasAttr<PassObjectSizeAttr>(); 56 }); 57 } 58 59 /// A convenience routine for creating a decayed reference to a function. 60 static ExprResult CreateFunctionRefExpr( 61 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 62 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 63 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 64 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 65 return ExprError(); 66 // If FoundDecl is different from Fn (such as if one is a template 67 // and the other a specialization), make sure DiagnoseUseOfDecl is 68 // called on both. 69 // FIXME: This would be more comprehensively addressed by modifying 70 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 71 // being used. 72 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 73 return ExprError(); 74 DeclRefExpr *DRE = new (S.Context) 75 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 76 if (HadMultipleCandidates) 77 DRE->setHadMultipleCandidates(true); 78 79 S.MarkDeclRefReferenced(DRE, Base); 80 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 81 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 82 S.ResolveExceptionSpec(Loc, FPT); 83 DRE->setType(Fn->getType()); 84 } 85 } 86 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 87 CK_FunctionToPointerDecay); 88 } 89 90 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle, 94 bool AllowObjCWritebackConversion); 95 96 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 97 QualType &ToType, 98 bool InOverloadResolution, 99 StandardConversionSequence &SCS, 100 bool CStyle); 101 static OverloadingResult 102 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 103 UserDefinedConversionSequence& User, 104 OverloadCandidateSet& Conversions, 105 AllowedExplicit AllowExplicit, 106 bool AllowObjCConversionOnExplicit); 107 108 static ImplicitConversionSequence::CompareKind 109 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 110 const StandardConversionSequence& SCS1, 111 const StandardConversionSequence& SCS2); 112 113 static ImplicitConversionSequence::CompareKind 114 CompareQualificationConversions(Sema &S, 115 const StandardConversionSequence& SCS1, 116 const StandardConversionSequence& SCS2); 117 118 static ImplicitConversionSequence::CompareKind 119 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 120 const StandardConversionSequence& SCS1, 121 const StandardConversionSequence& SCS2); 122 123 /// GetConversionRank - Retrieve the implicit conversion rank 124 /// corresponding to the given implicit conversion kind. 125 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 126 static const ImplicitConversionRank 127 Rank[] = { 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Promotion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Conversion, 148 ICR_Conversion, 149 ICR_OCL_Scalar_Widening, 150 ICR_Complex_Real_Conversion, 151 ICR_Conversion, 152 ICR_Conversion, 153 ICR_Writeback_Conversion, 154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 155 // it was omitted by the patch that added 156 // ICK_Zero_Event_Conversion 157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right -- 158 // it was omitted by the patch that added 159 // ICK_Zero_Queue_Conversion 160 ICR_C_Conversion, 161 ICR_C_Conversion_Extension, 162 ICR_Conversion, 163 }; 164 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds); 165 return Rank[(int)Kind]; 166 } 167 168 /// GetImplicitConversionName - Return the name of this kind of 169 /// implicit conversion. 170 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 171 static const char* const Name[] = { 172 "No conversion", 173 "Lvalue-to-rvalue", 174 "Array-to-pointer", 175 "Function-to-pointer", 176 "Function pointer conversion", 177 "Qualification", 178 "Integral promotion", 179 "Floating point promotion", 180 "Complex promotion", 181 "Integral conversion", 182 "Floating conversion", 183 "Complex conversion", 184 "Floating-integral conversion", 185 "Pointer conversion", 186 "Pointer-to-member conversion", 187 "Boolean conversion", 188 "Compatible-types conversion", 189 "Derived-to-base conversion", 190 "Vector conversion", 191 "SVE Vector conversion", 192 "RVV Vector conversion", 193 "Vector splat", 194 "Complex-real conversion", 195 "Block Pointer conversion", 196 "Transparent Union Conversion", 197 "Writeback conversion", 198 "OpenCL Zero Event Conversion", 199 "OpenCL Zero Queue Conversion", 200 "C specific type conversion", 201 "Incompatible pointer conversion", 202 "Fixed point conversion", 203 }; 204 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds); 205 return Name[Kind]; 206 } 207 208 /// StandardConversionSequence - Set the standard conversion 209 /// sequence to the identity conversion. 210 void StandardConversionSequence::setAsIdentityConversion() { 211 First = ICK_Identity; 212 Second = ICK_Identity; 213 Third = ICK_Identity; 214 DeprecatedStringLiteralToCharPtr = false; 215 QualificationIncludesObjCLifetime = false; 216 ReferenceBinding = false; 217 DirectBinding = false; 218 IsLvalueReference = true; 219 BindsToFunctionLvalue = false; 220 BindsToRvalue = false; 221 BindsImplicitObjectArgumentWithoutRefQualifier = false; 222 ObjCLifetimeConversionBinding = false; 223 CopyConstructor = nullptr; 224 } 225 226 /// getRank - Retrieve the rank of this standard conversion sequence 227 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 228 /// implicit conversions. 229 ImplicitConversionRank StandardConversionSequence::getRank() const { 230 ImplicitConversionRank Rank = ICR_Exact_Match; 231 if (GetConversionRank(First) > Rank) 232 Rank = GetConversionRank(First); 233 if (GetConversionRank(Second) > Rank) 234 Rank = GetConversionRank(Second); 235 if (GetConversionRank(Third) > Rank) 236 Rank = GetConversionRank(Third); 237 return Rank; 238 } 239 240 /// isPointerConversionToBool - Determines whether this conversion is 241 /// a conversion of a pointer or pointer-to-member to bool. This is 242 /// used as part of the ranking of standard conversion sequences 243 /// (C++ 13.3.3.2p4). 244 bool StandardConversionSequence::isPointerConversionToBool() const { 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer or function-to-pointer implicit conversions, so 247 // check for their presence as well as checking whether FromType is 248 // a pointer. 249 if (getToType(1)->isBooleanType() && 250 (getFromType()->isPointerType() || 251 getFromType()->isMemberPointerType() || 252 getFromType()->isObjCObjectPointerType() || 253 getFromType()->isBlockPointerType() || 254 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 255 return true; 256 257 return false; 258 } 259 260 /// isPointerConversionToVoidPointer - Determines whether this 261 /// conversion is a conversion of a pointer to a void pointer. This is 262 /// used as part of the ranking of standard conversion sequences (C++ 263 /// 13.3.3.2p4). 264 bool 265 StandardConversionSequence:: 266 isPointerConversionToVoidPointer(ASTContext& Context) const { 267 QualType FromType = getFromType(); 268 QualType ToType = getToType(1); 269 270 // Note that FromType has not necessarily been transformed by the 271 // array-to-pointer implicit conversion, so check for its presence 272 // and redo the conversion to get a pointer. 273 if (First == ICK_Array_To_Pointer) 274 FromType = Context.getArrayDecayedType(FromType); 275 276 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 277 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 278 return ToPtrType->getPointeeType()->isVoidType(); 279 280 return false; 281 } 282 283 /// Skip any implicit casts which could be either part of a narrowing conversion 284 /// or after one in an implicit conversion. 285 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 286 const Expr *Converted) { 287 // We can have cleanups wrapping the converted expression; these need to be 288 // preserved so that destructors run if necessary. 289 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 290 Expr *Inner = 291 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 292 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 293 EWC->getObjects()); 294 } 295 296 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 297 switch (ICE->getCastKind()) { 298 case CK_NoOp: 299 case CK_IntegralCast: 300 case CK_IntegralToBoolean: 301 case CK_IntegralToFloating: 302 case CK_BooleanToSignedIntegral: 303 case CK_FloatingToIntegral: 304 case CK_FloatingToBoolean: 305 case CK_FloatingCast: 306 Converted = ICE->getSubExpr(); 307 continue; 308 309 default: 310 return Converted; 311 } 312 } 313 314 return Converted; 315 } 316 317 /// Check if this standard conversion sequence represents a narrowing 318 /// conversion, according to C++11 [dcl.init.list]p7. 319 /// 320 /// \param Ctx The AST context. 321 /// \param Converted The result of applying this standard conversion sequence. 322 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 323 /// value of the expression prior to the narrowing conversion. 324 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 325 /// type of the expression prior to the narrowing conversion. 326 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 327 /// from floating point types to integral types should be ignored. 328 NarrowingKind StandardConversionSequence::getNarrowingKind( 329 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 330 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 331 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 332 333 // C++11 [dcl.init.list]p7: 334 // A narrowing conversion is an implicit conversion ... 335 QualType FromType = getToType(0); 336 QualType ToType = getToType(1); 337 338 // A conversion to an enumeration type is narrowing if the conversion to 339 // the underlying type is narrowing. This only arises for expressions of 340 // the form 'Enum{init}'. 341 if (auto *ET = ToType->getAs<EnumType>()) 342 ToType = ET->getDecl()->getIntegerType(); 343 344 switch (Second) { 345 // 'bool' is an integral type; dispatch to the right place to handle it. 346 case ICK_Boolean_Conversion: 347 if (FromType->isRealFloatingType()) 348 goto FloatingIntegralConversion; 349 if (FromType->isIntegralOrUnscopedEnumerationType()) 350 goto IntegralConversion; 351 // -- from a pointer type or pointer-to-member type to bool, or 352 return NK_Type_Narrowing; 353 354 // -- from a floating-point type to an integer type, or 355 // 356 // -- from an integer type or unscoped enumeration type to a floating-point 357 // type, except where the source is a constant expression and the actual 358 // value after conversion will fit into the target type and will produce 359 // the original value when converted back to the original type, or 360 case ICK_Floating_Integral: 361 FloatingIntegralConversion: 362 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 363 return NK_Type_Narrowing; 364 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 365 ToType->isRealFloatingType()) { 366 if (IgnoreFloatToIntegralConversion) 367 return NK_Not_Narrowing; 368 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 369 assert(Initializer && "Unknown conversion expression"); 370 371 // If it's value-dependent, we can't tell whether it's narrowing. 372 if (Initializer->isValueDependent()) 373 return NK_Dependent_Narrowing; 374 375 if (std::optional<llvm::APSInt> IntConstantValue = 376 Initializer->getIntegerConstantExpr(Ctx)) { 377 // Convert the integer to the floating type. 378 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 379 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 380 llvm::APFloat::rmNearestTiesToEven); 381 // And back. 382 llvm::APSInt ConvertedValue = *IntConstantValue; 383 bool ignored; 384 Result.convertToInteger(ConvertedValue, 385 llvm::APFloat::rmTowardZero, &ignored); 386 // If the resulting value is different, this was a narrowing conversion. 387 if (*IntConstantValue != ConvertedValue) { 388 ConstantValue = APValue(*IntConstantValue); 389 ConstantType = Initializer->getType(); 390 return NK_Constant_Narrowing; 391 } 392 } else { 393 // Variables are always narrowings. 394 return NK_Variable_Narrowing; 395 } 396 } 397 return NK_Not_Narrowing; 398 399 // -- from long double to double or float, or from double to float, except 400 // where the source is a constant expression and the actual value after 401 // conversion is within the range of values that can be represented (even 402 // if it cannot be represented exactly), or 403 case ICK_Floating_Conversion: 404 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 405 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 406 // FromType is larger than ToType. 407 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 408 409 // If it's value-dependent, we can't tell whether it's narrowing. 410 if (Initializer->isValueDependent()) 411 return NK_Dependent_Narrowing; 412 413 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 414 // Constant! 415 assert(ConstantValue.isFloat()); 416 llvm::APFloat FloatVal = ConstantValue.getFloat(); 417 // Convert the source value into the target type. 418 bool ignored; 419 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 420 Ctx.getFloatTypeSemantics(ToType), 421 llvm::APFloat::rmNearestTiesToEven, &ignored); 422 // If there was no overflow, the source value is within the range of 423 // values that can be represented. 424 if (ConvertStatus & llvm::APFloat::opOverflow) { 425 ConstantType = Initializer->getType(); 426 return NK_Constant_Narrowing; 427 } 428 } else { 429 return NK_Variable_Narrowing; 430 } 431 } 432 return NK_Not_Narrowing; 433 434 // -- from an integer type or unscoped enumeration type to an integer type 435 // that cannot represent all the values of the original type, except where 436 // the source is a constant expression and the actual value after 437 // conversion will fit into the target type and will produce the original 438 // value when converted back to the original type. 439 case ICK_Integral_Conversion: 440 IntegralConversion: { 441 assert(FromType->isIntegralOrUnscopedEnumerationType()); 442 assert(ToType->isIntegralOrUnscopedEnumerationType()); 443 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 444 const unsigned FromWidth = Ctx.getIntWidth(FromType); 445 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 446 const unsigned ToWidth = Ctx.getIntWidth(ToType); 447 448 if (FromWidth > ToWidth || 449 (FromWidth == ToWidth && FromSigned != ToSigned) || 450 (FromSigned && !ToSigned)) { 451 // Not all values of FromType can be represented in ToType. 452 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 453 454 // If it's value-dependent, we can't tell whether it's narrowing. 455 if (Initializer->isValueDependent()) 456 return NK_Dependent_Narrowing; 457 458 std::optional<llvm::APSInt> OptInitializerValue; 459 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 460 // Such conversions on variables are always narrowing. 461 return NK_Variable_Narrowing; 462 } 463 llvm::APSInt &InitializerValue = *OptInitializerValue; 464 bool Narrowing = false; 465 if (FromWidth < ToWidth) { 466 // Negative -> unsigned is narrowing. Otherwise, more bits is never 467 // narrowing. 468 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 469 Narrowing = true; 470 } else { 471 // Add a bit to the InitializerValue so we don't have to worry about 472 // signed vs. unsigned comparisons. 473 InitializerValue = InitializerValue.extend( 474 InitializerValue.getBitWidth() + 1); 475 // Convert the initializer to and from the target width and signed-ness. 476 llvm::APSInt ConvertedValue = InitializerValue; 477 ConvertedValue = ConvertedValue.trunc(ToWidth); 478 ConvertedValue.setIsSigned(ToSigned); 479 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 480 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 481 // If the result is different, this was a narrowing conversion. 482 if (ConvertedValue != InitializerValue) 483 Narrowing = true; 484 } 485 if (Narrowing) { 486 ConstantType = Initializer->getType(); 487 ConstantValue = APValue(InitializerValue); 488 return NK_Constant_Narrowing; 489 } 490 } 491 return NK_Not_Narrowing; 492 } 493 494 default: 495 // Other kinds of conversions are not narrowings. 496 return NK_Not_Narrowing; 497 } 498 } 499 500 /// dump - Print this standard conversion sequence to standard 501 /// error. Useful for debugging overloading issues. 502 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 503 raw_ostream &OS = llvm::errs(); 504 bool PrintedSomething = false; 505 if (First != ICK_Identity) { 506 OS << GetImplicitConversionName(First); 507 PrintedSomething = true; 508 } 509 510 if (Second != ICK_Identity) { 511 if (PrintedSomething) { 512 OS << " -> "; 513 } 514 OS << GetImplicitConversionName(Second); 515 516 if (CopyConstructor) { 517 OS << " (by copy constructor)"; 518 } else if (DirectBinding) { 519 OS << " (direct reference binding)"; 520 } else if (ReferenceBinding) { 521 OS << " (reference binding)"; 522 } 523 PrintedSomething = true; 524 } 525 526 if (Third != ICK_Identity) { 527 if (PrintedSomething) { 528 OS << " -> "; 529 } 530 OS << GetImplicitConversionName(Third); 531 PrintedSomething = true; 532 } 533 534 if (!PrintedSomething) { 535 OS << "No conversions required"; 536 } 537 } 538 539 /// dump - Print this user-defined conversion sequence to standard 540 /// error. Useful for debugging overloading issues. 541 void UserDefinedConversionSequence::dump() const { 542 raw_ostream &OS = llvm::errs(); 543 if (Before.First || Before.Second || Before.Third) { 544 Before.dump(); 545 OS << " -> "; 546 } 547 if (ConversionFunction) 548 OS << '\'' << *ConversionFunction << '\''; 549 else 550 OS << "aggregate initialization"; 551 if (After.First || After.Second || After.Third) { 552 OS << " -> "; 553 After.dump(); 554 } 555 } 556 557 /// dump - Print this implicit conversion sequence to standard 558 /// error. Useful for debugging overloading issues. 559 void ImplicitConversionSequence::dump() const { 560 raw_ostream &OS = llvm::errs(); 561 if (hasInitializerListContainerType()) 562 OS << "Worst list element conversion: "; 563 switch (ConversionKind) { 564 case StandardConversion: 565 OS << "Standard conversion: "; 566 Standard.dump(); 567 break; 568 case UserDefinedConversion: 569 OS << "User-defined conversion: "; 570 UserDefined.dump(); 571 break; 572 case EllipsisConversion: 573 OS << "Ellipsis conversion"; 574 break; 575 case AmbiguousConversion: 576 OS << "Ambiguous conversion"; 577 break; 578 case BadConversion: 579 OS << "Bad conversion"; 580 break; 581 } 582 583 OS << "\n"; 584 } 585 586 void AmbiguousConversionSequence::construct() { 587 new (&conversions()) ConversionSet(); 588 } 589 590 void AmbiguousConversionSequence::destruct() { 591 conversions().~ConversionSet(); 592 } 593 594 void 595 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 596 FromTypePtr = O.FromTypePtr; 597 ToTypePtr = O.ToTypePtr; 598 new (&conversions()) ConversionSet(O.conversions()); 599 } 600 601 namespace { 602 // Structure used by DeductionFailureInfo to store 603 // template argument information. 604 struct DFIArguments { 605 TemplateArgument FirstArg; 606 TemplateArgument SecondArg; 607 }; 608 // Structure used by DeductionFailureInfo to store 609 // template parameter and template argument information. 610 struct DFIParamWithArguments : DFIArguments { 611 TemplateParameter Param; 612 }; 613 // Structure used by DeductionFailureInfo to store template argument 614 // information and the index of the problematic call argument. 615 struct DFIDeducedMismatchArgs : DFIArguments { 616 TemplateArgumentList *TemplateArgs; 617 unsigned CallArgIndex; 618 }; 619 // Structure used by DeductionFailureInfo to store information about 620 // unsatisfied constraints. 621 struct CNSInfo { 622 TemplateArgumentList *TemplateArgs; 623 ConstraintSatisfaction Satisfaction; 624 }; 625 } 626 627 /// Convert from Sema's representation of template deduction information 628 /// to the form used in overload-candidate information. 629 DeductionFailureInfo 630 clang::MakeDeductionFailureInfo(ASTContext &Context, 631 Sema::TemplateDeductionResult TDK, 632 TemplateDeductionInfo &Info) { 633 DeductionFailureInfo Result; 634 Result.Result = static_cast<unsigned>(TDK); 635 Result.HasDiagnostic = false; 636 switch (TDK) { 637 case Sema::TDK_Invalid: 638 case Sema::TDK_InstantiationDepth: 639 case Sema::TDK_TooManyArguments: 640 case Sema::TDK_TooFewArguments: 641 case Sema::TDK_MiscellaneousDeductionFailure: 642 case Sema::TDK_CUDATargetMismatch: 643 Result.Data = nullptr; 644 break; 645 646 case Sema::TDK_Incomplete: 647 case Sema::TDK_InvalidExplicitArguments: 648 Result.Data = Info.Param.getOpaqueValue(); 649 break; 650 651 case Sema::TDK_DeducedMismatch: 652 case Sema::TDK_DeducedMismatchNested: { 653 // FIXME: Should allocate from normal heap so that we can free this later. 654 auto *Saved = new (Context) DFIDeducedMismatchArgs; 655 Saved->FirstArg = Info.FirstArg; 656 Saved->SecondArg = Info.SecondArg; 657 Saved->TemplateArgs = Info.takeSugared(); 658 Saved->CallArgIndex = Info.CallArgIndex; 659 Result.Data = Saved; 660 break; 661 } 662 663 case Sema::TDK_NonDeducedMismatch: { 664 // FIXME: Should allocate from normal heap so that we can free this later. 665 DFIArguments *Saved = new (Context) DFIArguments; 666 Saved->FirstArg = Info.FirstArg; 667 Saved->SecondArg = Info.SecondArg; 668 Result.Data = Saved; 669 break; 670 } 671 672 case Sema::TDK_IncompletePack: 673 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 674 case Sema::TDK_Inconsistent: 675 case Sema::TDK_Underqualified: { 676 // FIXME: Should allocate from normal heap so that we can free this later. 677 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 678 Saved->Param = Info.Param; 679 Saved->FirstArg = Info.FirstArg; 680 Saved->SecondArg = Info.SecondArg; 681 Result.Data = Saved; 682 break; 683 } 684 685 case Sema::TDK_SubstitutionFailure: 686 Result.Data = Info.takeSugared(); 687 if (Info.hasSFINAEDiagnostic()) { 688 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 689 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 690 Info.takeSFINAEDiagnostic(*Diag); 691 Result.HasDiagnostic = true; 692 } 693 break; 694 695 case Sema::TDK_ConstraintsNotSatisfied: { 696 CNSInfo *Saved = new (Context) CNSInfo; 697 Saved->TemplateArgs = Info.takeSugared(); 698 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 699 Result.Data = Saved; 700 break; 701 } 702 703 case Sema::TDK_Success: 704 case Sema::TDK_NonDependentConversionFailure: 705 case Sema::TDK_AlreadyDiagnosed: 706 llvm_unreachable("not a deduction failure"); 707 } 708 709 return Result; 710 } 711 712 void DeductionFailureInfo::Destroy() { 713 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 714 case Sema::TDK_Success: 715 case Sema::TDK_Invalid: 716 case Sema::TDK_InstantiationDepth: 717 case Sema::TDK_Incomplete: 718 case Sema::TDK_TooManyArguments: 719 case Sema::TDK_TooFewArguments: 720 case Sema::TDK_InvalidExplicitArguments: 721 case Sema::TDK_CUDATargetMismatch: 722 case Sema::TDK_NonDependentConversionFailure: 723 break; 724 725 case Sema::TDK_IncompletePack: 726 case Sema::TDK_Inconsistent: 727 case Sema::TDK_Underqualified: 728 case Sema::TDK_DeducedMismatch: 729 case Sema::TDK_DeducedMismatchNested: 730 case Sema::TDK_NonDeducedMismatch: 731 // FIXME: Destroy the data? 732 Data = nullptr; 733 break; 734 735 case Sema::TDK_SubstitutionFailure: 736 // FIXME: Destroy the template argument list? 737 Data = nullptr; 738 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 739 Diag->~PartialDiagnosticAt(); 740 HasDiagnostic = false; 741 } 742 break; 743 744 case Sema::TDK_ConstraintsNotSatisfied: 745 // FIXME: Destroy the template argument list? 746 Data = nullptr; 747 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 748 Diag->~PartialDiagnosticAt(); 749 HasDiagnostic = false; 750 } 751 break; 752 753 // Unhandled 754 case Sema::TDK_MiscellaneousDeductionFailure: 755 case Sema::TDK_AlreadyDiagnosed: 756 break; 757 } 758 } 759 760 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 761 if (HasDiagnostic) 762 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 763 return nullptr; 764 } 765 766 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 767 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 768 case Sema::TDK_Success: 769 case Sema::TDK_Invalid: 770 case Sema::TDK_InstantiationDepth: 771 case Sema::TDK_TooManyArguments: 772 case Sema::TDK_TooFewArguments: 773 case Sema::TDK_SubstitutionFailure: 774 case Sema::TDK_DeducedMismatch: 775 case Sema::TDK_DeducedMismatchNested: 776 case Sema::TDK_NonDeducedMismatch: 777 case Sema::TDK_CUDATargetMismatch: 778 case Sema::TDK_NonDependentConversionFailure: 779 case Sema::TDK_ConstraintsNotSatisfied: 780 return TemplateParameter(); 781 782 case Sema::TDK_Incomplete: 783 case Sema::TDK_InvalidExplicitArguments: 784 return TemplateParameter::getFromOpaqueValue(Data); 785 786 case Sema::TDK_IncompletePack: 787 case Sema::TDK_Inconsistent: 788 case Sema::TDK_Underqualified: 789 return static_cast<DFIParamWithArguments*>(Data)->Param; 790 791 // Unhandled 792 case Sema::TDK_MiscellaneousDeductionFailure: 793 case Sema::TDK_AlreadyDiagnosed: 794 break; 795 } 796 797 return TemplateParameter(); 798 } 799 800 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 801 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 802 case Sema::TDK_Success: 803 case Sema::TDK_Invalid: 804 case Sema::TDK_InstantiationDepth: 805 case Sema::TDK_TooManyArguments: 806 case Sema::TDK_TooFewArguments: 807 case Sema::TDK_Incomplete: 808 case Sema::TDK_IncompletePack: 809 case Sema::TDK_InvalidExplicitArguments: 810 case Sema::TDK_Inconsistent: 811 case Sema::TDK_Underqualified: 812 case Sema::TDK_NonDeducedMismatch: 813 case Sema::TDK_CUDATargetMismatch: 814 case Sema::TDK_NonDependentConversionFailure: 815 return nullptr; 816 817 case Sema::TDK_DeducedMismatch: 818 case Sema::TDK_DeducedMismatchNested: 819 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 820 821 case Sema::TDK_SubstitutionFailure: 822 return static_cast<TemplateArgumentList*>(Data); 823 824 case Sema::TDK_ConstraintsNotSatisfied: 825 return static_cast<CNSInfo*>(Data)->TemplateArgs; 826 827 // Unhandled 828 case Sema::TDK_MiscellaneousDeductionFailure: 829 case Sema::TDK_AlreadyDiagnosed: 830 break; 831 } 832 833 return nullptr; 834 } 835 836 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 837 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 838 case Sema::TDK_Success: 839 case Sema::TDK_Invalid: 840 case Sema::TDK_InstantiationDepth: 841 case Sema::TDK_Incomplete: 842 case Sema::TDK_TooManyArguments: 843 case Sema::TDK_TooFewArguments: 844 case Sema::TDK_InvalidExplicitArguments: 845 case Sema::TDK_SubstitutionFailure: 846 case Sema::TDK_CUDATargetMismatch: 847 case Sema::TDK_NonDependentConversionFailure: 848 case Sema::TDK_ConstraintsNotSatisfied: 849 return nullptr; 850 851 case Sema::TDK_IncompletePack: 852 case Sema::TDK_Inconsistent: 853 case Sema::TDK_Underqualified: 854 case Sema::TDK_DeducedMismatch: 855 case Sema::TDK_DeducedMismatchNested: 856 case Sema::TDK_NonDeducedMismatch: 857 return &static_cast<DFIArguments*>(Data)->FirstArg; 858 859 // Unhandled 860 case Sema::TDK_MiscellaneousDeductionFailure: 861 case Sema::TDK_AlreadyDiagnosed: 862 break; 863 } 864 865 return nullptr; 866 } 867 868 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 869 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 870 case Sema::TDK_Success: 871 case Sema::TDK_Invalid: 872 case Sema::TDK_InstantiationDepth: 873 case Sema::TDK_Incomplete: 874 case Sema::TDK_IncompletePack: 875 case Sema::TDK_TooManyArguments: 876 case Sema::TDK_TooFewArguments: 877 case Sema::TDK_InvalidExplicitArguments: 878 case Sema::TDK_SubstitutionFailure: 879 case Sema::TDK_CUDATargetMismatch: 880 case Sema::TDK_NonDependentConversionFailure: 881 case Sema::TDK_ConstraintsNotSatisfied: 882 return nullptr; 883 884 case Sema::TDK_Inconsistent: 885 case Sema::TDK_Underqualified: 886 case Sema::TDK_DeducedMismatch: 887 case Sema::TDK_DeducedMismatchNested: 888 case Sema::TDK_NonDeducedMismatch: 889 return &static_cast<DFIArguments*>(Data)->SecondArg; 890 891 // Unhandled 892 case Sema::TDK_MiscellaneousDeductionFailure: 893 case Sema::TDK_AlreadyDiagnosed: 894 break; 895 } 896 897 return nullptr; 898 } 899 900 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 901 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 902 case Sema::TDK_DeducedMismatch: 903 case Sema::TDK_DeducedMismatchNested: 904 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 905 906 default: 907 return std::nullopt; 908 } 909 } 910 911 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, 912 const FunctionDecl *Y) { 913 if (!X || !Y) 914 return false; 915 if (X->getNumParams() != Y->getNumParams()) 916 return false; 917 // FIXME: when do rewritten comparison operators 918 // with explicit object parameters correspond? 919 // https://cplusplus.github.io/CWG/issues/2797.html 920 for (unsigned I = 0; I < X->getNumParams(); ++I) 921 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(), 922 Y->getParamDecl(I)->getType())) 923 return false; 924 if (auto *FTX = X->getDescribedFunctionTemplate()) { 925 auto *FTY = Y->getDescribedFunctionTemplate(); 926 if (!FTY) 927 return false; 928 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(), 929 FTY->getTemplateParameters())) 930 return false; 931 } 932 return true; 933 } 934 935 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, 936 Expr *FirstOperand, FunctionDecl *EqFD) { 937 assert(EqFD->getOverloadedOperator() == 938 OverloadedOperatorKind::OO_EqualEqual); 939 // C++2a [over.match.oper]p4: 940 // A non-template function or function template F named operator== is a 941 // rewrite target with first operand o unless a search for the name operator!= 942 // in the scope S from the instantiation context of the operator expression 943 // finds a function or function template that would correspond 944 // ([basic.scope.scope]) to F if its name were operator==, where S is the 945 // scope of the class type of o if F is a class member, and the namespace 946 // scope of which F is a member otherwise. A function template specialization 947 // named operator== is a rewrite target if its function template is a rewrite 948 // target. 949 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName( 950 OverloadedOperatorKind::OO_ExclaimEqual); 951 if (isa<CXXMethodDecl>(EqFD)) { 952 // If F is a class member, search scope is class type of first operand. 953 QualType RHS = FirstOperand->getType(); 954 auto *RHSRec = RHS->getAs<RecordType>(); 955 if (!RHSRec) 956 return true; 957 LookupResult Members(S, NotEqOp, OpLoc, 958 Sema::LookupNameKind::LookupMemberName); 959 S.LookupQualifiedName(Members, RHSRec->getDecl()); 960 Members.suppressAccessDiagnostics(); 961 for (NamedDecl *Op : Members) 962 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction())) 963 return false; 964 return true; 965 } 966 // Otherwise the search scope is the namespace scope of which F is a member. 967 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) { 968 auto *NotEqFD = Op->getAsFunction(); 969 if (auto *UD = dyn_cast<UsingShadowDecl>(Op)) 970 NotEqFD = UD->getUnderlyingDecl()->getAsFunction(); 971 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) && 972 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()), 973 cast<Decl>(Op->getLexicalDeclContext()))) 974 return false; 975 } 976 return true; 977 } 978 979 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed( 980 OverloadedOperatorKind Op) { 981 if (!AllowRewrittenCandidates) 982 return false; 983 return Op == OO_EqualEqual || Op == OO_Spaceship; 984 } 985 986 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 987 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) { 988 auto Op = FD->getOverloadedOperator(); 989 if (!allowsReversed(Op)) 990 return false; 991 if (Op == OverloadedOperatorKind::OO_EqualEqual) { 992 assert(OriginalArgs.size() == 2); 993 if (!shouldAddReversedEqEq( 994 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD)) 995 return false; 996 } 997 // Don't bother adding a reversed candidate that can never be a better 998 // match than the non-reversed version. 999 return FD->getNumNonObjectParams() != 2 || 1000 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 1001 FD->getParamDecl(1)->getType()) || 1002 FD->hasAttr<EnableIfAttr>(); 1003 } 1004 1005 void OverloadCandidateSet::destroyCandidates() { 1006 for (iterator i = begin(), e = end(); i != e; ++i) { 1007 for (auto &C : i->Conversions) 1008 C.~ImplicitConversionSequence(); 1009 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 1010 i->DeductionFailure.Destroy(); 1011 } 1012 } 1013 1014 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 1015 destroyCandidates(); 1016 SlabAllocator.Reset(); 1017 NumInlineBytesUsed = 0; 1018 Candidates.clear(); 1019 Functions.clear(); 1020 Kind = CSK; 1021 } 1022 1023 namespace { 1024 class UnbridgedCastsSet { 1025 struct Entry { 1026 Expr **Addr; 1027 Expr *Saved; 1028 }; 1029 SmallVector<Entry, 2> Entries; 1030 1031 public: 1032 void save(Sema &S, Expr *&E) { 1033 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 1034 Entry entry = { &E, E }; 1035 Entries.push_back(entry); 1036 E = S.stripARCUnbridgedCast(E); 1037 } 1038 1039 void restore() { 1040 for (SmallVectorImpl<Entry>::iterator 1041 i = Entries.begin(), e = Entries.end(); i != e; ++i) 1042 *i->Addr = i->Saved; 1043 } 1044 }; 1045 } 1046 1047 /// checkPlaceholderForOverload - Do any interesting placeholder-like 1048 /// preprocessing on the given expression. 1049 /// 1050 /// \param unbridgedCasts a collection to which to add unbridged casts; 1051 /// without this, they will be immediately diagnosed as errors 1052 /// 1053 /// Return true on unrecoverable error. 1054 static bool 1055 checkPlaceholderForOverload(Sema &S, Expr *&E, 1056 UnbridgedCastsSet *unbridgedCasts = nullptr) { 1057 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 1058 // We can't handle overloaded expressions here because overload 1059 // resolution might reasonably tweak them. 1060 if (placeholder->getKind() == BuiltinType::Overload) return false; 1061 1062 // If the context potentially accepts unbridged ARC casts, strip 1063 // the unbridged cast and add it to the collection for later restoration. 1064 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 1065 unbridgedCasts) { 1066 unbridgedCasts->save(S, E); 1067 return false; 1068 } 1069 1070 // Go ahead and check everything else. 1071 ExprResult result = S.CheckPlaceholderExpr(E); 1072 if (result.isInvalid()) 1073 return true; 1074 1075 E = result.get(); 1076 return false; 1077 } 1078 1079 // Nothing to do. 1080 return false; 1081 } 1082 1083 /// checkArgPlaceholdersForOverload - Check a set of call operands for 1084 /// placeholders. 1085 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 1086 UnbridgedCastsSet &unbridged) { 1087 for (unsigned i = 0, e = Args.size(); i != e; ++i) 1088 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 1089 return true; 1090 1091 return false; 1092 } 1093 1094 /// Determine whether the given New declaration is an overload of the 1095 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 1096 /// New and Old cannot be overloaded, e.g., if New has the same signature as 1097 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 1098 /// functions (or function templates) at all. When it does return Ovl_Match or 1099 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1100 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1101 /// declaration. 1102 /// 1103 /// Example: Given the following input: 1104 /// 1105 /// void f(int, float); // #1 1106 /// void f(int, int); // #2 1107 /// int f(int, int); // #3 1108 /// 1109 /// When we process #1, there is no previous declaration of "f", so IsOverload 1110 /// will not be used. 1111 /// 1112 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1113 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1114 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1115 /// unchanged. 1116 /// 1117 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1118 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1119 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1120 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1121 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1122 /// 1123 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1124 /// by a using declaration. The rules for whether to hide shadow declarations 1125 /// ignore some properties which otherwise figure into a function template's 1126 /// signature. 1127 Sema::OverloadKind 1128 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1129 NamedDecl *&Match, bool NewIsUsingDecl) { 1130 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1131 I != E; ++I) { 1132 NamedDecl *OldD = *I; 1133 1134 bool OldIsUsingDecl = false; 1135 if (isa<UsingShadowDecl>(OldD)) { 1136 OldIsUsingDecl = true; 1137 1138 // We can always introduce two using declarations into the same 1139 // context, even if they have identical signatures. 1140 if (NewIsUsingDecl) continue; 1141 1142 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1143 } 1144 1145 // A using-declaration does not conflict with another declaration 1146 // if one of them is hidden. 1147 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1148 continue; 1149 1150 // If either declaration was introduced by a using declaration, 1151 // we'll need to use slightly different rules for matching. 1152 // Essentially, these rules are the normal rules, except that 1153 // function templates hide function templates with different 1154 // return types or template parameter lists. 1155 bool UseMemberUsingDeclRules = 1156 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1157 !New->getFriendObjectKind(); 1158 1159 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1160 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1161 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1162 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1163 continue; 1164 } 1165 1166 if (!isa<FunctionTemplateDecl>(OldD) && 1167 !shouldLinkPossiblyHiddenDecl(*I, New)) 1168 continue; 1169 1170 Match = *I; 1171 return Ovl_Match; 1172 } 1173 1174 // Builtins that have custom typechecking or have a reference should 1175 // not be overloadable or redeclarable. 1176 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1177 Match = *I; 1178 return Ovl_NonFunction; 1179 } 1180 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1181 // We can overload with these, which can show up when doing 1182 // redeclaration checks for UsingDecls. 1183 assert(Old.getLookupKind() == LookupUsingDeclName); 1184 } else if (isa<TagDecl>(OldD)) { 1185 // We can always overload with tags by hiding them. 1186 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1187 // Optimistically assume that an unresolved using decl will 1188 // overload; if it doesn't, we'll have to diagnose during 1189 // template instantiation. 1190 // 1191 // Exception: if the scope is dependent and this is not a class 1192 // member, the using declaration can only introduce an enumerator. 1193 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1194 Match = *I; 1195 return Ovl_NonFunction; 1196 } 1197 } else { 1198 // (C++ 13p1): 1199 // Only function declarations can be overloaded; object and type 1200 // declarations cannot be overloaded. 1201 Match = *I; 1202 return Ovl_NonFunction; 1203 } 1204 } 1205 1206 // C++ [temp.friend]p1: 1207 // For a friend function declaration that is not a template declaration: 1208 // -- if the name of the friend is a qualified or unqualified template-id, 1209 // [...], otherwise 1210 // -- if the name of the friend is a qualified-id and a matching 1211 // non-template function is found in the specified class or namespace, 1212 // the friend declaration refers to that function, otherwise, 1213 // -- if the name of the friend is a qualified-id and a matching function 1214 // template is found in the specified class or namespace, the friend 1215 // declaration refers to the deduced specialization of that function 1216 // template, otherwise 1217 // -- the name shall be an unqualified-id [...] 1218 // If we get here for a qualified friend declaration, we've just reached the 1219 // third bullet. If the type of the friend is dependent, skip this lookup 1220 // until instantiation. 1221 if (New->getFriendObjectKind() && New->getQualifier() && 1222 !New->getDescribedFunctionTemplate() && 1223 !New->getDependentSpecializationInfo() && 1224 !New->getType()->isDependentType()) { 1225 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1226 TemplateSpecResult.addAllDecls(Old); 1227 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1228 /*QualifiedFriend*/true)) { 1229 New->setInvalidDecl(); 1230 return Ovl_Overload; 1231 } 1232 1233 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1234 return Ovl_Match; 1235 } 1236 1237 return Ovl_Overload; 1238 } 1239 1240 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, 1241 FunctionDecl *Old, 1242 bool UseMemberUsingDeclRules, 1243 bool ConsiderCudaAttrs, 1244 bool UseOverrideRules = false) { 1245 // C++ [basic.start.main]p2: This function shall not be overloaded. 1246 if (New->isMain()) 1247 return false; 1248 1249 // MSVCRT user defined entry points cannot be overloaded. 1250 if (New->isMSVCRTEntryPoint()) 1251 return false; 1252 1253 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1254 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1255 1256 // C++ [temp.fct]p2: 1257 // A function template can be overloaded with other function templates 1258 // and with normal (non-template) functions. 1259 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1260 return true; 1261 1262 // Is the function New an overload of the function Old? 1263 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType()); 1264 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType()); 1265 1266 // Compare the signatures (C++ 1.3.10) of the two functions to 1267 // determine whether they are overloads. If we find any mismatch 1268 // in the signature, they are overloads. 1269 1270 // If either of these functions is a K&R-style function (no 1271 // prototype), then we consider them to have matching signatures. 1272 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1273 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1274 return false; 1275 1276 const auto *OldType = cast<FunctionProtoType>(OldQType); 1277 const auto *NewType = cast<FunctionProtoType>(NewQType); 1278 1279 // The signature of a function includes the types of its 1280 // parameters (C++ 1.3.10), which includes the presence or absence 1281 // of the ellipsis; see C++ DR 357). 1282 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic()) 1283 return true; 1284 1285 // For member-like friends, the enclosing class is part of the signature. 1286 if ((New->isMemberLikeConstrainedFriend() || 1287 Old->isMemberLikeConstrainedFriend()) && 1288 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext())) 1289 return true; 1290 1291 // Compare the parameter lists. 1292 // This can only be done once we have establish that friend functions 1293 // inhabit the same context, otherwise we might tried to instantiate 1294 // references to non-instantiated entities during constraint substitution. 1295 // GH78101. 1296 if (NewTemplate) { 1297 // C++ [temp.over.link]p4: 1298 // The signature of a function template consists of its function 1299 // signature, its return type and its template parameter list. The names 1300 // of the template parameters are significant only for establishing the 1301 // relationship between the template parameters and the rest of the 1302 // signature. 1303 // 1304 // We check the return type and template parameter lists for function 1305 // templates first; the remaining checks follow. 1306 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual( 1307 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate, 1308 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch); 1309 bool SameReturnType = SemaRef.Context.hasSameType( 1310 Old->getDeclaredReturnType(), New->getDeclaredReturnType()); 1311 // FIXME(GH58571): Match template parameter list even for non-constrained 1312 // template heads. This currently ensures that the code prior to C++20 is 1313 // not newly broken. 1314 bool ConstraintsInTemplateHead = 1315 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() || 1316 OldTemplate->getTemplateParameters()->hasAssociatedConstraints(); 1317 // C++ [namespace.udecl]p11: 1318 // The set of declarations named by a using-declarator that inhabits a 1319 // class C does not include member functions and member function 1320 // templates of a base class that "correspond" to (and thus would 1321 // conflict with) a declaration of a function or function template in 1322 // C. 1323 // Comparing return types is not required for the "correspond" check to 1324 // decide whether a member introduced by a shadow declaration is hidden. 1325 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead && 1326 !SameTemplateParameterList) 1327 return true; 1328 if (!UseMemberUsingDeclRules && 1329 (!SameTemplateParameterList || !SameReturnType)) 1330 return true; 1331 } 1332 1333 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1334 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New); 1335 1336 int OldParamsOffset = 0; 1337 int NewParamsOffset = 0; 1338 1339 // When determining if a method is an overload from a base class, act as if 1340 // the implicit object parameter are of the same type. 1341 1342 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) { 1343 if (M->isExplicitObjectMemberFunction()) 1344 return Q; 1345 1346 // We do not allow overloading based off of '__restrict'. 1347 Q.removeRestrict(); 1348 1349 // We may not have applied the implicit const for a constexpr member 1350 // function yet (because we haven't yet resolved whether this is a static 1351 // or non-static member function). Add it now, on the assumption that this 1352 // is a redeclaration of OldMethod. 1353 if (!SemaRef.getLangOpts().CPlusPlus14 && 1354 (M->isConstexpr() || M->isConsteval()) && 1355 !isa<CXXConstructorDecl>(NewMethod)) 1356 Q.addConst(); 1357 return Q; 1358 }; 1359 1360 auto CompareType = [&](QualType Base, QualType D) { 1361 auto BS = Base.getNonReferenceType().getCanonicalType().split(); 1362 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals); 1363 1364 auto DS = D.getNonReferenceType().getCanonicalType().split(); 1365 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals); 1366 1367 if (BS.Quals != DS.Quals) 1368 return false; 1369 1370 if (OldMethod->isImplicitObjectMemberFunction() && 1371 OldMethod->getParent() != NewMethod->getParent()) { 1372 QualType ParentType = 1373 SemaRef.Context.getTypeDeclType(OldMethod->getParent()) 1374 .getCanonicalType(); 1375 if (ParentType.getTypePtr() != BS.Ty) 1376 return false; 1377 BS.Ty = DS.Ty; 1378 } 1379 1380 // FIXME: should we ignore some type attributes here? 1381 if (BS.Ty != DS.Ty) 1382 return false; 1383 1384 if (Base->isLValueReferenceType()) 1385 return D->isLValueReferenceType(); 1386 return Base->isRValueReferenceType() == D->isRValueReferenceType(); 1387 }; 1388 1389 // If the function is a class member, its signature includes the 1390 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1391 auto DiagnoseInconsistentRefQualifiers = [&]() { 1392 if (SemaRef.LangOpts.CPlusPlus23) 1393 return false; 1394 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier()) 1395 return false; 1396 if (OldMethod->isExplicitObjectMemberFunction() || 1397 NewMethod->isExplicitObjectMemberFunction()) 1398 return false; 1399 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None || 1400 NewMethod->getRefQualifier() == RQ_None)) { 1401 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1402 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1403 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1404 return true; 1405 } 1406 return false; 1407 }; 1408 1409 if (OldMethod && OldMethod->isExplicitObjectMemberFunction()) 1410 OldParamsOffset++; 1411 if (NewMethod && NewMethod->isExplicitObjectMemberFunction()) 1412 NewParamsOffset++; 1413 1414 if (OldType->getNumParams() - OldParamsOffset != 1415 NewType->getNumParams() - NewParamsOffset || 1416 !SemaRef.FunctionParamTypesAreEqual( 1417 {OldType->param_type_begin() + OldParamsOffset, 1418 OldType->param_type_end()}, 1419 {NewType->param_type_begin() + NewParamsOffset, 1420 NewType->param_type_end()}, 1421 nullptr)) { 1422 return true; 1423 } 1424 1425 if (OldMethod && NewMethod && !OldMethod->isStatic() && 1426 !OldMethod->isStatic()) { 1427 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old, 1428 const CXXMethodDecl *New) { 1429 auto NewObjectType = New->getFunctionObjectParameterReferenceType(); 1430 auto OldObjectType = Old->getFunctionObjectParameterReferenceType(); 1431 1432 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) { 1433 return F->getRefQualifier() == RQ_None && 1434 !F->isExplicitObjectMemberFunction(); 1435 }; 1436 1437 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) && 1438 CompareType(OldObjectType.getNonReferenceType(), 1439 NewObjectType.getNonReferenceType())) 1440 return true; 1441 return CompareType(OldObjectType, NewObjectType); 1442 }(OldMethod, NewMethod); 1443 1444 if (!HaveCorrespondingObjectParameters) { 1445 if (DiagnoseInconsistentRefQualifiers()) 1446 return true; 1447 // CWG2554 1448 // and, if at least one is an explicit object member function, ignoring 1449 // object parameters 1450 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() && 1451 !OldMethod->isExplicitObjectMemberFunction())) 1452 return true; 1453 } 1454 } 1455 1456 if (!UseOverrideRules) { 1457 Expr *NewRC = New->getTrailingRequiresClause(), 1458 *OldRC = Old->getTrailingRequiresClause(); 1459 if ((NewRC != nullptr) != (OldRC != nullptr)) 1460 return true; 1461 1462 if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC)) 1463 return true; 1464 } 1465 1466 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() && 1467 NewMethod->isImplicitObjectMemberFunction()) { 1468 if (DiagnoseInconsistentRefQualifiers()) 1469 return true; 1470 } 1471 1472 // Though pass_object_size is placed on parameters and takes an argument, we 1473 // consider it to be a function-level modifier for the sake of function 1474 // identity. Either the function has one or more parameters with 1475 // pass_object_size or it doesn't. 1476 if (functionHasPassObjectSizeParams(New) != 1477 functionHasPassObjectSizeParams(Old)) 1478 return true; 1479 1480 // enable_if attributes are an order-sensitive part of the signature. 1481 for (specific_attr_iterator<EnableIfAttr> 1482 NewI = New->specific_attr_begin<EnableIfAttr>(), 1483 NewE = New->specific_attr_end<EnableIfAttr>(), 1484 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1485 OldE = Old->specific_attr_end<EnableIfAttr>(); 1486 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1487 if (NewI == NewE || OldI == OldE) 1488 return true; 1489 llvm::FoldingSetNodeID NewID, OldID; 1490 NewI->getCond()->Profile(NewID, SemaRef.Context, true); 1491 OldI->getCond()->Profile(OldID, SemaRef.Context, true); 1492 if (NewID != OldID) 1493 return true; 1494 } 1495 1496 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) { 1497 // Don't allow overloading of destructors. (In theory we could, but it 1498 // would be a giant change to clang.) 1499 if (!isa<CXXDestructorDecl>(New)) { 1500 Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(New), 1501 OldTarget = SemaRef.IdentifyCUDATarget(Old); 1502 if (NewTarget != Sema::CFT_InvalidTarget) { 1503 assert((OldTarget != Sema::CFT_InvalidTarget) && 1504 "Unexpected invalid target."); 1505 1506 // Allow overloading of functions with same signature and different CUDA 1507 // target attributes. 1508 if (NewTarget != OldTarget) 1509 return true; 1510 } 1511 } 1512 } 1513 1514 // The signatures match; this is not an overload. 1515 return false; 1516 } 1517 1518 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1519 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1520 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules, 1521 ConsiderCudaAttrs); 1522 } 1523 1524 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, 1525 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1526 return IsOverloadOrOverrideImpl(*this, MD, BaseMD, 1527 /*UseMemberUsingDeclRules=*/false, 1528 /*ConsiderCudaAttrs=*/true, 1529 /*UseOverrideRules=*/true); 1530 } 1531 1532 /// Tries a user-defined conversion from From to ToType. 1533 /// 1534 /// Produces an implicit conversion sequence for when a standard conversion 1535 /// is not an option. See TryImplicitConversion for more information. 1536 static ImplicitConversionSequence 1537 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1538 bool SuppressUserConversions, 1539 AllowedExplicit AllowExplicit, 1540 bool InOverloadResolution, 1541 bool CStyle, 1542 bool AllowObjCWritebackConversion, 1543 bool AllowObjCConversionOnExplicit) { 1544 ImplicitConversionSequence ICS; 1545 1546 if (SuppressUserConversions) { 1547 // We're not in the case above, so there is no conversion that 1548 // we can perform. 1549 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1550 return ICS; 1551 } 1552 1553 // Attempt user-defined conversion. 1554 OverloadCandidateSet Conversions(From->getExprLoc(), 1555 OverloadCandidateSet::CSK_Normal); 1556 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1557 Conversions, AllowExplicit, 1558 AllowObjCConversionOnExplicit)) { 1559 case OR_Success: 1560 case OR_Deleted: 1561 ICS.setUserDefined(); 1562 // C++ [over.ics.user]p4: 1563 // A conversion of an expression of class type to the same class 1564 // type is given Exact Match rank, and a conversion of an 1565 // expression of class type to a base class of that type is 1566 // given Conversion rank, in spite of the fact that a copy 1567 // constructor (i.e., a user-defined conversion function) is 1568 // called for those cases. 1569 if (CXXConstructorDecl *Constructor 1570 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1571 QualType FromCanon 1572 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1573 QualType ToCanon 1574 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1575 if (Constructor->isCopyConstructor() && 1576 (FromCanon == ToCanon || 1577 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1578 // Turn this into a "standard" conversion sequence, so that it 1579 // gets ranked with standard conversion sequences. 1580 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1581 ICS.setStandard(); 1582 ICS.Standard.setAsIdentityConversion(); 1583 ICS.Standard.setFromType(From->getType()); 1584 ICS.Standard.setAllToTypes(ToType); 1585 ICS.Standard.CopyConstructor = Constructor; 1586 ICS.Standard.FoundCopyConstructor = Found; 1587 if (ToCanon != FromCanon) 1588 ICS.Standard.Second = ICK_Derived_To_Base; 1589 } 1590 } 1591 break; 1592 1593 case OR_Ambiguous: 1594 ICS.setAmbiguous(); 1595 ICS.Ambiguous.setFromType(From->getType()); 1596 ICS.Ambiguous.setToType(ToType); 1597 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1598 Cand != Conversions.end(); ++Cand) 1599 if (Cand->Best) 1600 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1601 break; 1602 1603 // Fall through. 1604 case OR_No_Viable_Function: 1605 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1606 break; 1607 } 1608 1609 return ICS; 1610 } 1611 1612 /// TryImplicitConversion - Attempt to perform an implicit conversion 1613 /// from the given expression (Expr) to the given type (ToType). This 1614 /// function returns an implicit conversion sequence that can be used 1615 /// to perform the initialization. Given 1616 /// 1617 /// void f(float f); 1618 /// void g(int i) { f(i); } 1619 /// 1620 /// this routine would produce an implicit conversion sequence to 1621 /// describe the initialization of f from i, which will be a standard 1622 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1623 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1624 // 1625 /// Note that this routine only determines how the conversion can be 1626 /// performed; it does not actually perform the conversion. As such, 1627 /// it will not produce any diagnostics if no conversion is available, 1628 /// but will instead return an implicit conversion sequence of kind 1629 /// "BadConversion". 1630 /// 1631 /// If @p SuppressUserConversions, then user-defined conversions are 1632 /// not permitted. 1633 /// If @p AllowExplicit, then explicit user-defined conversions are 1634 /// permitted. 1635 /// 1636 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1637 /// writeback conversion, which allows __autoreleasing id* parameters to 1638 /// be initialized with __strong id* or __weak id* arguments. 1639 static ImplicitConversionSequence 1640 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1641 bool SuppressUserConversions, 1642 AllowedExplicit AllowExplicit, 1643 bool InOverloadResolution, 1644 bool CStyle, 1645 bool AllowObjCWritebackConversion, 1646 bool AllowObjCConversionOnExplicit) { 1647 ImplicitConversionSequence ICS; 1648 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1649 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1650 ICS.setStandard(); 1651 return ICS; 1652 } 1653 1654 if (!S.getLangOpts().CPlusPlus) { 1655 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1656 return ICS; 1657 } 1658 1659 // C++ [over.ics.user]p4: 1660 // A conversion of an expression of class type to the same class 1661 // type is given Exact Match rank, and a conversion of an 1662 // expression of class type to a base class of that type is 1663 // given Conversion rank, in spite of the fact that a copy/move 1664 // constructor (i.e., a user-defined conversion function) is 1665 // called for those cases. 1666 QualType FromType = From->getType(); 1667 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1668 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1669 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1670 ICS.setStandard(); 1671 ICS.Standard.setAsIdentityConversion(); 1672 ICS.Standard.setFromType(FromType); 1673 ICS.Standard.setAllToTypes(ToType); 1674 1675 // We don't actually check at this point whether there is a valid 1676 // copy/move constructor, since overloading just assumes that it 1677 // exists. When we actually perform initialization, we'll find the 1678 // appropriate constructor to copy the returned object, if needed. 1679 ICS.Standard.CopyConstructor = nullptr; 1680 1681 // Determine whether this is considered a derived-to-base conversion. 1682 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1683 ICS.Standard.Second = ICK_Derived_To_Base; 1684 1685 return ICS; 1686 } 1687 1688 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1689 AllowExplicit, InOverloadResolution, CStyle, 1690 AllowObjCWritebackConversion, 1691 AllowObjCConversionOnExplicit); 1692 } 1693 1694 ImplicitConversionSequence 1695 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1696 bool SuppressUserConversions, 1697 AllowedExplicit AllowExplicit, 1698 bool InOverloadResolution, 1699 bool CStyle, 1700 bool AllowObjCWritebackConversion) { 1701 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1702 AllowExplicit, InOverloadResolution, CStyle, 1703 AllowObjCWritebackConversion, 1704 /*AllowObjCConversionOnExplicit=*/false); 1705 } 1706 1707 /// PerformImplicitConversion - Perform an implicit conversion of the 1708 /// expression From to the type ToType. Returns the 1709 /// converted expression. Flavor is the kind of conversion we're 1710 /// performing, used in the error message. If @p AllowExplicit, 1711 /// explicit user-defined conversions are permitted. 1712 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1713 AssignmentAction Action, 1714 bool AllowExplicit) { 1715 if (checkPlaceholderForOverload(*this, From)) 1716 return ExprError(); 1717 1718 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1719 bool AllowObjCWritebackConversion 1720 = getLangOpts().ObjCAutoRefCount && 1721 (Action == AA_Passing || Action == AA_Sending); 1722 if (getLangOpts().ObjC) 1723 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1724 From->getType(), From); 1725 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1726 *this, From, ToType, 1727 /*SuppressUserConversions=*/false, 1728 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1729 /*InOverloadResolution=*/false, 1730 /*CStyle=*/false, AllowObjCWritebackConversion, 1731 /*AllowObjCConversionOnExplicit=*/false); 1732 return PerformImplicitConversion(From, ToType, ICS, Action); 1733 } 1734 1735 /// Determine whether the conversion from FromType to ToType is a valid 1736 /// conversion that strips "noexcept" or "noreturn" off the nested function 1737 /// type. 1738 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1739 QualType &ResultTy) { 1740 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1741 return false; 1742 1743 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1744 // or F(t noexcept) -> F(t) 1745 // where F adds one of the following at most once: 1746 // - a pointer 1747 // - a member pointer 1748 // - a block pointer 1749 // Changes here need matching changes in FindCompositePointerType. 1750 CanQualType CanTo = Context.getCanonicalType(ToType); 1751 CanQualType CanFrom = Context.getCanonicalType(FromType); 1752 Type::TypeClass TyClass = CanTo->getTypeClass(); 1753 if (TyClass != CanFrom->getTypeClass()) return false; 1754 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1755 if (TyClass == Type::Pointer) { 1756 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1757 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1758 } else if (TyClass == Type::BlockPointer) { 1759 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1760 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1761 } else if (TyClass == Type::MemberPointer) { 1762 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1763 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1764 // A function pointer conversion cannot change the class of the function. 1765 if (ToMPT->getClass() != FromMPT->getClass()) 1766 return false; 1767 CanTo = ToMPT->getPointeeType(); 1768 CanFrom = FromMPT->getPointeeType(); 1769 } else { 1770 return false; 1771 } 1772 1773 TyClass = CanTo->getTypeClass(); 1774 if (TyClass != CanFrom->getTypeClass()) return false; 1775 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1776 return false; 1777 } 1778 1779 const auto *FromFn = cast<FunctionType>(CanFrom); 1780 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1781 1782 const auto *ToFn = cast<FunctionType>(CanTo); 1783 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1784 1785 bool Changed = false; 1786 1787 // Drop 'noreturn' if not present in target type. 1788 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1789 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1790 Changed = true; 1791 } 1792 1793 // Drop 'noexcept' if not present in target type. 1794 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1795 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1796 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1797 FromFn = cast<FunctionType>( 1798 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1799 EST_None) 1800 .getTypePtr()); 1801 Changed = true; 1802 } 1803 1804 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1805 // only if the ExtParameterInfo lists of the two function prototypes can be 1806 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1807 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1808 bool CanUseToFPT, CanUseFromFPT; 1809 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1810 CanUseFromFPT, NewParamInfos) && 1811 CanUseToFPT && !CanUseFromFPT) { 1812 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1813 ExtInfo.ExtParameterInfos = 1814 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1815 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1816 FromFPT->getParamTypes(), ExtInfo); 1817 FromFn = QT->getAs<FunctionType>(); 1818 Changed = true; 1819 } 1820 } 1821 1822 if (!Changed) 1823 return false; 1824 1825 assert(QualType(FromFn, 0).isCanonical()); 1826 if (QualType(FromFn, 0) != CanTo) return false; 1827 1828 ResultTy = ToType; 1829 return true; 1830 } 1831 1832 /// Determine whether the conversion from FromType to ToType is a valid 1833 /// vector conversion. 1834 /// 1835 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1836 /// conversion. 1837 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, 1838 ImplicitConversionKind &ICK, Expr *From, 1839 bool InOverloadResolution, bool CStyle) { 1840 // We need at least one of these types to be a vector type to have a vector 1841 // conversion. 1842 if (!ToType->isVectorType() && !FromType->isVectorType()) 1843 return false; 1844 1845 // Identical types require no conversions. 1846 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1847 return false; 1848 1849 // There are no conversions between extended vector types, only identity. 1850 if (ToType->isExtVectorType()) { 1851 // There are no conversions between extended vector types other than the 1852 // identity conversion. 1853 if (FromType->isExtVectorType()) 1854 return false; 1855 1856 // Vector splat from any arithmetic type to a vector. 1857 if (FromType->isArithmeticType()) { 1858 ICK = ICK_Vector_Splat; 1859 return true; 1860 } 1861 } 1862 1863 if (ToType->isSVESizelessBuiltinType() || 1864 FromType->isSVESizelessBuiltinType()) 1865 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1866 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1867 ICK = ICK_SVE_Vector_Conversion; 1868 return true; 1869 } 1870 1871 if (ToType->isRVVSizelessBuiltinType() || 1872 FromType->isRVVSizelessBuiltinType()) 1873 if (S.Context.areCompatibleRVVTypes(FromType, ToType) || 1874 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) { 1875 ICK = ICK_RVV_Vector_Conversion; 1876 return true; 1877 } 1878 1879 // We can perform the conversion between vector types in the following cases: 1880 // 1)vector types are equivalent AltiVec and GCC vector types 1881 // 2)lax vector conversions are permitted and the vector types are of the 1882 // same size 1883 // 3)the destination type does not have the ARM MVE strict-polymorphism 1884 // attribute, which inhibits lax vector conversion for overload resolution 1885 // only 1886 if (ToType->isVectorType() && FromType->isVectorType()) { 1887 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1888 (S.isLaxVectorConversion(FromType, ToType) && 1889 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1890 if (S.getASTContext().getTargetInfo().getTriple().isPPC() && 1891 S.isLaxVectorConversion(FromType, ToType) && 1892 S.anyAltivecTypes(FromType, ToType) && 1893 !S.Context.areCompatibleVectorTypes(FromType, ToType) && 1894 !InOverloadResolution && !CStyle) { 1895 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) 1896 << FromType << ToType; 1897 } 1898 ICK = ICK_Vector_Conversion; 1899 return true; 1900 } 1901 } 1902 1903 return false; 1904 } 1905 1906 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1907 bool InOverloadResolution, 1908 StandardConversionSequence &SCS, 1909 bool CStyle); 1910 1911 /// IsStandardConversion - Determines whether there is a standard 1912 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1913 /// expression From to the type ToType. Standard conversion sequences 1914 /// only consider non-class types; for conversions that involve class 1915 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1916 /// contain the standard conversion sequence required to perform this 1917 /// conversion and this routine will return true. Otherwise, this 1918 /// routine will return false and the value of SCS is unspecified. 1919 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1920 bool InOverloadResolution, 1921 StandardConversionSequence &SCS, 1922 bool CStyle, 1923 bool AllowObjCWritebackConversion) { 1924 QualType FromType = From->getType(); 1925 1926 // Standard conversions (C++ [conv]) 1927 SCS.setAsIdentityConversion(); 1928 SCS.IncompatibleObjC = false; 1929 SCS.setFromType(FromType); 1930 SCS.CopyConstructor = nullptr; 1931 1932 // There are no standard conversions for class types in C++, so 1933 // abort early. When overloading in C, however, we do permit them. 1934 if (S.getLangOpts().CPlusPlus && 1935 (FromType->isRecordType() || ToType->isRecordType())) 1936 return false; 1937 1938 // The first conversion can be an lvalue-to-rvalue conversion, 1939 // array-to-pointer conversion, or function-to-pointer conversion 1940 // (C++ 4p1). 1941 1942 if (FromType == S.Context.OverloadTy) { 1943 DeclAccessPair AccessPair; 1944 if (FunctionDecl *Fn 1945 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1946 AccessPair)) { 1947 // We were able to resolve the address of the overloaded function, 1948 // so we can convert to the type of that function. 1949 FromType = Fn->getType(); 1950 SCS.setFromType(FromType); 1951 1952 // we can sometimes resolve &foo<int> regardless of ToType, so check 1953 // if the type matches (identity) or we are converting to bool 1954 if (!S.Context.hasSameUnqualifiedType( 1955 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1956 QualType resultTy; 1957 // if the function type matches except for [[noreturn]], it's ok 1958 if (!S.IsFunctionConversion(FromType, 1959 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1960 // otherwise, only a boolean conversion is standard 1961 if (!ToType->isBooleanType()) 1962 return false; 1963 } 1964 1965 // Check if the "from" expression is taking the address of an overloaded 1966 // function and recompute the FromType accordingly. Take advantage of the 1967 // fact that non-static member functions *must* have such an address-of 1968 // expression. 1969 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1970 if (Method && !Method->isStatic() && 1971 !Method->isExplicitObjectMemberFunction()) { 1972 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1973 "Non-unary operator on non-static member address"); 1974 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1975 == UO_AddrOf && 1976 "Non-address-of operator on non-static member address"); 1977 const Type *ClassType 1978 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1979 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1980 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1981 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1982 UO_AddrOf && 1983 "Non-address-of operator for overloaded function expression"); 1984 FromType = S.Context.getPointerType(FromType); 1985 } 1986 } else { 1987 return false; 1988 } 1989 } 1990 // Lvalue-to-rvalue conversion (C++11 4.1): 1991 // A glvalue (3.10) of a non-function, non-array type T can 1992 // be converted to a prvalue. 1993 bool argIsLValue = From->isGLValue(); 1994 if (argIsLValue && 1995 !FromType->isFunctionType() && !FromType->isArrayType() && 1996 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1997 SCS.First = ICK_Lvalue_To_Rvalue; 1998 1999 // C11 6.3.2.1p2: 2000 // ... if the lvalue has atomic type, the value has the non-atomic version 2001 // of the type of the lvalue ... 2002 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 2003 FromType = Atomic->getValueType(); 2004 2005 // If T is a non-class type, the type of the rvalue is the 2006 // cv-unqualified version of T. Otherwise, the type of the rvalue 2007 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 2008 // just strip the qualifiers because they don't matter. 2009 FromType = FromType.getUnqualifiedType(); 2010 } else if (FromType->isArrayType()) { 2011 // Array-to-pointer conversion (C++ 4.2) 2012 SCS.First = ICK_Array_To_Pointer; 2013 2014 // An lvalue or rvalue of type "array of N T" or "array of unknown 2015 // bound of T" can be converted to an rvalue of type "pointer to 2016 // T" (C++ 4.2p1). 2017 FromType = S.Context.getArrayDecayedType(FromType); 2018 2019 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 2020 // This conversion is deprecated in C++03 (D.4) 2021 SCS.DeprecatedStringLiteralToCharPtr = true; 2022 2023 // For the purpose of ranking in overload resolution 2024 // (13.3.3.1.1), this conversion is considered an 2025 // array-to-pointer conversion followed by a qualification 2026 // conversion (4.4). (C++ 4.2p2) 2027 SCS.Second = ICK_Identity; 2028 SCS.Third = ICK_Qualification; 2029 SCS.QualificationIncludesObjCLifetime = false; 2030 SCS.setAllToTypes(FromType); 2031 return true; 2032 } 2033 } else if (FromType->isFunctionType() && argIsLValue) { 2034 // Function-to-pointer conversion (C++ 4.3). 2035 SCS.First = ICK_Function_To_Pointer; 2036 2037 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 2038 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 2039 if (!S.checkAddressOfFunctionIsAvailable(FD)) 2040 return false; 2041 2042 // An lvalue of function type T can be converted to an rvalue of 2043 // type "pointer to T." The result is a pointer to the 2044 // function. (C++ 4.3p1). 2045 FromType = S.Context.getPointerType(FromType); 2046 } else { 2047 // We don't require any conversions for the first step. 2048 SCS.First = ICK_Identity; 2049 } 2050 SCS.setToType(0, FromType); 2051 2052 // The second conversion can be an integral promotion, floating 2053 // point promotion, integral conversion, floating point conversion, 2054 // floating-integral conversion, pointer conversion, 2055 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 2056 // For overloading in C, this can also be a "compatible-type" 2057 // conversion. 2058 bool IncompatibleObjC = false; 2059 ImplicitConversionKind SecondICK = ICK_Identity; 2060 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 2061 // The unqualified versions of the types are the same: there's no 2062 // conversion to do. 2063 SCS.Second = ICK_Identity; 2064 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 2065 // Integral promotion (C++ 4.5). 2066 SCS.Second = ICK_Integral_Promotion; 2067 FromType = ToType.getUnqualifiedType(); 2068 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 2069 // Floating point promotion (C++ 4.6). 2070 SCS.Second = ICK_Floating_Promotion; 2071 FromType = ToType.getUnqualifiedType(); 2072 } else if (S.IsComplexPromotion(FromType, ToType)) { 2073 // Complex promotion (Clang extension) 2074 SCS.Second = ICK_Complex_Promotion; 2075 FromType = ToType.getUnqualifiedType(); 2076 } else if (ToType->isBooleanType() && 2077 (FromType->isArithmeticType() || 2078 FromType->isAnyPointerType() || 2079 FromType->isBlockPointerType() || 2080 FromType->isMemberPointerType())) { 2081 // Boolean conversions (C++ 4.12). 2082 SCS.Second = ICK_Boolean_Conversion; 2083 FromType = S.Context.BoolTy; 2084 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 2085 ToType->isIntegralType(S.Context)) { 2086 // Integral conversions (C++ 4.7). 2087 SCS.Second = ICK_Integral_Conversion; 2088 FromType = ToType.getUnqualifiedType(); 2089 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 2090 // Complex conversions (C99 6.3.1.6) 2091 SCS.Second = ICK_Complex_Conversion; 2092 FromType = ToType.getUnqualifiedType(); 2093 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 2094 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 2095 // Complex-real conversions (C99 6.3.1.7) 2096 SCS.Second = ICK_Complex_Real; 2097 FromType = ToType.getUnqualifiedType(); 2098 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 2099 // FIXME: disable conversions between long double, __ibm128 and __float128 2100 // if their representation is different until there is back end support 2101 // We of course allow this conversion if long double is really double. 2102 2103 // Conversions between bfloat16 and float16 are currently not supported. 2104 if ((FromType->isBFloat16Type() && 2105 (ToType->isFloat16Type() || ToType->isHalfType())) || 2106 (ToType->isBFloat16Type() && 2107 (FromType->isFloat16Type() || FromType->isHalfType()))) 2108 return false; 2109 2110 // Conversions between IEEE-quad and IBM-extended semantics are not 2111 // permitted. 2112 const llvm::fltSemantics &FromSem = 2113 S.Context.getFloatTypeSemantics(FromType); 2114 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 2115 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 2116 &ToSem == &llvm::APFloat::IEEEquad()) || 2117 (&FromSem == &llvm::APFloat::IEEEquad() && 2118 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 2119 return false; 2120 2121 // Floating point conversions (C++ 4.8). 2122 SCS.Second = ICK_Floating_Conversion; 2123 FromType = ToType.getUnqualifiedType(); 2124 } else if ((FromType->isRealFloatingType() && 2125 ToType->isIntegralType(S.Context)) || 2126 (FromType->isIntegralOrUnscopedEnumerationType() && 2127 ToType->isRealFloatingType())) { 2128 2129 // Floating-integral conversions (C++ 4.9). 2130 SCS.Second = ICK_Floating_Integral; 2131 FromType = ToType.getUnqualifiedType(); 2132 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 2133 SCS.Second = ICK_Block_Pointer_Conversion; 2134 } else if (AllowObjCWritebackConversion && 2135 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 2136 SCS.Second = ICK_Writeback_Conversion; 2137 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 2138 FromType, IncompatibleObjC)) { 2139 // Pointer conversions (C++ 4.10). 2140 SCS.Second = ICK_Pointer_Conversion; 2141 SCS.IncompatibleObjC = IncompatibleObjC; 2142 FromType = FromType.getUnqualifiedType(); 2143 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 2144 InOverloadResolution, FromType)) { 2145 // Pointer to member conversions (4.11). 2146 SCS.Second = ICK_Pointer_Member; 2147 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, 2148 InOverloadResolution, CStyle)) { 2149 SCS.Second = SecondICK; 2150 FromType = ToType.getUnqualifiedType(); 2151 } else if (!S.getLangOpts().CPlusPlus && 2152 S.Context.typesAreCompatible(ToType, FromType)) { 2153 // Compatible conversions (Clang extension for C function overloading) 2154 SCS.Second = ICK_Compatible_Conversion; 2155 FromType = ToType.getUnqualifiedType(); 2156 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 2157 InOverloadResolution, 2158 SCS, CStyle)) { 2159 SCS.Second = ICK_TransparentUnionConversion; 2160 FromType = ToType; 2161 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 2162 CStyle)) { 2163 // tryAtomicConversion has updated the standard conversion sequence 2164 // appropriately. 2165 return true; 2166 } else if (ToType->isEventT() && 2167 From->isIntegerConstantExpr(S.getASTContext()) && 2168 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 2169 SCS.Second = ICK_Zero_Event_Conversion; 2170 FromType = ToType; 2171 } else if (ToType->isQueueT() && 2172 From->isIntegerConstantExpr(S.getASTContext()) && 2173 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 2174 SCS.Second = ICK_Zero_Queue_Conversion; 2175 FromType = ToType; 2176 } else if (ToType->isSamplerT() && 2177 From->isIntegerConstantExpr(S.getASTContext())) { 2178 SCS.Second = ICK_Compatible_Conversion; 2179 FromType = ToType; 2180 } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) { 2181 SCS.Second = ICK_Fixed_Point_Conversion; 2182 FromType = ToType; 2183 } else { 2184 // No second conversion required. 2185 SCS.Second = ICK_Identity; 2186 } 2187 SCS.setToType(1, FromType); 2188 2189 // The third conversion can be a function pointer conversion or a 2190 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 2191 bool ObjCLifetimeConversion; 2192 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 2193 // Function pointer conversions (removing 'noexcept') including removal of 2194 // 'noreturn' (Clang extension). 2195 SCS.Third = ICK_Function_Conversion; 2196 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 2197 ObjCLifetimeConversion)) { 2198 SCS.Third = ICK_Qualification; 2199 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 2200 FromType = ToType; 2201 } else { 2202 // No conversion required 2203 SCS.Third = ICK_Identity; 2204 } 2205 2206 // C++ [over.best.ics]p6: 2207 // [...] Any difference in top-level cv-qualification is 2208 // subsumed by the initialization itself and does not constitute 2209 // a conversion. [...] 2210 QualType CanonFrom = S.Context.getCanonicalType(FromType); 2211 QualType CanonTo = S.Context.getCanonicalType(ToType); 2212 if (CanonFrom.getLocalUnqualifiedType() 2213 == CanonTo.getLocalUnqualifiedType() && 2214 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 2215 FromType = ToType; 2216 CanonFrom = CanonTo; 2217 } 2218 2219 SCS.setToType(2, FromType); 2220 2221 if (CanonFrom == CanonTo) 2222 return true; 2223 2224 // If we have not converted the argument type to the parameter type, 2225 // this is a bad conversion sequence, unless we're resolving an overload in C. 2226 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 2227 return false; 2228 2229 ExprResult ER = ExprResult{From}; 2230 Sema::AssignConvertType Conv = 2231 S.CheckSingleAssignmentConstraints(ToType, ER, 2232 /*Diagnose=*/false, 2233 /*DiagnoseCFAudited=*/false, 2234 /*ConvertRHS=*/false); 2235 ImplicitConversionKind SecondConv; 2236 switch (Conv) { 2237 case Sema::Compatible: 2238 SecondConv = ICK_C_Only_Conversion; 2239 break; 2240 // For our purposes, discarding qualifiers is just as bad as using an 2241 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2242 // qualifiers, as well. 2243 case Sema::CompatiblePointerDiscardsQualifiers: 2244 case Sema::IncompatiblePointer: 2245 case Sema::IncompatiblePointerSign: 2246 SecondConv = ICK_Incompatible_Pointer_Conversion; 2247 break; 2248 default: 2249 return false; 2250 } 2251 2252 // First can only be an lvalue conversion, so we pretend that this was the 2253 // second conversion. First should already be valid from earlier in the 2254 // function. 2255 SCS.Second = SecondConv; 2256 SCS.setToType(1, ToType); 2257 2258 // Third is Identity, because Second should rank us worse than any other 2259 // conversion. This could also be ICK_Qualification, but it's simpler to just 2260 // lump everything in with the second conversion, and we don't gain anything 2261 // from making this ICK_Qualification. 2262 SCS.Third = ICK_Identity; 2263 SCS.setToType(2, ToType); 2264 return true; 2265 } 2266 2267 static bool 2268 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2269 QualType &ToType, 2270 bool InOverloadResolution, 2271 StandardConversionSequence &SCS, 2272 bool CStyle) { 2273 2274 const RecordType *UT = ToType->getAsUnionType(); 2275 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2276 return false; 2277 // The field to initialize within the transparent union. 2278 RecordDecl *UD = UT->getDecl(); 2279 // It's compatible if the expression matches any of the fields. 2280 for (const auto *it : UD->fields()) { 2281 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2282 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2283 ToType = it->getType(); 2284 return true; 2285 } 2286 } 2287 return false; 2288 } 2289 2290 /// IsIntegralPromotion - Determines whether the conversion from the 2291 /// expression From (whose potentially-adjusted type is FromType) to 2292 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2293 /// sets PromotedType to the promoted type. 2294 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2295 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2296 // All integers are built-in. 2297 if (!To) { 2298 return false; 2299 } 2300 2301 // An rvalue of type char, signed char, unsigned char, short int, or 2302 // unsigned short int can be converted to an rvalue of type int if 2303 // int can represent all the values of the source type; otherwise, 2304 // the source rvalue can be converted to an rvalue of type unsigned 2305 // int (C++ 4.5p1). 2306 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() && 2307 !FromType->isEnumeralType()) { 2308 if ( // We can promote any signed, promotable integer type to an int 2309 (FromType->isSignedIntegerType() || 2310 // We can promote any unsigned integer type whose size is 2311 // less than int to an int. 2312 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2313 return To->getKind() == BuiltinType::Int; 2314 } 2315 2316 return To->getKind() == BuiltinType::UInt; 2317 } 2318 2319 // C++11 [conv.prom]p3: 2320 // A prvalue of an unscoped enumeration type whose underlying type is not 2321 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2322 // following types that can represent all the values of the enumeration 2323 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2324 // unsigned int, long int, unsigned long int, long long int, or unsigned 2325 // long long int. If none of the types in that list can represent all the 2326 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2327 // type can be converted to an rvalue a prvalue of the extended integer type 2328 // with lowest integer conversion rank (4.13) greater than the rank of long 2329 // long in which all the values of the enumeration can be represented. If 2330 // there are two such extended types, the signed one is chosen. 2331 // C++11 [conv.prom]p4: 2332 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2333 // can be converted to a prvalue of its underlying type. Moreover, if 2334 // integral promotion can be applied to its underlying type, a prvalue of an 2335 // unscoped enumeration type whose underlying type is fixed can also be 2336 // converted to a prvalue of the promoted underlying type. 2337 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2338 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2339 // provided for a scoped enumeration. 2340 if (FromEnumType->getDecl()->isScoped()) 2341 return false; 2342 2343 // We can perform an integral promotion to the underlying type of the enum, 2344 // even if that's not the promoted type. Note that the check for promoting 2345 // the underlying type is based on the type alone, and does not consider 2346 // the bitfield-ness of the actual source expression. 2347 if (FromEnumType->getDecl()->isFixed()) { 2348 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2349 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2350 IsIntegralPromotion(nullptr, Underlying, ToType); 2351 } 2352 2353 // We have already pre-calculated the promotion type, so this is trivial. 2354 if (ToType->isIntegerType() && 2355 isCompleteType(From->getBeginLoc(), FromType)) 2356 return Context.hasSameUnqualifiedType( 2357 ToType, FromEnumType->getDecl()->getPromotionType()); 2358 2359 // C++ [conv.prom]p5: 2360 // If the bit-field has an enumerated type, it is treated as any other 2361 // value of that type for promotion purposes. 2362 // 2363 // ... so do not fall through into the bit-field checks below in C++. 2364 if (getLangOpts().CPlusPlus) 2365 return false; 2366 } 2367 2368 // C++0x [conv.prom]p2: 2369 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2370 // to an rvalue a prvalue of the first of the following types that can 2371 // represent all the values of its underlying type: int, unsigned int, 2372 // long int, unsigned long int, long long int, or unsigned long long int. 2373 // If none of the types in that list can represent all the values of its 2374 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2375 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2376 // type. 2377 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2378 ToType->isIntegerType()) { 2379 // Determine whether the type we're converting from is signed or 2380 // unsigned. 2381 bool FromIsSigned = FromType->isSignedIntegerType(); 2382 uint64_t FromSize = Context.getTypeSize(FromType); 2383 2384 // The types we'll try to promote to, in the appropriate 2385 // order. Try each of these types. 2386 QualType PromoteTypes[6] = { 2387 Context.IntTy, Context.UnsignedIntTy, 2388 Context.LongTy, Context.UnsignedLongTy , 2389 Context.LongLongTy, Context.UnsignedLongLongTy 2390 }; 2391 for (int Idx = 0; Idx < 6; ++Idx) { 2392 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2393 if (FromSize < ToSize || 2394 (FromSize == ToSize && 2395 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2396 // We found the type that we can promote to. If this is the 2397 // type we wanted, we have a promotion. Otherwise, no 2398 // promotion. 2399 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2400 } 2401 } 2402 } 2403 2404 // An rvalue for an integral bit-field (9.6) can be converted to an 2405 // rvalue of type int if int can represent all the values of the 2406 // bit-field; otherwise, it can be converted to unsigned int if 2407 // unsigned int can represent all the values of the bit-field. If 2408 // the bit-field is larger yet, no integral promotion applies to 2409 // it. If the bit-field has an enumerated type, it is treated as any 2410 // other value of that type for promotion purposes (C++ 4.5p3). 2411 // FIXME: We should delay checking of bit-fields until we actually perform the 2412 // conversion. 2413 // 2414 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2415 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2416 // bit-fields and those whose underlying type is larger than int) for GCC 2417 // compatibility. 2418 if (From) { 2419 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2420 std::optional<llvm::APSInt> BitWidth; 2421 if (FromType->isIntegralType(Context) && 2422 (BitWidth = 2423 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2424 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2425 ToSize = Context.getTypeSize(ToType); 2426 2427 // Are we promoting to an int from a bitfield that fits in an int? 2428 if (*BitWidth < ToSize || 2429 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2430 return To->getKind() == BuiltinType::Int; 2431 } 2432 2433 // Are we promoting to an unsigned int from an unsigned bitfield 2434 // that fits into an unsigned int? 2435 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2436 return To->getKind() == BuiltinType::UInt; 2437 } 2438 2439 return false; 2440 } 2441 } 2442 } 2443 2444 // An rvalue of type bool can be converted to an rvalue of type int, 2445 // with false becoming zero and true becoming one (C++ 4.5p4). 2446 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2447 return true; 2448 } 2449 2450 return false; 2451 } 2452 2453 /// IsFloatingPointPromotion - Determines whether the conversion from 2454 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2455 /// returns true and sets PromotedType to the promoted type. 2456 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2457 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2458 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2459 /// An rvalue of type float can be converted to an rvalue of type 2460 /// double. (C++ 4.6p1). 2461 if (FromBuiltin->getKind() == BuiltinType::Float && 2462 ToBuiltin->getKind() == BuiltinType::Double) 2463 return true; 2464 2465 // C99 6.3.1.5p1: 2466 // When a float is promoted to double or long double, or a 2467 // double is promoted to long double [...]. 2468 if (!getLangOpts().CPlusPlus && 2469 (FromBuiltin->getKind() == BuiltinType::Float || 2470 FromBuiltin->getKind() == BuiltinType::Double) && 2471 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2472 ToBuiltin->getKind() == BuiltinType::Float128 || 2473 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2474 return true; 2475 2476 // Half can be promoted to float. 2477 if (!getLangOpts().NativeHalfType && 2478 FromBuiltin->getKind() == BuiltinType::Half && 2479 ToBuiltin->getKind() == BuiltinType::Float) 2480 return true; 2481 } 2482 2483 return false; 2484 } 2485 2486 /// Determine if a conversion is a complex promotion. 2487 /// 2488 /// A complex promotion is defined as a complex -> complex conversion 2489 /// where the conversion between the underlying real types is a 2490 /// floating-point or integral promotion. 2491 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2492 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2493 if (!FromComplex) 2494 return false; 2495 2496 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2497 if (!ToComplex) 2498 return false; 2499 2500 return IsFloatingPointPromotion(FromComplex->getElementType(), 2501 ToComplex->getElementType()) || 2502 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2503 ToComplex->getElementType()); 2504 } 2505 2506 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2507 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2508 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2509 /// if non-empty, will be a pointer to ToType that may or may not have 2510 /// the right set of qualifiers on its pointee. 2511 /// 2512 static QualType 2513 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2514 QualType ToPointee, QualType ToType, 2515 ASTContext &Context, 2516 bool StripObjCLifetime = false) { 2517 assert((FromPtr->getTypeClass() == Type::Pointer || 2518 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2519 "Invalid similarly-qualified pointer type"); 2520 2521 /// Conversions to 'id' subsume cv-qualifier conversions. 2522 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2523 return ToType.getUnqualifiedType(); 2524 2525 QualType CanonFromPointee 2526 = Context.getCanonicalType(FromPtr->getPointeeType()); 2527 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2528 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2529 2530 if (StripObjCLifetime) 2531 Quals.removeObjCLifetime(); 2532 2533 // Exact qualifier match -> return the pointer type we're converting to. 2534 if (CanonToPointee.getLocalQualifiers() == Quals) { 2535 // ToType is exactly what we need. Return it. 2536 if (!ToType.isNull()) 2537 return ToType.getUnqualifiedType(); 2538 2539 // Build a pointer to ToPointee. It has the right qualifiers 2540 // already. 2541 if (isa<ObjCObjectPointerType>(ToType)) 2542 return Context.getObjCObjectPointerType(ToPointee); 2543 return Context.getPointerType(ToPointee); 2544 } 2545 2546 // Just build a canonical type that has the right qualifiers. 2547 QualType QualifiedCanonToPointee 2548 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2549 2550 if (isa<ObjCObjectPointerType>(ToType)) 2551 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2552 return Context.getPointerType(QualifiedCanonToPointee); 2553 } 2554 2555 static bool isNullPointerConstantForConversion(Expr *Expr, 2556 bool InOverloadResolution, 2557 ASTContext &Context) { 2558 // Handle value-dependent integral null pointer constants correctly. 2559 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2560 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2561 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2562 return !InOverloadResolution; 2563 2564 return Expr->isNullPointerConstant(Context, 2565 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2566 : Expr::NPC_ValueDependentIsNull); 2567 } 2568 2569 /// IsPointerConversion - Determines whether the conversion of the 2570 /// expression From, which has the (possibly adjusted) type FromType, 2571 /// can be converted to the type ToType via a pointer conversion (C++ 2572 /// 4.10). If so, returns true and places the converted type (that 2573 /// might differ from ToType in its cv-qualifiers at some level) into 2574 /// ConvertedType. 2575 /// 2576 /// This routine also supports conversions to and from block pointers 2577 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2578 /// pointers to interfaces. FIXME: Once we've determined the 2579 /// appropriate overloading rules for Objective-C, we may want to 2580 /// split the Objective-C checks into a different routine; however, 2581 /// GCC seems to consider all of these conversions to be pointer 2582 /// conversions, so for now they live here. IncompatibleObjC will be 2583 /// set if the conversion is an allowed Objective-C conversion that 2584 /// should result in a warning. 2585 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2586 bool InOverloadResolution, 2587 QualType& ConvertedType, 2588 bool &IncompatibleObjC) { 2589 IncompatibleObjC = false; 2590 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2591 IncompatibleObjC)) 2592 return true; 2593 2594 // Conversion from a null pointer constant to any Objective-C pointer type. 2595 if (ToType->isObjCObjectPointerType() && 2596 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2597 ConvertedType = ToType; 2598 return true; 2599 } 2600 2601 // Blocks: Block pointers can be converted to void*. 2602 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2603 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2604 ConvertedType = ToType; 2605 return true; 2606 } 2607 // Blocks: A null pointer constant can be converted to a block 2608 // pointer type. 2609 if (ToType->isBlockPointerType() && 2610 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2611 ConvertedType = ToType; 2612 return true; 2613 } 2614 2615 // If the left-hand-side is nullptr_t, the right side can be a null 2616 // pointer constant. 2617 if (ToType->isNullPtrType() && 2618 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2619 ConvertedType = ToType; 2620 return true; 2621 } 2622 2623 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2624 if (!ToTypePtr) 2625 return false; 2626 2627 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2628 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2629 ConvertedType = ToType; 2630 return true; 2631 } 2632 2633 // Beyond this point, both types need to be pointers 2634 // , including objective-c pointers. 2635 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2636 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2637 !getLangOpts().ObjCAutoRefCount) { 2638 ConvertedType = BuildSimilarlyQualifiedPointerType( 2639 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2640 Context); 2641 return true; 2642 } 2643 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2644 if (!FromTypePtr) 2645 return false; 2646 2647 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2648 2649 // If the unqualified pointee types are the same, this can't be a 2650 // pointer conversion, so don't do all of the work below. 2651 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2652 return false; 2653 2654 // An rvalue of type "pointer to cv T," where T is an object type, 2655 // can be converted to an rvalue of type "pointer to cv void" (C++ 2656 // 4.10p2). 2657 if (FromPointeeType->isIncompleteOrObjectType() && 2658 ToPointeeType->isVoidType()) { 2659 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2660 ToPointeeType, 2661 ToType, Context, 2662 /*StripObjCLifetime=*/true); 2663 return true; 2664 } 2665 2666 // MSVC allows implicit function to void* type conversion. 2667 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2668 ToPointeeType->isVoidType()) { 2669 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2670 ToPointeeType, 2671 ToType, Context); 2672 return true; 2673 } 2674 2675 // When we're overloading in C, we allow a special kind of pointer 2676 // conversion for compatible-but-not-identical pointee types. 2677 if (!getLangOpts().CPlusPlus && 2678 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2679 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2680 ToPointeeType, 2681 ToType, Context); 2682 return true; 2683 } 2684 2685 // C++ [conv.ptr]p3: 2686 // 2687 // An rvalue of type "pointer to cv D," where D is a class type, 2688 // can be converted to an rvalue of type "pointer to cv B," where 2689 // B is a base class (clause 10) of D. If B is an inaccessible 2690 // (clause 11) or ambiguous (10.2) base class of D, a program that 2691 // necessitates this conversion is ill-formed. The result of the 2692 // conversion is a pointer to the base class sub-object of the 2693 // derived class object. The null pointer value is converted to 2694 // the null pointer value of the destination type. 2695 // 2696 // Note that we do not check for ambiguity or inaccessibility 2697 // here. That is handled by CheckPointerConversion. 2698 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2699 ToPointeeType->isRecordType() && 2700 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2701 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2702 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2703 ToPointeeType, 2704 ToType, Context); 2705 return true; 2706 } 2707 2708 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2709 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2710 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2711 ToPointeeType, 2712 ToType, Context); 2713 return true; 2714 } 2715 2716 return false; 2717 } 2718 2719 /// Adopt the given qualifiers for the given type. 2720 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2721 Qualifiers TQs = T.getQualifiers(); 2722 2723 // Check whether qualifiers already match. 2724 if (TQs == Qs) 2725 return T; 2726 2727 if (Qs.compatiblyIncludes(TQs)) 2728 return Context.getQualifiedType(T, Qs); 2729 2730 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2731 } 2732 2733 /// isObjCPointerConversion - Determines whether this is an 2734 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2735 /// with the same arguments and return values. 2736 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2737 QualType& ConvertedType, 2738 bool &IncompatibleObjC) { 2739 if (!getLangOpts().ObjC) 2740 return false; 2741 2742 // The set of qualifiers on the type we're converting from. 2743 Qualifiers FromQualifiers = FromType.getQualifiers(); 2744 2745 // First, we handle all conversions on ObjC object pointer types. 2746 const ObjCObjectPointerType* ToObjCPtr = 2747 ToType->getAs<ObjCObjectPointerType>(); 2748 const ObjCObjectPointerType *FromObjCPtr = 2749 FromType->getAs<ObjCObjectPointerType>(); 2750 2751 if (ToObjCPtr && FromObjCPtr) { 2752 // If the pointee types are the same (ignoring qualifications), 2753 // then this is not a pointer conversion. 2754 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2755 FromObjCPtr->getPointeeType())) 2756 return false; 2757 2758 // Conversion between Objective-C pointers. 2759 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2760 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2761 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2762 if (getLangOpts().CPlusPlus && LHS && RHS && 2763 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2764 FromObjCPtr->getPointeeType())) 2765 return false; 2766 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2767 ToObjCPtr->getPointeeType(), 2768 ToType, Context); 2769 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2770 return true; 2771 } 2772 2773 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2774 // Okay: this is some kind of implicit downcast of Objective-C 2775 // interfaces, which is permitted. However, we're going to 2776 // complain about it. 2777 IncompatibleObjC = true; 2778 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2779 ToObjCPtr->getPointeeType(), 2780 ToType, Context); 2781 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2782 return true; 2783 } 2784 } 2785 // Beyond this point, both types need to be C pointers or block pointers. 2786 QualType ToPointeeType; 2787 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2788 ToPointeeType = ToCPtr->getPointeeType(); 2789 else if (const BlockPointerType *ToBlockPtr = 2790 ToType->getAs<BlockPointerType>()) { 2791 // Objective C++: We're able to convert from a pointer to any object 2792 // to a block pointer type. 2793 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2794 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2795 return true; 2796 } 2797 ToPointeeType = ToBlockPtr->getPointeeType(); 2798 } 2799 else if (FromType->getAs<BlockPointerType>() && 2800 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2801 // Objective C++: We're able to convert from a block pointer type to a 2802 // pointer to any object. 2803 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2804 return true; 2805 } 2806 else 2807 return false; 2808 2809 QualType FromPointeeType; 2810 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2811 FromPointeeType = FromCPtr->getPointeeType(); 2812 else if (const BlockPointerType *FromBlockPtr = 2813 FromType->getAs<BlockPointerType>()) 2814 FromPointeeType = FromBlockPtr->getPointeeType(); 2815 else 2816 return false; 2817 2818 // If we have pointers to pointers, recursively check whether this 2819 // is an Objective-C conversion. 2820 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2821 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2822 IncompatibleObjC)) { 2823 // We always complain about this conversion. 2824 IncompatibleObjC = true; 2825 ConvertedType = Context.getPointerType(ConvertedType); 2826 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2827 return true; 2828 } 2829 // Allow conversion of pointee being objective-c pointer to another one; 2830 // as in I* to id. 2831 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2832 ToPointeeType->getAs<ObjCObjectPointerType>() && 2833 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2834 IncompatibleObjC)) { 2835 2836 ConvertedType = Context.getPointerType(ConvertedType); 2837 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2838 return true; 2839 } 2840 2841 // If we have pointers to functions or blocks, check whether the only 2842 // differences in the argument and result types are in Objective-C 2843 // pointer conversions. If so, we permit the conversion (but 2844 // complain about it). 2845 const FunctionProtoType *FromFunctionType 2846 = FromPointeeType->getAs<FunctionProtoType>(); 2847 const FunctionProtoType *ToFunctionType 2848 = ToPointeeType->getAs<FunctionProtoType>(); 2849 if (FromFunctionType && ToFunctionType) { 2850 // If the function types are exactly the same, this isn't an 2851 // Objective-C pointer conversion. 2852 if (Context.getCanonicalType(FromPointeeType) 2853 == Context.getCanonicalType(ToPointeeType)) 2854 return false; 2855 2856 // Perform the quick checks that will tell us whether these 2857 // function types are obviously different. 2858 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2859 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2860 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2861 return false; 2862 2863 bool HasObjCConversion = false; 2864 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2865 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2866 // Okay, the types match exactly. Nothing to do. 2867 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2868 ToFunctionType->getReturnType(), 2869 ConvertedType, IncompatibleObjC)) { 2870 // Okay, we have an Objective-C pointer conversion. 2871 HasObjCConversion = true; 2872 } else { 2873 // Function types are too different. Abort. 2874 return false; 2875 } 2876 2877 // Check argument types. 2878 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2879 ArgIdx != NumArgs; ++ArgIdx) { 2880 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2881 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2882 if (Context.getCanonicalType(FromArgType) 2883 == Context.getCanonicalType(ToArgType)) { 2884 // Okay, the types match exactly. Nothing to do. 2885 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2886 ConvertedType, IncompatibleObjC)) { 2887 // Okay, we have an Objective-C pointer conversion. 2888 HasObjCConversion = true; 2889 } else { 2890 // Argument types are too different. Abort. 2891 return false; 2892 } 2893 } 2894 2895 if (HasObjCConversion) { 2896 // We had an Objective-C conversion. Allow this pointer 2897 // conversion, but complain about it. 2898 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2899 IncompatibleObjC = true; 2900 return true; 2901 } 2902 } 2903 2904 return false; 2905 } 2906 2907 /// Determine whether this is an Objective-C writeback conversion, 2908 /// used for parameter passing when performing automatic reference counting. 2909 /// 2910 /// \param FromType The type we're converting form. 2911 /// 2912 /// \param ToType The type we're converting to. 2913 /// 2914 /// \param ConvertedType The type that will be produced after applying 2915 /// this conversion. 2916 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2917 QualType &ConvertedType) { 2918 if (!getLangOpts().ObjCAutoRefCount || 2919 Context.hasSameUnqualifiedType(FromType, ToType)) 2920 return false; 2921 2922 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2923 QualType ToPointee; 2924 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2925 ToPointee = ToPointer->getPointeeType(); 2926 else 2927 return false; 2928 2929 Qualifiers ToQuals = ToPointee.getQualifiers(); 2930 if (!ToPointee->isObjCLifetimeType() || 2931 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2932 !ToQuals.withoutObjCLifetime().empty()) 2933 return false; 2934 2935 // Argument must be a pointer to __strong to __weak. 2936 QualType FromPointee; 2937 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2938 FromPointee = FromPointer->getPointeeType(); 2939 else 2940 return false; 2941 2942 Qualifiers FromQuals = FromPointee.getQualifiers(); 2943 if (!FromPointee->isObjCLifetimeType() || 2944 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2945 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2946 return false; 2947 2948 // Make sure that we have compatible qualifiers. 2949 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2950 if (!ToQuals.compatiblyIncludes(FromQuals)) 2951 return false; 2952 2953 // Remove qualifiers from the pointee type we're converting from; they 2954 // aren't used in the compatibility check belong, and we'll be adding back 2955 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2956 FromPointee = FromPointee.getUnqualifiedType(); 2957 2958 // The unqualified form of the pointee types must be compatible. 2959 ToPointee = ToPointee.getUnqualifiedType(); 2960 bool IncompatibleObjC; 2961 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2962 FromPointee = ToPointee; 2963 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2964 IncompatibleObjC)) 2965 return false; 2966 2967 /// Construct the type we're converting to, which is a pointer to 2968 /// __autoreleasing pointee. 2969 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2970 ConvertedType = Context.getPointerType(FromPointee); 2971 return true; 2972 } 2973 2974 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2975 QualType& ConvertedType) { 2976 QualType ToPointeeType; 2977 if (const BlockPointerType *ToBlockPtr = 2978 ToType->getAs<BlockPointerType>()) 2979 ToPointeeType = ToBlockPtr->getPointeeType(); 2980 else 2981 return false; 2982 2983 QualType FromPointeeType; 2984 if (const BlockPointerType *FromBlockPtr = 2985 FromType->getAs<BlockPointerType>()) 2986 FromPointeeType = FromBlockPtr->getPointeeType(); 2987 else 2988 return false; 2989 // We have pointer to blocks, check whether the only 2990 // differences in the argument and result types are in Objective-C 2991 // pointer conversions. If so, we permit the conversion. 2992 2993 const FunctionProtoType *FromFunctionType 2994 = FromPointeeType->getAs<FunctionProtoType>(); 2995 const FunctionProtoType *ToFunctionType 2996 = ToPointeeType->getAs<FunctionProtoType>(); 2997 2998 if (!FromFunctionType || !ToFunctionType) 2999 return false; 3000 3001 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 3002 return true; 3003 3004 // Perform the quick checks that will tell us whether these 3005 // function types are obviously different. 3006 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 3007 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 3008 return false; 3009 3010 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 3011 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 3012 if (FromEInfo != ToEInfo) 3013 return false; 3014 3015 bool IncompatibleObjC = false; 3016 if (Context.hasSameType(FromFunctionType->getReturnType(), 3017 ToFunctionType->getReturnType())) { 3018 // Okay, the types match exactly. Nothing to do. 3019 } else { 3020 QualType RHS = FromFunctionType->getReturnType(); 3021 QualType LHS = ToFunctionType->getReturnType(); 3022 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 3023 !RHS.hasQualifiers() && LHS.hasQualifiers()) 3024 LHS = LHS.getUnqualifiedType(); 3025 3026 if (Context.hasSameType(RHS,LHS)) { 3027 // OK exact match. 3028 } else if (isObjCPointerConversion(RHS, LHS, 3029 ConvertedType, IncompatibleObjC)) { 3030 if (IncompatibleObjC) 3031 return false; 3032 // Okay, we have an Objective-C pointer conversion. 3033 } 3034 else 3035 return false; 3036 } 3037 3038 // Check argument types. 3039 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 3040 ArgIdx != NumArgs; ++ArgIdx) { 3041 IncompatibleObjC = false; 3042 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 3043 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 3044 if (Context.hasSameType(FromArgType, ToArgType)) { 3045 // Okay, the types match exactly. Nothing to do. 3046 } else if (isObjCPointerConversion(ToArgType, FromArgType, 3047 ConvertedType, IncompatibleObjC)) { 3048 if (IncompatibleObjC) 3049 return false; 3050 // Okay, we have an Objective-C pointer conversion. 3051 } else 3052 // Argument types are too different. Abort. 3053 return false; 3054 } 3055 3056 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 3057 bool CanUseToFPT, CanUseFromFPT; 3058 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 3059 CanUseToFPT, CanUseFromFPT, 3060 NewParamInfos)) 3061 return false; 3062 3063 ConvertedType = ToType; 3064 return true; 3065 } 3066 3067 enum { 3068 ft_default, 3069 ft_different_class, 3070 ft_parameter_arity, 3071 ft_parameter_mismatch, 3072 ft_return_type, 3073 ft_qualifer_mismatch, 3074 ft_noexcept 3075 }; 3076 3077 /// Attempts to get the FunctionProtoType from a Type. Handles 3078 /// MemberFunctionPointers properly. 3079 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 3080 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 3081 return FPT; 3082 3083 if (auto *MPT = FromType->getAs<MemberPointerType>()) 3084 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 3085 3086 return nullptr; 3087 } 3088 3089 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 3090 /// function types. Catches different number of parameter, mismatch in 3091 /// parameter types, and different return types. 3092 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3093 QualType FromType, QualType ToType) { 3094 // If either type is not valid, include no extra info. 3095 if (FromType.isNull() || ToType.isNull()) { 3096 PDiag << ft_default; 3097 return; 3098 } 3099 3100 // Get the function type from the pointers. 3101 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 3102 const auto *FromMember = FromType->castAs<MemberPointerType>(), 3103 *ToMember = ToType->castAs<MemberPointerType>(); 3104 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 3105 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 3106 << QualType(FromMember->getClass(), 0); 3107 return; 3108 } 3109 FromType = FromMember->getPointeeType(); 3110 ToType = ToMember->getPointeeType(); 3111 } 3112 3113 if (FromType->isPointerType()) 3114 FromType = FromType->getPointeeType(); 3115 if (ToType->isPointerType()) 3116 ToType = ToType->getPointeeType(); 3117 3118 // Remove references. 3119 FromType = FromType.getNonReferenceType(); 3120 ToType = ToType.getNonReferenceType(); 3121 3122 // Don't print extra info for non-specialized template functions. 3123 if (FromType->isInstantiationDependentType() && 3124 !FromType->getAs<TemplateSpecializationType>()) { 3125 PDiag << ft_default; 3126 return; 3127 } 3128 3129 // No extra info for same types. 3130 if (Context.hasSameType(FromType, ToType)) { 3131 PDiag << ft_default; 3132 return; 3133 } 3134 3135 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 3136 *ToFunction = tryGetFunctionProtoType(ToType); 3137 3138 // Both types need to be function types. 3139 if (!FromFunction || !ToFunction) { 3140 PDiag << ft_default; 3141 return; 3142 } 3143 3144 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 3145 PDiag << ft_parameter_arity << ToFunction->getNumParams() 3146 << FromFunction->getNumParams(); 3147 return; 3148 } 3149 3150 // Handle different parameter types. 3151 unsigned ArgPos; 3152 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 3153 PDiag << ft_parameter_mismatch << ArgPos + 1 3154 << ToFunction->getParamType(ArgPos) 3155 << FromFunction->getParamType(ArgPos); 3156 return; 3157 } 3158 3159 // Handle different return type. 3160 if (!Context.hasSameType(FromFunction->getReturnType(), 3161 ToFunction->getReturnType())) { 3162 PDiag << ft_return_type << ToFunction->getReturnType() 3163 << FromFunction->getReturnType(); 3164 return; 3165 } 3166 3167 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 3168 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 3169 << FromFunction->getMethodQuals(); 3170 return; 3171 } 3172 3173 // Handle exception specification differences on canonical type (in C++17 3174 // onwards). 3175 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 3176 ->isNothrow() != 3177 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 3178 ->isNothrow()) { 3179 PDiag << ft_noexcept; 3180 return; 3181 } 3182 3183 // Unable to find a difference, so add no extra info. 3184 PDiag << ft_default; 3185 } 3186 3187 /// FunctionParamTypesAreEqual - This routine checks two function proto types 3188 /// for equality of their parameter types. Caller has already checked that 3189 /// they have same number of parameters. If the parameters are different, 3190 /// ArgPos will have the parameter index of the first different parameter. 3191 /// If `Reversed` is true, the parameters of `NewType` will be compared in 3192 /// reverse order. That's useful if one of the functions is being used as a C++20 3193 /// synthesized operator overload with a reversed parameter order. 3194 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old, 3195 ArrayRef<QualType> New, unsigned *ArgPos, 3196 bool Reversed) { 3197 assert(llvm::size(Old) == llvm::size(New) && 3198 "Can't compare parameters of functions with different number of " 3199 "parameters!"); 3200 3201 for (auto &&[Idx, Type] : llvm::enumerate(Old)) { 3202 // Reverse iterate over the parameters of `OldType` if `Reversed` is true. 3203 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx; 3204 3205 // Ignore address spaces in pointee type. This is to disallow overloading 3206 // on __ptr32/__ptr64 address spaces. 3207 QualType OldType = 3208 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType()); 3209 QualType NewType = 3210 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType()); 3211 3212 if (!Context.hasSameType(OldType, NewType)) { 3213 if (ArgPos) 3214 *ArgPos = Idx; 3215 return false; 3216 } 3217 } 3218 return true; 3219 } 3220 3221 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3222 const FunctionProtoType *NewType, 3223 unsigned *ArgPos, bool Reversed) { 3224 return FunctionParamTypesAreEqual(OldType->param_types(), 3225 NewType->param_types(), ArgPos, Reversed); 3226 } 3227 3228 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, 3229 const FunctionDecl *NewFunction, 3230 unsigned *ArgPos, 3231 bool Reversed) { 3232 3233 if (OldFunction->getNumNonObjectParams() != 3234 NewFunction->getNumNonObjectParams()) 3235 return false; 3236 3237 unsigned OldIgnore = 3238 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter()); 3239 unsigned NewIgnore = 3240 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter()); 3241 3242 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType()); 3243 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType()); 3244 3245 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore), 3246 NewPT->param_types().slice(NewIgnore), 3247 ArgPos, Reversed); 3248 } 3249 3250 /// CheckPointerConversion - Check the pointer conversion from the 3251 /// expression From to the type ToType. This routine checks for 3252 /// ambiguous or inaccessible derived-to-base pointer 3253 /// conversions for which IsPointerConversion has already returned 3254 /// true. It returns true and produces a diagnostic if there was an 3255 /// error, or returns false otherwise. 3256 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 3257 CastKind &Kind, 3258 CXXCastPath& BasePath, 3259 bool IgnoreBaseAccess, 3260 bool Diagnose) { 3261 QualType FromType = From->getType(); 3262 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3263 3264 Kind = CK_BitCast; 3265 3266 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3267 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3268 Expr::NPCK_ZeroExpression) { 3269 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3270 DiagRuntimeBehavior(From->getExprLoc(), From, 3271 PDiag(diag::warn_impcast_bool_to_null_pointer) 3272 << ToType << From->getSourceRange()); 3273 else if (!isUnevaluatedContext()) 3274 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3275 << ToType << From->getSourceRange(); 3276 } 3277 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3278 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3279 QualType FromPointeeType = FromPtrType->getPointeeType(), 3280 ToPointeeType = ToPtrType->getPointeeType(); 3281 3282 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3283 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3284 // We must have a derived-to-base conversion. Check an 3285 // ambiguous or inaccessible conversion. 3286 unsigned InaccessibleID = 0; 3287 unsigned AmbiguousID = 0; 3288 if (Diagnose) { 3289 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3290 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3291 } 3292 if (CheckDerivedToBaseConversion( 3293 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3294 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3295 &BasePath, IgnoreBaseAccess)) 3296 return true; 3297 3298 // The conversion was successful. 3299 Kind = CK_DerivedToBase; 3300 } 3301 3302 if (Diagnose && !IsCStyleOrFunctionalCast && 3303 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3304 assert(getLangOpts().MSVCCompat && 3305 "this should only be possible with MSVCCompat!"); 3306 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3307 << From->getSourceRange(); 3308 } 3309 } 3310 } else if (const ObjCObjectPointerType *ToPtrType = 3311 ToType->getAs<ObjCObjectPointerType>()) { 3312 if (const ObjCObjectPointerType *FromPtrType = 3313 FromType->getAs<ObjCObjectPointerType>()) { 3314 // Objective-C++ conversions are always okay. 3315 // FIXME: We should have a different class of conversions for the 3316 // Objective-C++ implicit conversions. 3317 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3318 return false; 3319 } else if (FromType->isBlockPointerType()) { 3320 Kind = CK_BlockPointerToObjCPointerCast; 3321 } else { 3322 Kind = CK_CPointerToObjCPointerCast; 3323 } 3324 } else if (ToType->isBlockPointerType()) { 3325 if (!FromType->isBlockPointerType()) 3326 Kind = CK_AnyPointerToBlockPointerCast; 3327 } 3328 3329 // We shouldn't fall into this case unless it's valid for other 3330 // reasons. 3331 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3332 Kind = CK_NullToPointer; 3333 3334 return false; 3335 } 3336 3337 /// IsMemberPointerConversion - Determines whether the conversion of the 3338 /// expression From, which has the (possibly adjusted) type FromType, can be 3339 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3340 /// If so, returns true and places the converted type (that might differ from 3341 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3342 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3343 QualType ToType, 3344 bool InOverloadResolution, 3345 QualType &ConvertedType) { 3346 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3347 if (!ToTypePtr) 3348 return false; 3349 3350 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3351 if (From->isNullPointerConstant(Context, 3352 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3353 : Expr::NPC_ValueDependentIsNull)) { 3354 ConvertedType = ToType; 3355 return true; 3356 } 3357 3358 // Otherwise, both types have to be member pointers. 3359 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3360 if (!FromTypePtr) 3361 return false; 3362 3363 // A pointer to member of B can be converted to a pointer to member of D, 3364 // where D is derived from B (C++ 4.11p2). 3365 QualType FromClass(FromTypePtr->getClass(), 0); 3366 QualType ToClass(ToTypePtr->getClass(), 0); 3367 3368 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3369 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3370 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3371 ToClass.getTypePtr()); 3372 return true; 3373 } 3374 3375 return false; 3376 } 3377 3378 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3379 /// expression From to the type ToType. This routine checks for ambiguous or 3380 /// virtual or inaccessible base-to-derived member pointer conversions 3381 /// for which IsMemberPointerConversion has already returned true. It returns 3382 /// true and produces a diagnostic if there was an error, or returns false 3383 /// otherwise. 3384 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3385 CastKind &Kind, 3386 CXXCastPath &BasePath, 3387 bool IgnoreBaseAccess) { 3388 QualType FromType = From->getType(); 3389 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3390 if (!FromPtrType) { 3391 // This must be a null pointer to member pointer conversion 3392 assert(From->isNullPointerConstant(Context, 3393 Expr::NPC_ValueDependentIsNull) && 3394 "Expr must be null pointer constant!"); 3395 Kind = CK_NullToMemberPointer; 3396 return false; 3397 } 3398 3399 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3400 assert(ToPtrType && "No member pointer cast has a target type " 3401 "that is not a member pointer."); 3402 3403 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3404 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3405 3406 // FIXME: What about dependent types? 3407 assert(FromClass->isRecordType() && "Pointer into non-class."); 3408 assert(ToClass->isRecordType() && "Pointer into non-class."); 3409 3410 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3411 /*DetectVirtual=*/true); 3412 bool DerivationOkay = 3413 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3414 assert(DerivationOkay && 3415 "Should not have been called if derivation isn't OK."); 3416 (void)DerivationOkay; 3417 3418 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3419 getUnqualifiedType())) { 3420 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3421 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3422 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3423 return true; 3424 } 3425 3426 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3427 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3428 << FromClass << ToClass << QualType(VBase, 0) 3429 << From->getSourceRange(); 3430 return true; 3431 } 3432 3433 if (!IgnoreBaseAccess) 3434 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3435 Paths.front(), 3436 diag::err_downcast_from_inaccessible_base); 3437 3438 // Must be a base to derived member conversion. 3439 BuildBasePathArray(Paths, BasePath); 3440 Kind = CK_BaseToDerivedMemberPointer; 3441 return false; 3442 } 3443 3444 /// Determine whether the lifetime conversion between the two given 3445 /// qualifiers sets is nontrivial. 3446 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3447 Qualifiers ToQuals) { 3448 // Converting anything to const __unsafe_unretained is trivial. 3449 if (ToQuals.hasConst() && 3450 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3451 return false; 3452 3453 return true; 3454 } 3455 3456 /// Perform a single iteration of the loop for checking if a qualification 3457 /// conversion is valid. 3458 /// 3459 /// Specifically, check whether any change between the qualifiers of \p 3460 /// FromType and \p ToType is permissible, given knowledge about whether every 3461 /// outer layer is const-qualified. 3462 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3463 bool CStyle, bool IsTopLevel, 3464 bool &PreviousToQualsIncludeConst, 3465 bool &ObjCLifetimeConversion) { 3466 Qualifiers FromQuals = FromType.getQualifiers(); 3467 Qualifiers ToQuals = ToType.getQualifiers(); 3468 3469 // Ignore __unaligned qualifier. 3470 FromQuals.removeUnaligned(); 3471 3472 // Objective-C ARC: 3473 // Check Objective-C lifetime conversions. 3474 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3475 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3476 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3477 ObjCLifetimeConversion = true; 3478 FromQuals.removeObjCLifetime(); 3479 ToQuals.removeObjCLifetime(); 3480 } else { 3481 // Qualification conversions cannot cast between different 3482 // Objective-C lifetime qualifiers. 3483 return false; 3484 } 3485 } 3486 3487 // Allow addition/removal of GC attributes but not changing GC attributes. 3488 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3489 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3490 FromQuals.removeObjCGCAttr(); 3491 ToQuals.removeObjCGCAttr(); 3492 } 3493 3494 // -- for every j > 0, if const is in cv 1,j then const is in cv 3495 // 2,j, and similarly for volatile. 3496 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3497 return false; 3498 3499 // If address spaces mismatch: 3500 // - in top level it is only valid to convert to addr space that is a 3501 // superset in all cases apart from C-style casts where we allow 3502 // conversions between overlapping address spaces. 3503 // - in non-top levels it is not a valid conversion. 3504 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3505 (!IsTopLevel || 3506 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3507 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3508 return false; 3509 3510 // -- if the cv 1,j and cv 2,j are different, then const is in 3511 // every cv for 0 < k < j. 3512 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3513 !PreviousToQualsIncludeConst) 3514 return false; 3515 3516 // The following wording is from C++20, where the result of the conversion 3517 // is T3, not T2. 3518 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3519 // "array of unknown bound of" 3520 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3521 return false; 3522 3523 // -- if the resulting P3,i is different from P1,i [...], then const is 3524 // added to every cv 3_k for 0 < k < i. 3525 if (!CStyle && FromType->isConstantArrayType() && 3526 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3527 return false; 3528 3529 // Keep track of whether all prior cv-qualifiers in the "to" type 3530 // include const. 3531 PreviousToQualsIncludeConst = 3532 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3533 return true; 3534 } 3535 3536 /// IsQualificationConversion - Determines whether the conversion from 3537 /// an rvalue of type FromType to ToType is a qualification conversion 3538 /// (C++ 4.4). 3539 /// 3540 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3541 /// when the qualification conversion involves a change in the Objective-C 3542 /// object lifetime. 3543 bool 3544 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3545 bool CStyle, bool &ObjCLifetimeConversion) { 3546 FromType = Context.getCanonicalType(FromType); 3547 ToType = Context.getCanonicalType(ToType); 3548 ObjCLifetimeConversion = false; 3549 3550 // If FromType and ToType are the same type, this is not a 3551 // qualification conversion. 3552 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3553 return false; 3554 3555 // (C++ 4.4p4): 3556 // A conversion can add cv-qualifiers at levels other than the first 3557 // in multi-level pointers, subject to the following rules: [...] 3558 bool PreviousToQualsIncludeConst = true; 3559 bool UnwrappedAnyPointer = false; 3560 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3561 if (!isQualificationConversionStep( 3562 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3563 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3564 return false; 3565 UnwrappedAnyPointer = true; 3566 } 3567 3568 // We are left with FromType and ToType being the pointee types 3569 // after unwrapping the original FromType and ToType the same number 3570 // of times. If we unwrapped any pointers, and if FromType and 3571 // ToType have the same unqualified type (since we checked 3572 // qualifiers above), then this is a qualification conversion. 3573 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3574 } 3575 3576 /// - Determine whether this is a conversion from a scalar type to an 3577 /// atomic type. 3578 /// 3579 /// If successful, updates \c SCS's second and third steps in the conversion 3580 /// sequence to finish the conversion. 3581 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3582 bool InOverloadResolution, 3583 StandardConversionSequence &SCS, 3584 bool CStyle) { 3585 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3586 if (!ToAtomic) 3587 return false; 3588 3589 StandardConversionSequence InnerSCS; 3590 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3591 InOverloadResolution, InnerSCS, 3592 CStyle, /*AllowObjCWritebackConversion=*/false)) 3593 return false; 3594 3595 SCS.Second = InnerSCS.Second; 3596 SCS.setToType(1, InnerSCS.getToType(1)); 3597 SCS.Third = InnerSCS.Third; 3598 SCS.QualificationIncludesObjCLifetime 3599 = InnerSCS.QualificationIncludesObjCLifetime; 3600 SCS.setToType(2, InnerSCS.getToType(2)); 3601 return true; 3602 } 3603 3604 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3605 CXXConstructorDecl *Constructor, 3606 QualType Type) { 3607 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3608 if (CtorType->getNumParams() > 0) { 3609 QualType FirstArg = CtorType->getParamType(0); 3610 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3611 return true; 3612 } 3613 return false; 3614 } 3615 3616 static OverloadingResult 3617 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3618 CXXRecordDecl *To, 3619 UserDefinedConversionSequence &User, 3620 OverloadCandidateSet &CandidateSet, 3621 bool AllowExplicit) { 3622 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3623 for (auto *D : S.LookupConstructors(To)) { 3624 auto Info = getConstructorInfo(D); 3625 if (!Info) 3626 continue; 3627 3628 bool Usable = !Info.Constructor->isInvalidDecl() && 3629 S.isInitListConstructor(Info.Constructor); 3630 if (Usable) { 3631 bool SuppressUserConversions = false; 3632 if (Info.ConstructorTmpl) 3633 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3634 /*ExplicitArgs*/ nullptr, From, 3635 CandidateSet, SuppressUserConversions, 3636 /*PartialOverloading*/ false, 3637 AllowExplicit); 3638 else 3639 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3640 CandidateSet, SuppressUserConversions, 3641 /*PartialOverloading*/ false, AllowExplicit); 3642 } 3643 } 3644 3645 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3646 3647 OverloadCandidateSet::iterator Best; 3648 switch (auto Result = 3649 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3650 case OR_Deleted: 3651 case OR_Success: { 3652 // Record the standard conversion we used and the conversion function. 3653 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3654 QualType ThisType = Constructor->getFunctionObjectParameterType(); 3655 // Initializer lists don't have conversions as such. 3656 User.Before.setAsIdentityConversion(); 3657 User.HadMultipleCandidates = HadMultipleCandidates; 3658 User.ConversionFunction = Constructor; 3659 User.FoundConversionFunction = Best->FoundDecl; 3660 User.After.setAsIdentityConversion(); 3661 User.After.setFromType(ThisType); 3662 User.After.setAllToTypes(ToType); 3663 return Result; 3664 } 3665 3666 case OR_No_Viable_Function: 3667 return OR_No_Viable_Function; 3668 case OR_Ambiguous: 3669 return OR_Ambiguous; 3670 } 3671 3672 llvm_unreachable("Invalid OverloadResult!"); 3673 } 3674 3675 /// Determines whether there is a user-defined conversion sequence 3676 /// (C++ [over.ics.user]) that converts expression From to the type 3677 /// ToType. If such a conversion exists, User will contain the 3678 /// user-defined conversion sequence that performs such a conversion 3679 /// and this routine will return true. Otherwise, this routine returns 3680 /// false and User is unspecified. 3681 /// 3682 /// \param AllowExplicit true if the conversion should consider C++0x 3683 /// "explicit" conversion functions as well as non-explicit conversion 3684 /// functions (C++0x [class.conv.fct]p2). 3685 /// 3686 /// \param AllowObjCConversionOnExplicit true if the conversion should 3687 /// allow an extra Objective-C pointer conversion on uses of explicit 3688 /// constructors. Requires \c AllowExplicit to also be set. 3689 static OverloadingResult 3690 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3691 UserDefinedConversionSequence &User, 3692 OverloadCandidateSet &CandidateSet, 3693 AllowedExplicit AllowExplicit, 3694 bool AllowObjCConversionOnExplicit) { 3695 assert(AllowExplicit != AllowedExplicit::None || 3696 !AllowObjCConversionOnExplicit); 3697 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3698 3699 // Whether we will only visit constructors. 3700 bool ConstructorsOnly = false; 3701 3702 // If the type we are conversion to is a class type, enumerate its 3703 // constructors. 3704 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3705 // C++ [over.match.ctor]p1: 3706 // When objects of class type are direct-initialized (8.5), or 3707 // copy-initialized from an expression of the same or a 3708 // derived class type (8.5), overload resolution selects the 3709 // constructor. [...] For copy-initialization, the candidate 3710 // functions are all the converting constructors (12.3.1) of 3711 // that class. The argument list is the expression-list within 3712 // the parentheses of the initializer. 3713 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3714 (From->getType()->getAs<RecordType>() && 3715 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3716 ConstructorsOnly = true; 3717 3718 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3719 // We're not going to find any constructors. 3720 } else if (CXXRecordDecl *ToRecordDecl 3721 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3722 3723 Expr **Args = &From; 3724 unsigned NumArgs = 1; 3725 bool ListInitializing = false; 3726 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3727 // But first, see if there is an init-list-constructor that will work. 3728 OverloadingResult Result = IsInitializerListConstructorConversion( 3729 S, From, ToType, ToRecordDecl, User, CandidateSet, 3730 AllowExplicit == AllowedExplicit::All); 3731 if (Result != OR_No_Viable_Function) 3732 return Result; 3733 // Never mind. 3734 CandidateSet.clear( 3735 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3736 3737 // If we're list-initializing, we pass the individual elements as 3738 // arguments, not the entire list. 3739 Args = InitList->getInits(); 3740 NumArgs = InitList->getNumInits(); 3741 ListInitializing = true; 3742 } 3743 3744 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3745 auto Info = getConstructorInfo(D); 3746 if (!Info) 3747 continue; 3748 3749 bool Usable = !Info.Constructor->isInvalidDecl(); 3750 if (!ListInitializing) 3751 Usable = Usable && Info.Constructor->isConvertingConstructor( 3752 /*AllowExplicit*/ true); 3753 if (Usable) { 3754 bool SuppressUserConversions = !ConstructorsOnly; 3755 // C++20 [over.best.ics.general]/4.5: 3756 // if the target is the first parameter of a constructor [of class 3757 // X] and the constructor [...] is a candidate by [...] the second 3758 // phase of [over.match.list] when the initializer list has exactly 3759 // one element that is itself an initializer list, [...] and the 3760 // conversion is to X or reference to cv X, user-defined conversion 3761 // sequences are not cnosidered. 3762 if (SuppressUserConversions && ListInitializing) { 3763 SuppressUserConversions = 3764 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3765 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3766 ToType); 3767 } 3768 if (Info.ConstructorTmpl) 3769 S.AddTemplateOverloadCandidate( 3770 Info.ConstructorTmpl, Info.FoundDecl, 3771 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs), 3772 CandidateSet, SuppressUserConversions, 3773 /*PartialOverloading*/ false, 3774 AllowExplicit == AllowedExplicit::All); 3775 else 3776 // Allow one user-defined conversion when user specifies a 3777 // From->ToType conversion via an static cast (c-style, etc). 3778 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3779 llvm::ArrayRef(Args, NumArgs), CandidateSet, 3780 SuppressUserConversions, 3781 /*PartialOverloading*/ false, 3782 AllowExplicit == AllowedExplicit::All); 3783 } 3784 } 3785 } 3786 } 3787 3788 // Enumerate conversion functions, if we're allowed to. 3789 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3790 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3791 // No conversion functions from incomplete types. 3792 } else if (const RecordType *FromRecordType = 3793 From->getType()->getAs<RecordType>()) { 3794 if (CXXRecordDecl *FromRecordDecl 3795 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3796 // Add all of the conversion functions as candidates. 3797 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3798 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3799 DeclAccessPair FoundDecl = I.getPair(); 3800 NamedDecl *D = FoundDecl.getDecl(); 3801 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3802 if (isa<UsingShadowDecl>(D)) 3803 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3804 3805 CXXConversionDecl *Conv; 3806 FunctionTemplateDecl *ConvTemplate; 3807 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3808 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3809 else 3810 Conv = cast<CXXConversionDecl>(D); 3811 3812 if (ConvTemplate) 3813 S.AddTemplateConversionCandidate( 3814 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3815 CandidateSet, AllowObjCConversionOnExplicit, 3816 AllowExplicit != AllowedExplicit::None); 3817 else 3818 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3819 CandidateSet, AllowObjCConversionOnExplicit, 3820 AllowExplicit != AllowedExplicit::None); 3821 } 3822 } 3823 } 3824 3825 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3826 3827 OverloadCandidateSet::iterator Best; 3828 switch (auto Result = 3829 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3830 case OR_Success: 3831 case OR_Deleted: 3832 // Record the standard conversion we used and the conversion function. 3833 if (CXXConstructorDecl *Constructor 3834 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3835 // C++ [over.ics.user]p1: 3836 // If the user-defined conversion is specified by a 3837 // constructor (12.3.1), the initial standard conversion 3838 // sequence converts the source type to the type required by 3839 // the argument of the constructor. 3840 // 3841 if (isa<InitListExpr>(From)) { 3842 // Initializer lists don't have conversions as such. 3843 User.Before.setAsIdentityConversion(); 3844 } else { 3845 if (Best->Conversions[0].isEllipsis()) 3846 User.EllipsisConversion = true; 3847 else { 3848 User.Before = Best->Conversions[0].Standard; 3849 User.EllipsisConversion = false; 3850 } 3851 } 3852 User.HadMultipleCandidates = HadMultipleCandidates; 3853 User.ConversionFunction = Constructor; 3854 User.FoundConversionFunction = Best->FoundDecl; 3855 User.After.setAsIdentityConversion(); 3856 User.After.setFromType(Constructor->getFunctionObjectParameterType()); 3857 User.After.setAllToTypes(ToType); 3858 return Result; 3859 } 3860 if (CXXConversionDecl *Conversion 3861 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3862 // C++ [over.ics.user]p1: 3863 // 3864 // [...] If the user-defined conversion is specified by a 3865 // conversion function (12.3.2), the initial standard 3866 // conversion sequence converts the source type to the 3867 // implicit object parameter of the conversion function. 3868 User.Before = Best->Conversions[0].Standard; 3869 User.HadMultipleCandidates = HadMultipleCandidates; 3870 User.ConversionFunction = Conversion; 3871 User.FoundConversionFunction = Best->FoundDecl; 3872 User.EllipsisConversion = false; 3873 3874 // C++ [over.ics.user]p2: 3875 // The second standard conversion sequence converts the 3876 // result of the user-defined conversion to the target type 3877 // for the sequence. Since an implicit conversion sequence 3878 // is an initialization, the special rules for 3879 // initialization by user-defined conversion apply when 3880 // selecting the best user-defined conversion for a 3881 // user-defined conversion sequence (see 13.3.3 and 3882 // 13.3.3.1). 3883 User.After = Best->FinalConversion; 3884 return Result; 3885 } 3886 llvm_unreachable("Not a constructor or conversion function?"); 3887 3888 case OR_No_Viable_Function: 3889 return OR_No_Viable_Function; 3890 3891 case OR_Ambiguous: 3892 return OR_Ambiguous; 3893 } 3894 3895 llvm_unreachable("Invalid OverloadResult!"); 3896 } 3897 3898 bool 3899 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3900 ImplicitConversionSequence ICS; 3901 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3902 OverloadCandidateSet::CSK_Normal); 3903 OverloadingResult OvResult = 3904 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3905 CandidateSet, AllowedExplicit::None, false); 3906 3907 if (!(OvResult == OR_Ambiguous || 3908 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3909 return false; 3910 3911 auto Cands = CandidateSet.CompleteCandidates( 3912 *this, 3913 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3914 From); 3915 if (OvResult == OR_Ambiguous) 3916 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3917 << From->getType() << ToType << From->getSourceRange(); 3918 else { // OR_No_Viable_Function && !CandidateSet.empty() 3919 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3920 diag::err_typecheck_nonviable_condition_incomplete, 3921 From->getType(), From->getSourceRange())) 3922 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3923 << false << From->getType() << From->getSourceRange() << ToType; 3924 } 3925 3926 CandidateSet.NoteCandidates( 3927 *this, From, Cands); 3928 return true; 3929 } 3930 3931 // Helper for compareConversionFunctions that gets the FunctionType that the 3932 // conversion-operator return value 'points' to, or nullptr. 3933 static const FunctionType * 3934 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3935 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3936 const PointerType *RetPtrTy = 3937 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3938 3939 if (!RetPtrTy) 3940 return nullptr; 3941 3942 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3943 } 3944 3945 /// Compare the user-defined conversion functions or constructors 3946 /// of two user-defined conversion sequences to determine whether any ordering 3947 /// is possible. 3948 static ImplicitConversionSequence::CompareKind 3949 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3950 FunctionDecl *Function2) { 3951 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3952 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3953 if (!Conv1 || !Conv2) 3954 return ImplicitConversionSequence::Indistinguishable; 3955 3956 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3957 return ImplicitConversionSequence::Indistinguishable; 3958 3959 // Objective-C++: 3960 // If both conversion functions are implicitly-declared conversions from 3961 // a lambda closure type to a function pointer and a block pointer, 3962 // respectively, always prefer the conversion to a function pointer, 3963 // because the function pointer is more lightweight and is more likely 3964 // to keep code working. 3965 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3966 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3967 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3968 if (Block1 != Block2) 3969 return Block1 ? ImplicitConversionSequence::Worse 3970 : ImplicitConversionSequence::Better; 3971 } 3972 3973 // In order to support multiple calling conventions for the lambda conversion 3974 // operator (such as when the free and member function calling convention is 3975 // different), prefer the 'free' mechanism, followed by the calling-convention 3976 // of operator(). The latter is in place to support the MSVC-like solution of 3977 // defining ALL of the possible conversions in regards to calling-convention. 3978 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3979 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3980 3981 if (Conv1FuncRet && Conv2FuncRet && 3982 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3983 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3984 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3985 3986 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3987 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 3988 3989 CallingConv CallOpCC = 3990 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3991 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3992 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3993 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3994 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3995 3996 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3997 for (CallingConv CC : PrefOrder) { 3998 if (Conv1CC == CC) 3999 return ImplicitConversionSequence::Better; 4000 if (Conv2CC == CC) 4001 return ImplicitConversionSequence::Worse; 4002 } 4003 } 4004 4005 return ImplicitConversionSequence::Indistinguishable; 4006 } 4007 4008 static bool hasDeprecatedStringLiteralToCharPtrConversion( 4009 const ImplicitConversionSequence &ICS) { 4010 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 4011 (ICS.isUserDefined() && 4012 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 4013 } 4014 4015 /// CompareImplicitConversionSequences - Compare two implicit 4016 /// conversion sequences to determine whether one is better than the 4017 /// other or if they are indistinguishable (C++ 13.3.3.2). 4018 static ImplicitConversionSequence::CompareKind 4019 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 4020 const ImplicitConversionSequence& ICS1, 4021 const ImplicitConversionSequence& ICS2) 4022 { 4023 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 4024 // conversion sequences (as defined in 13.3.3.1) 4025 // -- a standard conversion sequence (13.3.3.1.1) is a better 4026 // conversion sequence than a user-defined conversion sequence or 4027 // an ellipsis conversion sequence, and 4028 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 4029 // conversion sequence than an ellipsis conversion sequence 4030 // (13.3.3.1.3). 4031 // 4032 // C++0x [over.best.ics]p10: 4033 // For the purpose of ranking implicit conversion sequences as 4034 // described in 13.3.3.2, the ambiguous conversion sequence is 4035 // treated as a user-defined sequence that is indistinguishable 4036 // from any other user-defined conversion sequence. 4037 4038 // String literal to 'char *' conversion has been deprecated in C++03. It has 4039 // been removed from C++11. We still accept this conversion, if it happens at 4040 // the best viable function. Otherwise, this conversion is considered worse 4041 // than ellipsis conversion. Consider this as an extension; this is not in the 4042 // standard. For example: 4043 // 4044 // int &f(...); // #1 4045 // void f(char*); // #2 4046 // void g() { int &r = f("foo"); } 4047 // 4048 // In C++03, we pick #2 as the best viable function. 4049 // In C++11, we pick #1 as the best viable function, because ellipsis 4050 // conversion is better than string-literal to char* conversion (since there 4051 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 4052 // convert arguments, #2 would be the best viable function in C++11. 4053 // If the best viable function has this conversion, a warning will be issued 4054 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 4055 4056 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 4057 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 4058 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 4059 // Ill-formedness must not differ 4060 ICS1.isBad() == ICS2.isBad()) 4061 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 4062 ? ImplicitConversionSequence::Worse 4063 : ImplicitConversionSequence::Better; 4064 4065 if (ICS1.getKindRank() < ICS2.getKindRank()) 4066 return ImplicitConversionSequence::Better; 4067 if (ICS2.getKindRank() < ICS1.getKindRank()) 4068 return ImplicitConversionSequence::Worse; 4069 4070 // The following checks require both conversion sequences to be of 4071 // the same kind. 4072 if (ICS1.getKind() != ICS2.getKind()) 4073 return ImplicitConversionSequence::Indistinguishable; 4074 4075 ImplicitConversionSequence::CompareKind Result = 4076 ImplicitConversionSequence::Indistinguishable; 4077 4078 // Two implicit conversion sequences of the same form are 4079 // indistinguishable conversion sequences unless one of the 4080 // following rules apply: (C++ 13.3.3.2p3): 4081 4082 // List-initialization sequence L1 is a better conversion sequence than 4083 // list-initialization sequence L2 if: 4084 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 4085 // if not that, 4086 // — L1 and L2 convert to arrays of the same element type, and either the 4087 // number of elements n_1 initialized by L1 is less than the number of 4088 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 4089 // an array of unknown bound and L1 does not, 4090 // even if one of the other rules in this paragraph would otherwise apply. 4091 if (!ICS1.isBad()) { 4092 bool StdInit1 = false, StdInit2 = false; 4093 if (ICS1.hasInitializerListContainerType()) 4094 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 4095 nullptr); 4096 if (ICS2.hasInitializerListContainerType()) 4097 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 4098 nullptr); 4099 if (StdInit1 != StdInit2) 4100 return StdInit1 ? ImplicitConversionSequence::Better 4101 : ImplicitConversionSequence::Worse; 4102 4103 if (ICS1.hasInitializerListContainerType() && 4104 ICS2.hasInitializerListContainerType()) 4105 if (auto *CAT1 = S.Context.getAsConstantArrayType( 4106 ICS1.getInitializerListContainerType())) 4107 if (auto *CAT2 = S.Context.getAsConstantArrayType( 4108 ICS2.getInitializerListContainerType())) { 4109 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 4110 CAT2->getElementType())) { 4111 // Both to arrays of the same element type 4112 if (CAT1->getSize() != CAT2->getSize()) 4113 // Different sized, the smaller wins 4114 return CAT1->getSize().ult(CAT2->getSize()) 4115 ? ImplicitConversionSequence::Better 4116 : ImplicitConversionSequence::Worse; 4117 if (ICS1.isInitializerListOfIncompleteArray() != 4118 ICS2.isInitializerListOfIncompleteArray()) 4119 // One is incomplete, it loses 4120 return ICS2.isInitializerListOfIncompleteArray() 4121 ? ImplicitConversionSequence::Better 4122 : ImplicitConversionSequence::Worse; 4123 } 4124 } 4125 } 4126 4127 if (ICS1.isStandard()) 4128 // Standard conversion sequence S1 is a better conversion sequence than 4129 // standard conversion sequence S2 if [...] 4130 Result = CompareStandardConversionSequences(S, Loc, 4131 ICS1.Standard, ICS2.Standard); 4132 else if (ICS1.isUserDefined()) { 4133 // User-defined conversion sequence U1 is a better conversion 4134 // sequence than another user-defined conversion sequence U2 if 4135 // they contain the same user-defined conversion function or 4136 // constructor and if the second standard conversion sequence of 4137 // U1 is better than the second standard conversion sequence of 4138 // U2 (C++ 13.3.3.2p3). 4139 if (ICS1.UserDefined.ConversionFunction == 4140 ICS2.UserDefined.ConversionFunction) 4141 Result = CompareStandardConversionSequences(S, Loc, 4142 ICS1.UserDefined.After, 4143 ICS2.UserDefined.After); 4144 else 4145 Result = compareConversionFunctions(S, 4146 ICS1.UserDefined.ConversionFunction, 4147 ICS2.UserDefined.ConversionFunction); 4148 } 4149 4150 return Result; 4151 } 4152 4153 // Per 13.3.3.2p3, compare the given standard conversion sequences to 4154 // determine if one is a proper subset of the other. 4155 static ImplicitConversionSequence::CompareKind 4156 compareStandardConversionSubsets(ASTContext &Context, 4157 const StandardConversionSequence& SCS1, 4158 const StandardConversionSequence& SCS2) { 4159 ImplicitConversionSequence::CompareKind Result 4160 = ImplicitConversionSequence::Indistinguishable; 4161 4162 // the identity conversion sequence is considered to be a subsequence of 4163 // any non-identity conversion sequence 4164 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 4165 return ImplicitConversionSequence::Better; 4166 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 4167 return ImplicitConversionSequence::Worse; 4168 4169 if (SCS1.Second != SCS2.Second) { 4170 if (SCS1.Second == ICK_Identity) 4171 Result = ImplicitConversionSequence::Better; 4172 else if (SCS2.Second == ICK_Identity) 4173 Result = ImplicitConversionSequence::Worse; 4174 else 4175 return ImplicitConversionSequence::Indistinguishable; 4176 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 4177 return ImplicitConversionSequence::Indistinguishable; 4178 4179 if (SCS1.Third == SCS2.Third) { 4180 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 4181 : ImplicitConversionSequence::Indistinguishable; 4182 } 4183 4184 if (SCS1.Third == ICK_Identity) 4185 return Result == ImplicitConversionSequence::Worse 4186 ? ImplicitConversionSequence::Indistinguishable 4187 : ImplicitConversionSequence::Better; 4188 4189 if (SCS2.Third == ICK_Identity) 4190 return Result == ImplicitConversionSequence::Better 4191 ? ImplicitConversionSequence::Indistinguishable 4192 : ImplicitConversionSequence::Worse; 4193 4194 return ImplicitConversionSequence::Indistinguishable; 4195 } 4196 4197 /// Determine whether one of the given reference bindings is better 4198 /// than the other based on what kind of bindings they are. 4199 static bool 4200 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 4201 const StandardConversionSequence &SCS2) { 4202 // C++0x [over.ics.rank]p3b4: 4203 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 4204 // implicit object parameter of a non-static member function declared 4205 // without a ref-qualifier, and *either* S1 binds an rvalue reference 4206 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 4207 // lvalue reference to a function lvalue and S2 binds an rvalue 4208 // reference*. 4209 // 4210 // FIXME: Rvalue references. We're going rogue with the above edits, 4211 // because the semantics in the current C++0x working paper (N3225 at the 4212 // time of this writing) break the standard definition of std::forward 4213 // and std::reference_wrapper when dealing with references to functions. 4214 // Proposed wording changes submitted to CWG for consideration. 4215 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 4216 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 4217 return false; 4218 4219 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 4220 SCS2.IsLvalueReference) || 4221 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 4222 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 4223 } 4224 4225 enum class FixedEnumPromotion { 4226 None, 4227 ToUnderlyingType, 4228 ToPromotedUnderlyingType 4229 }; 4230 4231 /// Returns kind of fixed enum promotion the \a SCS uses. 4232 static FixedEnumPromotion 4233 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 4234 4235 if (SCS.Second != ICK_Integral_Promotion) 4236 return FixedEnumPromotion::None; 4237 4238 QualType FromType = SCS.getFromType(); 4239 if (!FromType->isEnumeralType()) 4240 return FixedEnumPromotion::None; 4241 4242 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 4243 if (!Enum->isFixed()) 4244 return FixedEnumPromotion::None; 4245 4246 QualType UnderlyingType = Enum->getIntegerType(); 4247 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 4248 return FixedEnumPromotion::ToUnderlyingType; 4249 4250 return FixedEnumPromotion::ToPromotedUnderlyingType; 4251 } 4252 4253 /// CompareStandardConversionSequences - Compare two standard 4254 /// conversion sequences to determine whether one is better than the 4255 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 4256 static ImplicitConversionSequence::CompareKind 4257 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 4258 const StandardConversionSequence& SCS1, 4259 const StandardConversionSequence& SCS2) 4260 { 4261 // Standard conversion sequence S1 is a better conversion sequence 4262 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 4263 4264 // -- S1 is a proper subsequence of S2 (comparing the conversion 4265 // sequences in the canonical form defined by 13.3.3.1.1, 4266 // excluding any Lvalue Transformation; the identity conversion 4267 // sequence is considered to be a subsequence of any 4268 // non-identity conversion sequence) or, if not that, 4269 if (ImplicitConversionSequence::CompareKind CK 4270 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4271 return CK; 4272 4273 // -- the rank of S1 is better than the rank of S2 (by the rules 4274 // defined below), or, if not that, 4275 ImplicitConversionRank Rank1 = SCS1.getRank(); 4276 ImplicitConversionRank Rank2 = SCS2.getRank(); 4277 if (Rank1 < Rank2) 4278 return ImplicitConversionSequence::Better; 4279 else if (Rank2 < Rank1) 4280 return ImplicitConversionSequence::Worse; 4281 4282 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4283 // are indistinguishable unless one of the following rules 4284 // applies: 4285 4286 // A conversion that is not a conversion of a pointer, or 4287 // pointer to member, to bool is better than another conversion 4288 // that is such a conversion. 4289 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4290 return SCS2.isPointerConversionToBool() 4291 ? ImplicitConversionSequence::Better 4292 : ImplicitConversionSequence::Worse; 4293 4294 // C++14 [over.ics.rank]p4b2: 4295 // This is retroactively applied to C++11 by CWG 1601. 4296 // 4297 // A conversion that promotes an enumeration whose underlying type is fixed 4298 // to its underlying type is better than one that promotes to the promoted 4299 // underlying type, if the two are different. 4300 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4301 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4302 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4303 FEP1 != FEP2) 4304 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4305 ? ImplicitConversionSequence::Better 4306 : ImplicitConversionSequence::Worse; 4307 4308 // C++ [over.ics.rank]p4b2: 4309 // 4310 // If class B is derived directly or indirectly from class A, 4311 // conversion of B* to A* is better than conversion of B* to 4312 // void*, and conversion of A* to void* is better than conversion 4313 // of B* to void*. 4314 bool SCS1ConvertsToVoid 4315 = SCS1.isPointerConversionToVoidPointer(S.Context); 4316 bool SCS2ConvertsToVoid 4317 = SCS2.isPointerConversionToVoidPointer(S.Context); 4318 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4319 // Exactly one of the conversion sequences is a conversion to 4320 // a void pointer; it's the worse conversion. 4321 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4322 : ImplicitConversionSequence::Worse; 4323 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4324 // Neither conversion sequence converts to a void pointer; compare 4325 // their derived-to-base conversions. 4326 if (ImplicitConversionSequence::CompareKind DerivedCK 4327 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4328 return DerivedCK; 4329 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4330 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4331 // Both conversion sequences are conversions to void 4332 // pointers. Compare the source types to determine if there's an 4333 // inheritance relationship in their sources. 4334 QualType FromType1 = SCS1.getFromType(); 4335 QualType FromType2 = SCS2.getFromType(); 4336 4337 // Adjust the types we're converting from via the array-to-pointer 4338 // conversion, if we need to. 4339 if (SCS1.First == ICK_Array_To_Pointer) 4340 FromType1 = S.Context.getArrayDecayedType(FromType1); 4341 if (SCS2.First == ICK_Array_To_Pointer) 4342 FromType2 = S.Context.getArrayDecayedType(FromType2); 4343 4344 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4345 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4346 4347 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4348 return ImplicitConversionSequence::Better; 4349 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4350 return ImplicitConversionSequence::Worse; 4351 4352 // Objective-C++: If one interface is more specific than the 4353 // other, it is the better one. 4354 const ObjCObjectPointerType* FromObjCPtr1 4355 = FromType1->getAs<ObjCObjectPointerType>(); 4356 const ObjCObjectPointerType* FromObjCPtr2 4357 = FromType2->getAs<ObjCObjectPointerType>(); 4358 if (FromObjCPtr1 && FromObjCPtr2) { 4359 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4360 FromObjCPtr2); 4361 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4362 FromObjCPtr1); 4363 if (AssignLeft != AssignRight) { 4364 return AssignLeft? ImplicitConversionSequence::Better 4365 : ImplicitConversionSequence::Worse; 4366 } 4367 } 4368 } 4369 4370 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4371 // Check for a better reference binding based on the kind of bindings. 4372 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4373 return ImplicitConversionSequence::Better; 4374 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4375 return ImplicitConversionSequence::Worse; 4376 } 4377 4378 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4379 // bullet 3). 4380 if (ImplicitConversionSequence::CompareKind QualCK 4381 = CompareQualificationConversions(S, SCS1, SCS2)) 4382 return QualCK; 4383 4384 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4385 // C++ [over.ics.rank]p3b4: 4386 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4387 // which the references refer are the same type except for 4388 // top-level cv-qualifiers, and the type to which the reference 4389 // initialized by S2 refers is more cv-qualified than the type 4390 // to which the reference initialized by S1 refers. 4391 QualType T1 = SCS1.getToType(2); 4392 QualType T2 = SCS2.getToType(2); 4393 T1 = S.Context.getCanonicalType(T1); 4394 T2 = S.Context.getCanonicalType(T2); 4395 Qualifiers T1Quals, T2Quals; 4396 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4397 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4398 if (UnqualT1 == UnqualT2) { 4399 // Objective-C++ ARC: If the references refer to objects with different 4400 // lifetimes, prefer bindings that don't change lifetime. 4401 if (SCS1.ObjCLifetimeConversionBinding != 4402 SCS2.ObjCLifetimeConversionBinding) { 4403 return SCS1.ObjCLifetimeConversionBinding 4404 ? ImplicitConversionSequence::Worse 4405 : ImplicitConversionSequence::Better; 4406 } 4407 4408 // If the type is an array type, promote the element qualifiers to the 4409 // type for comparison. 4410 if (isa<ArrayType>(T1) && T1Quals) 4411 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4412 if (isa<ArrayType>(T2) && T2Quals) 4413 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4414 if (T2.isMoreQualifiedThan(T1)) 4415 return ImplicitConversionSequence::Better; 4416 if (T1.isMoreQualifiedThan(T2)) 4417 return ImplicitConversionSequence::Worse; 4418 } 4419 } 4420 4421 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4422 // floating-to-integral conversion if the integral conversion 4423 // is between types of the same size. 4424 // For example: 4425 // void f(float); 4426 // void f(int); 4427 // int main { 4428 // long a; 4429 // f(a); 4430 // } 4431 // Here, MSVC will call f(int) instead of generating a compile error 4432 // as clang will do in standard mode. 4433 if (S.getLangOpts().MSVCCompat && 4434 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4435 SCS1.Second == ICK_Integral_Conversion && 4436 SCS2.Second == ICK_Floating_Integral && 4437 S.Context.getTypeSize(SCS1.getFromType()) == 4438 S.Context.getTypeSize(SCS1.getToType(2))) 4439 return ImplicitConversionSequence::Better; 4440 4441 // Prefer a compatible vector conversion over a lax vector conversion 4442 // For example: 4443 // 4444 // typedef float __v4sf __attribute__((__vector_size__(16))); 4445 // void f(vector float); 4446 // void f(vector signed int); 4447 // int main() { 4448 // __v4sf a; 4449 // f(a); 4450 // } 4451 // Here, we'd like to choose f(vector float) and not 4452 // report an ambiguous call error 4453 if (SCS1.Second == ICK_Vector_Conversion && 4454 SCS2.Second == ICK_Vector_Conversion) { 4455 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4456 SCS1.getFromType(), SCS1.getToType(2)); 4457 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4458 SCS2.getFromType(), SCS2.getToType(2)); 4459 4460 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4461 return SCS1IsCompatibleVectorConversion 4462 ? ImplicitConversionSequence::Better 4463 : ImplicitConversionSequence::Worse; 4464 } 4465 4466 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4467 SCS2.Second == ICK_SVE_Vector_Conversion) { 4468 bool SCS1IsCompatibleSVEVectorConversion = 4469 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4470 bool SCS2IsCompatibleSVEVectorConversion = 4471 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4472 4473 if (SCS1IsCompatibleSVEVectorConversion != 4474 SCS2IsCompatibleSVEVectorConversion) 4475 return SCS1IsCompatibleSVEVectorConversion 4476 ? ImplicitConversionSequence::Better 4477 : ImplicitConversionSequence::Worse; 4478 } 4479 4480 if (SCS1.Second == ICK_RVV_Vector_Conversion && 4481 SCS2.Second == ICK_RVV_Vector_Conversion) { 4482 bool SCS1IsCompatibleRVVVectorConversion = 4483 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2)); 4484 bool SCS2IsCompatibleRVVVectorConversion = 4485 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2)); 4486 4487 if (SCS1IsCompatibleRVVVectorConversion != 4488 SCS2IsCompatibleRVVVectorConversion) 4489 return SCS1IsCompatibleRVVVectorConversion 4490 ? ImplicitConversionSequence::Better 4491 : ImplicitConversionSequence::Worse; 4492 } 4493 4494 return ImplicitConversionSequence::Indistinguishable; 4495 } 4496 4497 /// CompareQualificationConversions - Compares two standard conversion 4498 /// sequences to determine whether they can be ranked based on their 4499 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4500 static ImplicitConversionSequence::CompareKind 4501 CompareQualificationConversions(Sema &S, 4502 const StandardConversionSequence& SCS1, 4503 const StandardConversionSequence& SCS2) { 4504 // C++ [over.ics.rank]p3: 4505 // -- S1 and S2 differ only in their qualification conversion and 4506 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4507 // [C++98] 4508 // [...] and the cv-qualification signature of type T1 is a proper subset 4509 // of the cv-qualification signature of type T2, and S1 is not the 4510 // deprecated string literal array-to-pointer conversion (4.2). 4511 // [C++2a] 4512 // [...] where T1 can be converted to T2 by a qualification conversion. 4513 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4514 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4515 return ImplicitConversionSequence::Indistinguishable; 4516 4517 // FIXME: the example in the standard doesn't use a qualification 4518 // conversion (!) 4519 QualType T1 = SCS1.getToType(2); 4520 QualType T2 = SCS2.getToType(2); 4521 T1 = S.Context.getCanonicalType(T1); 4522 T2 = S.Context.getCanonicalType(T2); 4523 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4524 Qualifiers T1Quals, T2Quals; 4525 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4526 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4527 4528 // If the types are the same, we won't learn anything by unwrapping 4529 // them. 4530 if (UnqualT1 == UnqualT2) 4531 return ImplicitConversionSequence::Indistinguishable; 4532 4533 // Don't ever prefer a standard conversion sequence that uses the deprecated 4534 // string literal array to pointer conversion. 4535 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4536 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4537 4538 // Objective-C++ ARC: 4539 // Prefer qualification conversions not involving a change in lifetime 4540 // to qualification conversions that do change lifetime. 4541 if (SCS1.QualificationIncludesObjCLifetime && 4542 !SCS2.QualificationIncludesObjCLifetime) 4543 CanPick1 = false; 4544 if (SCS2.QualificationIncludesObjCLifetime && 4545 !SCS1.QualificationIncludesObjCLifetime) 4546 CanPick2 = false; 4547 4548 bool ObjCLifetimeConversion; 4549 if (CanPick1 && 4550 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4551 CanPick1 = false; 4552 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4553 // directions, so we can't short-cut this second check in general. 4554 if (CanPick2 && 4555 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4556 CanPick2 = false; 4557 4558 if (CanPick1 != CanPick2) 4559 return CanPick1 ? ImplicitConversionSequence::Better 4560 : ImplicitConversionSequence::Worse; 4561 return ImplicitConversionSequence::Indistinguishable; 4562 } 4563 4564 /// CompareDerivedToBaseConversions - Compares two standard conversion 4565 /// sequences to determine whether they can be ranked based on their 4566 /// various kinds of derived-to-base conversions (C++ 4567 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4568 /// conversions between Objective-C interface types. 4569 static ImplicitConversionSequence::CompareKind 4570 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4571 const StandardConversionSequence& SCS1, 4572 const StandardConversionSequence& SCS2) { 4573 QualType FromType1 = SCS1.getFromType(); 4574 QualType ToType1 = SCS1.getToType(1); 4575 QualType FromType2 = SCS2.getFromType(); 4576 QualType ToType2 = SCS2.getToType(1); 4577 4578 // Adjust the types we're converting from via the array-to-pointer 4579 // conversion, if we need to. 4580 if (SCS1.First == ICK_Array_To_Pointer) 4581 FromType1 = S.Context.getArrayDecayedType(FromType1); 4582 if (SCS2.First == ICK_Array_To_Pointer) 4583 FromType2 = S.Context.getArrayDecayedType(FromType2); 4584 4585 // Canonicalize all of the types. 4586 FromType1 = S.Context.getCanonicalType(FromType1); 4587 ToType1 = S.Context.getCanonicalType(ToType1); 4588 FromType2 = S.Context.getCanonicalType(FromType2); 4589 ToType2 = S.Context.getCanonicalType(ToType2); 4590 4591 // C++ [over.ics.rank]p4b3: 4592 // 4593 // If class B is derived directly or indirectly from class A and 4594 // class C is derived directly or indirectly from B, 4595 // 4596 // Compare based on pointer conversions. 4597 if (SCS1.Second == ICK_Pointer_Conversion && 4598 SCS2.Second == ICK_Pointer_Conversion && 4599 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4600 FromType1->isPointerType() && FromType2->isPointerType() && 4601 ToType1->isPointerType() && ToType2->isPointerType()) { 4602 QualType FromPointee1 = 4603 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4604 QualType ToPointee1 = 4605 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4606 QualType FromPointee2 = 4607 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4608 QualType ToPointee2 = 4609 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4610 4611 // -- conversion of C* to B* is better than conversion of C* to A*, 4612 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4613 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4614 return ImplicitConversionSequence::Better; 4615 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4616 return ImplicitConversionSequence::Worse; 4617 } 4618 4619 // -- conversion of B* to A* is better than conversion of C* to A*, 4620 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4621 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4622 return ImplicitConversionSequence::Better; 4623 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4624 return ImplicitConversionSequence::Worse; 4625 } 4626 } else if (SCS1.Second == ICK_Pointer_Conversion && 4627 SCS2.Second == ICK_Pointer_Conversion) { 4628 const ObjCObjectPointerType *FromPtr1 4629 = FromType1->getAs<ObjCObjectPointerType>(); 4630 const ObjCObjectPointerType *FromPtr2 4631 = FromType2->getAs<ObjCObjectPointerType>(); 4632 const ObjCObjectPointerType *ToPtr1 4633 = ToType1->getAs<ObjCObjectPointerType>(); 4634 const ObjCObjectPointerType *ToPtr2 4635 = ToType2->getAs<ObjCObjectPointerType>(); 4636 4637 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4638 // Apply the same conversion ranking rules for Objective-C pointer types 4639 // that we do for C++ pointers to class types. However, we employ the 4640 // Objective-C pseudo-subtyping relationship used for assignment of 4641 // Objective-C pointer types. 4642 bool FromAssignLeft 4643 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4644 bool FromAssignRight 4645 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4646 bool ToAssignLeft 4647 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4648 bool ToAssignRight 4649 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4650 4651 // A conversion to an a non-id object pointer type or qualified 'id' 4652 // type is better than a conversion to 'id'. 4653 if (ToPtr1->isObjCIdType() && 4654 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4655 return ImplicitConversionSequence::Worse; 4656 if (ToPtr2->isObjCIdType() && 4657 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4658 return ImplicitConversionSequence::Better; 4659 4660 // A conversion to a non-id object pointer type is better than a 4661 // conversion to a qualified 'id' type 4662 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4663 return ImplicitConversionSequence::Worse; 4664 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4665 return ImplicitConversionSequence::Better; 4666 4667 // A conversion to an a non-Class object pointer type or qualified 'Class' 4668 // type is better than a conversion to 'Class'. 4669 if (ToPtr1->isObjCClassType() && 4670 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4671 return ImplicitConversionSequence::Worse; 4672 if (ToPtr2->isObjCClassType() && 4673 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4674 return ImplicitConversionSequence::Better; 4675 4676 // A conversion to a non-Class object pointer type is better than a 4677 // conversion to a qualified 'Class' type. 4678 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4679 return ImplicitConversionSequence::Worse; 4680 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4681 return ImplicitConversionSequence::Better; 4682 4683 // -- "conversion of C* to B* is better than conversion of C* to A*," 4684 if (S.Context.hasSameType(FromType1, FromType2) && 4685 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4686 (ToAssignLeft != ToAssignRight)) { 4687 if (FromPtr1->isSpecialized()) { 4688 // "conversion of B<A> * to B * is better than conversion of B * to 4689 // C *. 4690 bool IsFirstSame = 4691 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4692 bool IsSecondSame = 4693 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4694 if (IsFirstSame) { 4695 if (!IsSecondSame) 4696 return ImplicitConversionSequence::Better; 4697 } else if (IsSecondSame) 4698 return ImplicitConversionSequence::Worse; 4699 } 4700 return ToAssignLeft? ImplicitConversionSequence::Worse 4701 : ImplicitConversionSequence::Better; 4702 } 4703 4704 // -- "conversion of B* to A* is better than conversion of C* to A*," 4705 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4706 (FromAssignLeft != FromAssignRight)) 4707 return FromAssignLeft? ImplicitConversionSequence::Better 4708 : ImplicitConversionSequence::Worse; 4709 } 4710 } 4711 4712 // Ranking of member-pointer types. 4713 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4714 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4715 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4716 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4717 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4718 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4719 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4720 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4721 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4722 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4723 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4724 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4725 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4726 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4727 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4728 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4729 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4730 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4731 return ImplicitConversionSequence::Worse; 4732 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4733 return ImplicitConversionSequence::Better; 4734 } 4735 // conversion of B::* to C::* is better than conversion of A::* to C::* 4736 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4737 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4738 return ImplicitConversionSequence::Better; 4739 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4740 return ImplicitConversionSequence::Worse; 4741 } 4742 } 4743 4744 if (SCS1.Second == ICK_Derived_To_Base) { 4745 // -- conversion of C to B is better than conversion of C to A, 4746 // -- binding of an expression of type C to a reference of type 4747 // B& is better than binding an expression of type C to a 4748 // reference of type A&, 4749 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4750 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4751 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4752 return ImplicitConversionSequence::Better; 4753 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4754 return ImplicitConversionSequence::Worse; 4755 } 4756 4757 // -- conversion of B to A is better than conversion of C to A. 4758 // -- binding of an expression of type B to a reference of type 4759 // A& is better than binding an expression of type C to a 4760 // reference of type A&, 4761 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4762 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4763 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4764 return ImplicitConversionSequence::Better; 4765 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4766 return ImplicitConversionSequence::Worse; 4767 } 4768 } 4769 4770 return ImplicitConversionSequence::Indistinguishable; 4771 } 4772 4773 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4774 if (!T.getQualifiers().hasUnaligned()) 4775 return T; 4776 4777 Qualifiers Q; 4778 T = Ctx.getUnqualifiedArrayType(T, Q); 4779 Q.removeUnaligned(); 4780 return Ctx.getQualifiedType(T, Q); 4781 } 4782 4783 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4784 /// determine whether they are reference-compatible, 4785 /// reference-related, or incompatible, for use in C++ initialization by 4786 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4787 /// type, and the first type (T1) is the pointee type of the reference 4788 /// type being initialized. 4789 Sema::ReferenceCompareResult 4790 Sema::CompareReferenceRelationship(SourceLocation Loc, 4791 QualType OrigT1, QualType OrigT2, 4792 ReferenceConversions *ConvOut) { 4793 assert(!OrigT1->isReferenceType() && 4794 "T1 must be the pointee type of the reference type"); 4795 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4796 4797 QualType T1 = Context.getCanonicalType(OrigT1); 4798 QualType T2 = Context.getCanonicalType(OrigT2); 4799 Qualifiers T1Quals, T2Quals; 4800 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4801 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4802 4803 ReferenceConversions ConvTmp; 4804 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4805 Conv = ReferenceConversions(); 4806 4807 // C++2a [dcl.init.ref]p4: 4808 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4809 // reference-related to "cv2 T2" if T1 is similar to T2, or 4810 // T1 is a base class of T2. 4811 // "cv1 T1" is reference-compatible with "cv2 T2" if 4812 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4813 // "pointer to cv1 T1" via a standard conversion sequence. 4814 4815 // Check for standard conversions we can apply to pointers: derived-to-base 4816 // conversions, ObjC pointer conversions, and function pointer conversions. 4817 // (Qualification conversions are checked last.) 4818 QualType ConvertedT2; 4819 if (UnqualT1 == UnqualT2) { 4820 // Nothing to do. 4821 } else if (isCompleteType(Loc, OrigT2) && 4822 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4823 Conv |= ReferenceConversions::DerivedToBase; 4824 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4825 UnqualT2->isObjCObjectOrInterfaceType() && 4826 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4827 Conv |= ReferenceConversions::ObjC; 4828 else if (UnqualT2->isFunctionType() && 4829 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4830 Conv |= ReferenceConversions::Function; 4831 // No need to check qualifiers; function types don't have them. 4832 return Ref_Compatible; 4833 } 4834 bool ConvertedReferent = Conv != 0; 4835 4836 // We can have a qualification conversion. Compute whether the types are 4837 // similar at the same time. 4838 bool PreviousToQualsIncludeConst = true; 4839 bool TopLevel = true; 4840 do { 4841 if (T1 == T2) 4842 break; 4843 4844 // We will need a qualification conversion. 4845 Conv |= ReferenceConversions::Qualification; 4846 4847 // Track whether we performed a qualification conversion anywhere other 4848 // than the top level. This matters for ranking reference bindings in 4849 // overload resolution. 4850 if (!TopLevel) 4851 Conv |= ReferenceConversions::NestedQualification; 4852 4853 // MS compiler ignores __unaligned qualifier for references; do the same. 4854 T1 = withoutUnaligned(Context, T1); 4855 T2 = withoutUnaligned(Context, T2); 4856 4857 // If we find a qualifier mismatch, the types are not reference-compatible, 4858 // but are still be reference-related if they're similar. 4859 bool ObjCLifetimeConversion = false; 4860 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4861 PreviousToQualsIncludeConst, 4862 ObjCLifetimeConversion)) 4863 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4864 ? Ref_Related 4865 : Ref_Incompatible; 4866 4867 // FIXME: Should we track this for any level other than the first? 4868 if (ObjCLifetimeConversion) 4869 Conv |= ReferenceConversions::ObjCLifetime; 4870 4871 TopLevel = false; 4872 } while (Context.UnwrapSimilarTypes(T1, T2)); 4873 4874 // At this point, if the types are reference-related, we must either have the 4875 // same inner type (ignoring qualifiers), or must have already worked out how 4876 // to convert the referent. 4877 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4878 ? Ref_Compatible 4879 : Ref_Incompatible; 4880 } 4881 4882 /// Look for a user-defined conversion to a value reference-compatible 4883 /// with DeclType. Return true if something definite is found. 4884 static bool 4885 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4886 QualType DeclType, SourceLocation DeclLoc, 4887 Expr *Init, QualType T2, bool AllowRvalues, 4888 bool AllowExplicit) { 4889 assert(T2->isRecordType() && "Can only find conversions of record types."); 4890 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4891 4892 OverloadCandidateSet CandidateSet( 4893 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4894 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4895 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4896 NamedDecl *D = *I; 4897 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4898 if (isa<UsingShadowDecl>(D)) 4899 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4900 4901 FunctionTemplateDecl *ConvTemplate 4902 = dyn_cast<FunctionTemplateDecl>(D); 4903 CXXConversionDecl *Conv; 4904 if (ConvTemplate) 4905 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4906 else 4907 Conv = cast<CXXConversionDecl>(D); 4908 4909 if (AllowRvalues) { 4910 // If we are initializing an rvalue reference, don't permit conversion 4911 // functions that return lvalues. 4912 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4913 const ReferenceType *RefType 4914 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4915 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4916 continue; 4917 } 4918 4919 if (!ConvTemplate && 4920 S.CompareReferenceRelationship( 4921 DeclLoc, 4922 Conv->getConversionType() 4923 .getNonReferenceType() 4924 .getUnqualifiedType(), 4925 DeclType.getNonReferenceType().getUnqualifiedType()) == 4926 Sema::Ref_Incompatible) 4927 continue; 4928 } else { 4929 // If the conversion function doesn't return a reference type, 4930 // it can't be considered for this conversion. An rvalue reference 4931 // is only acceptable if its referencee is a function type. 4932 4933 const ReferenceType *RefType = 4934 Conv->getConversionType()->getAs<ReferenceType>(); 4935 if (!RefType || 4936 (!RefType->isLValueReferenceType() && 4937 !RefType->getPointeeType()->isFunctionType())) 4938 continue; 4939 } 4940 4941 if (ConvTemplate) 4942 S.AddTemplateConversionCandidate( 4943 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4944 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4945 else 4946 S.AddConversionCandidate( 4947 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4948 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4949 } 4950 4951 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4952 4953 OverloadCandidateSet::iterator Best; 4954 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4955 case OR_Success: 4956 // C++ [over.ics.ref]p1: 4957 // 4958 // [...] If the parameter binds directly to the result of 4959 // applying a conversion function to the argument 4960 // expression, the implicit conversion sequence is a 4961 // user-defined conversion sequence (13.3.3.1.2), with the 4962 // second standard conversion sequence either an identity 4963 // conversion or, if the conversion function returns an 4964 // entity of a type that is a derived class of the parameter 4965 // type, a derived-to-base Conversion. 4966 if (!Best->FinalConversion.DirectBinding) 4967 return false; 4968 4969 ICS.setUserDefined(); 4970 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4971 ICS.UserDefined.After = Best->FinalConversion; 4972 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4973 ICS.UserDefined.ConversionFunction = Best->Function; 4974 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4975 ICS.UserDefined.EllipsisConversion = false; 4976 assert(ICS.UserDefined.After.ReferenceBinding && 4977 ICS.UserDefined.After.DirectBinding && 4978 "Expected a direct reference binding!"); 4979 return true; 4980 4981 case OR_Ambiguous: 4982 ICS.setAmbiguous(); 4983 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4984 Cand != CandidateSet.end(); ++Cand) 4985 if (Cand->Best) 4986 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4987 return true; 4988 4989 case OR_No_Viable_Function: 4990 case OR_Deleted: 4991 // There was no suitable conversion, or we found a deleted 4992 // conversion; continue with other checks. 4993 return false; 4994 } 4995 4996 llvm_unreachable("Invalid OverloadResult!"); 4997 } 4998 4999 /// Compute an implicit conversion sequence for reference 5000 /// initialization. 5001 static ImplicitConversionSequence 5002 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 5003 SourceLocation DeclLoc, 5004 bool SuppressUserConversions, 5005 bool AllowExplicit) { 5006 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 5007 5008 // Most paths end in a failed conversion. 5009 ImplicitConversionSequence ICS; 5010 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5011 5012 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 5013 QualType T2 = Init->getType(); 5014 5015 // If the initializer is the address of an overloaded function, try 5016 // to resolve the overloaded function. If all goes well, T2 is the 5017 // type of the resulting function. 5018 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5019 DeclAccessPair Found; 5020 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 5021 false, Found)) 5022 T2 = Fn->getType(); 5023 } 5024 5025 // Compute some basic properties of the types and the initializer. 5026 bool isRValRef = DeclType->isRValueReferenceType(); 5027 Expr::Classification InitCategory = Init->Classify(S.Context); 5028 5029 Sema::ReferenceConversions RefConv; 5030 Sema::ReferenceCompareResult RefRelationship = 5031 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 5032 5033 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 5034 ICS.setStandard(); 5035 ICS.Standard.First = ICK_Identity; 5036 // FIXME: A reference binding can be a function conversion too. We should 5037 // consider that when ordering reference-to-function bindings. 5038 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 5039 ? ICK_Derived_To_Base 5040 : (RefConv & Sema::ReferenceConversions::ObjC) 5041 ? ICK_Compatible_Conversion 5042 : ICK_Identity; 5043 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 5044 // a reference binding that performs a non-top-level qualification 5045 // conversion as a qualification conversion, not as an identity conversion. 5046 ICS.Standard.Third = (RefConv & 5047 Sema::ReferenceConversions::NestedQualification) 5048 ? ICK_Qualification 5049 : ICK_Identity; 5050 ICS.Standard.setFromType(T2); 5051 ICS.Standard.setToType(0, T2); 5052 ICS.Standard.setToType(1, T1); 5053 ICS.Standard.setToType(2, T1); 5054 ICS.Standard.ReferenceBinding = true; 5055 ICS.Standard.DirectBinding = BindsDirectly; 5056 ICS.Standard.IsLvalueReference = !isRValRef; 5057 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 5058 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 5059 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5060 ICS.Standard.ObjCLifetimeConversionBinding = 5061 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 5062 ICS.Standard.CopyConstructor = nullptr; 5063 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 5064 }; 5065 5066 // C++0x [dcl.init.ref]p5: 5067 // A reference to type "cv1 T1" is initialized by an expression 5068 // of type "cv2 T2" as follows: 5069 5070 // -- If reference is an lvalue reference and the initializer expression 5071 if (!isRValRef) { 5072 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 5073 // reference-compatible with "cv2 T2," or 5074 // 5075 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 5076 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 5077 // C++ [over.ics.ref]p1: 5078 // When a parameter of reference type binds directly (8.5.3) 5079 // to an argument expression, the implicit conversion sequence 5080 // is the identity conversion, unless the argument expression 5081 // has a type that is a derived class of the parameter type, 5082 // in which case the implicit conversion sequence is a 5083 // derived-to-base Conversion (13.3.3.1). 5084 SetAsReferenceBinding(/*BindsDirectly=*/true); 5085 5086 // Nothing more to do: the inaccessibility/ambiguity check for 5087 // derived-to-base conversions is suppressed when we're 5088 // computing the implicit conversion sequence (C++ 5089 // [over.best.ics]p2). 5090 return ICS; 5091 } 5092 5093 // -- has a class type (i.e., T2 is a class type), where T1 is 5094 // not reference-related to T2, and can be implicitly 5095 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 5096 // is reference-compatible with "cv3 T3" 92) (this 5097 // conversion is selected by enumerating the applicable 5098 // conversion functions (13.3.1.6) and choosing the best 5099 // one through overload resolution (13.3)), 5100 if (!SuppressUserConversions && T2->isRecordType() && 5101 S.isCompleteType(DeclLoc, T2) && 5102 RefRelationship == Sema::Ref_Incompatible) { 5103 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 5104 Init, T2, /*AllowRvalues=*/false, 5105 AllowExplicit)) 5106 return ICS; 5107 } 5108 } 5109 5110 // -- Otherwise, the reference shall be an lvalue reference to a 5111 // non-volatile const type (i.e., cv1 shall be const), or the reference 5112 // shall be an rvalue reference. 5113 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 5114 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 5115 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 5116 return ICS; 5117 } 5118 5119 // -- If the initializer expression 5120 // 5121 // -- is an xvalue, class prvalue, array prvalue or function 5122 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 5123 if (RefRelationship == Sema::Ref_Compatible && 5124 (InitCategory.isXValue() || 5125 (InitCategory.isPRValue() && 5126 (T2->isRecordType() || T2->isArrayType())) || 5127 (InitCategory.isLValue() && T2->isFunctionType()))) { 5128 // In C++11, this is always a direct binding. In C++98/03, it's a direct 5129 // binding unless we're binding to a class prvalue. 5130 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 5131 // allow the use of rvalue references in C++98/03 for the benefit of 5132 // standard library implementors; therefore, we need the xvalue check here. 5133 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 5134 !(InitCategory.isPRValue() || T2->isRecordType())); 5135 return ICS; 5136 } 5137 5138 // -- has a class type (i.e., T2 is a class type), where T1 is not 5139 // reference-related to T2, and can be implicitly converted to 5140 // an xvalue, class prvalue, or function lvalue of type 5141 // "cv3 T3", where "cv1 T1" is reference-compatible with 5142 // "cv3 T3", 5143 // 5144 // then the reference is bound to the value of the initializer 5145 // expression in the first case and to the result of the conversion 5146 // in the second case (or, in either case, to an appropriate base 5147 // class subobject). 5148 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5149 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 5150 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 5151 Init, T2, /*AllowRvalues=*/true, 5152 AllowExplicit)) { 5153 // In the second case, if the reference is an rvalue reference 5154 // and the second standard conversion sequence of the 5155 // user-defined conversion sequence includes an lvalue-to-rvalue 5156 // conversion, the program is ill-formed. 5157 if (ICS.isUserDefined() && isRValRef && 5158 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 5159 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5160 5161 return ICS; 5162 } 5163 5164 // A temporary of function type cannot be created; don't even try. 5165 if (T1->isFunctionType()) 5166 return ICS; 5167 5168 // -- Otherwise, a temporary of type "cv1 T1" is created and 5169 // initialized from the initializer expression using the 5170 // rules for a non-reference copy initialization (8.5). The 5171 // reference is then bound to the temporary. If T1 is 5172 // reference-related to T2, cv1 must be the same 5173 // cv-qualification as, or greater cv-qualification than, 5174 // cv2; otherwise, the program is ill-formed. 5175 if (RefRelationship == Sema::Ref_Related) { 5176 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 5177 // we would be reference-compatible or reference-compatible with 5178 // added qualification. But that wasn't the case, so the reference 5179 // initialization fails. 5180 // 5181 // Note that we only want to check address spaces and cvr-qualifiers here. 5182 // ObjC GC, lifetime and unaligned qualifiers aren't important. 5183 Qualifiers T1Quals = T1.getQualifiers(); 5184 Qualifiers T2Quals = T2.getQualifiers(); 5185 T1Quals.removeObjCGCAttr(); 5186 T1Quals.removeObjCLifetime(); 5187 T2Quals.removeObjCGCAttr(); 5188 T2Quals.removeObjCLifetime(); 5189 // MS compiler ignores __unaligned qualifier for references; do the same. 5190 T1Quals.removeUnaligned(); 5191 T2Quals.removeUnaligned(); 5192 if (!T1Quals.compatiblyIncludes(T2Quals)) 5193 return ICS; 5194 } 5195 5196 // If at least one of the types is a class type, the types are not 5197 // related, and we aren't allowed any user conversions, the 5198 // reference binding fails. This case is important for breaking 5199 // recursion, since TryImplicitConversion below will attempt to 5200 // create a temporary through the use of a copy constructor. 5201 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5202 (T1->isRecordType() || T2->isRecordType())) 5203 return ICS; 5204 5205 // If T1 is reference-related to T2 and the reference is an rvalue 5206 // reference, the initializer expression shall not be an lvalue. 5207 if (RefRelationship >= Sema::Ref_Related && isRValRef && 5208 Init->Classify(S.Context).isLValue()) { 5209 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 5210 return ICS; 5211 } 5212 5213 // C++ [over.ics.ref]p2: 5214 // When a parameter of reference type is not bound directly to 5215 // an argument expression, the conversion sequence is the one 5216 // required to convert the argument expression to the 5217 // underlying type of the reference according to 5218 // 13.3.3.1. Conceptually, this conversion sequence corresponds 5219 // to copy-initializing a temporary of the underlying type with 5220 // the argument expression. Any difference in top-level 5221 // cv-qualification is subsumed by the initialization itself 5222 // and does not constitute a conversion. 5223 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 5224 AllowedExplicit::None, 5225 /*InOverloadResolution=*/false, 5226 /*CStyle=*/false, 5227 /*AllowObjCWritebackConversion=*/false, 5228 /*AllowObjCConversionOnExplicit=*/false); 5229 5230 // Of course, that's still a reference binding. 5231 if (ICS.isStandard()) { 5232 ICS.Standard.ReferenceBinding = true; 5233 ICS.Standard.IsLvalueReference = !isRValRef; 5234 ICS.Standard.BindsToFunctionLvalue = false; 5235 ICS.Standard.BindsToRvalue = true; 5236 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5237 ICS.Standard.ObjCLifetimeConversionBinding = false; 5238 } else if (ICS.isUserDefined()) { 5239 const ReferenceType *LValRefType = 5240 ICS.UserDefined.ConversionFunction->getReturnType() 5241 ->getAs<LValueReferenceType>(); 5242 5243 // C++ [over.ics.ref]p3: 5244 // Except for an implicit object parameter, for which see 13.3.1, a 5245 // standard conversion sequence cannot be formed if it requires [...] 5246 // binding an rvalue reference to an lvalue other than a function 5247 // lvalue. 5248 // Note that the function case is not possible here. 5249 if (isRValRef && LValRefType) { 5250 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5251 return ICS; 5252 } 5253 5254 ICS.UserDefined.After.ReferenceBinding = true; 5255 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 5256 ICS.UserDefined.After.BindsToFunctionLvalue = false; 5257 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 5258 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5259 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 5260 } 5261 5262 return ICS; 5263 } 5264 5265 static ImplicitConversionSequence 5266 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5267 bool SuppressUserConversions, 5268 bool InOverloadResolution, 5269 bool AllowObjCWritebackConversion, 5270 bool AllowExplicit = false); 5271 5272 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5273 /// initializer list From. 5274 static ImplicitConversionSequence 5275 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5276 bool SuppressUserConversions, 5277 bool InOverloadResolution, 5278 bool AllowObjCWritebackConversion) { 5279 // C++11 [over.ics.list]p1: 5280 // When an argument is an initializer list, it is not an expression and 5281 // special rules apply for converting it to a parameter type. 5282 5283 ImplicitConversionSequence Result; 5284 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5285 5286 // We need a complete type for what follows. With one C++20 exception, 5287 // incomplete types can never be initialized from init lists. 5288 QualType InitTy = ToType; 5289 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5290 if (AT && S.getLangOpts().CPlusPlus20) 5291 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5292 // C++20 allows list initialization of an incomplete array type. 5293 InitTy = IAT->getElementType(); 5294 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5295 return Result; 5296 5297 // C++20 [over.ics.list]/2: 5298 // If the initializer list is a designated-initializer-list, a conversion 5299 // is only possible if the parameter has an aggregate type 5300 // 5301 // FIXME: The exception for reference initialization here is not part of the 5302 // language rules, but follow other compilers in adding it as a tentative DR 5303 // resolution. 5304 bool IsDesignatedInit = From->hasDesignatedInit(); 5305 if (!ToType->isAggregateType() && !ToType->isReferenceType() && 5306 IsDesignatedInit) 5307 return Result; 5308 5309 // Per DR1467: 5310 // If the parameter type is a class X and the initializer list has a single 5311 // element of type cv U, where U is X or a class derived from X, the 5312 // implicit conversion sequence is the one required to convert the element 5313 // to the parameter type. 5314 // 5315 // Otherwise, if the parameter type is a character array [... ] 5316 // and the initializer list has a single element that is an 5317 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5318 // implicit conversion sequence is the identity conversion. 5319 if (From->getNumInits() == 1 && !IsDesignatedInit) { 5320 if (ToType->isRecordType()) { 5321 QualType InitType = From->getInit(0)->getType(); 5322 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5323 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5324 return TryCopyInitialization(S, From->getInit(0), ToType, 5325 SuppressUserConversions, 5326 InOverloadResolution, 5327 AllowObjCWritebackConversion); 5328 } 5329 5330 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5331 InitializedEntity Entity = 5332 InitializedEntity::InitializeParameter(S.Context, ToType, 5333 /*Consumed=*/false); 5334 if (S.CanPerformCopyInitialization(Entity, From)) { 5335 Result.setStandard(); 5336 Result.Standard.setAsIdentityConversion(); 5337 Result.Standard.setFromType(ToType); 5338 Result.Standard.setAllToTypes(ToType); 5339 return Result; 5340 } 5341 } 5342 } 5343 5344 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5345 // C++11 [over.ics.list]p2: 5346 // If the parameter type is std::initializer_list<X> or "array of X" and 5347 // all the elements can be implicitly converted to X, the implicit 5348 // conversion sequence is the worst conversion necessary to convert an 5349 // element of the list to X. 5350 // 5351 // C++14 [over.ics.list]p3: 5352 // Otherwise, if the parameter type is "array of N X", if the initializer 5353 // list has exactly N elements or if it has fewer than N elements and X is 5354 // default-constructible, and if all the elements of the initializer list 5355 // can be implicitly converted to X, the implicit conversion sequence is 5356 // the worst conversion necessary to convert an element of the list to X. 5357 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) { 5358 unsigned e = From->getNumInits(); 5359 ImplicitConversionSequence DfltElt; 5360 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5361 QualType()); 5362 QualType ContTy = ToType; 5363 bool IsUnbounded = false; 5364 if (AT) { 5365 InitTy = AT->getElementType(); 5366 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5367 if (CT->getSize().ult(e)) { 5368 // Too many inits, fatally bad 5369 Result.setBad(BadConversionSequence::too_many_initializers, From, 5370 ToType); 5371 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5372 return Result; 5373 } 5374 if (CT->getSize().ugt(e)) { 5375 // Need an init from empty {}, is there one? 5376 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt, 5377 From->getEndLoc()); 5378 EmptyList.setType(S.Context.VoidTy); 5379 DfltElt = TryListConversion( 5380 S, &EmptyList, InitTy, SuppressUserConversions, 5381 InOverloadResolution, AllowObjCWritebackConversion); 5382 if (DfltElt.isBad()) { 5383 // No {} init, fatally bad 5384 Result.setBad(BadConversionSequence::too_few_initializers, From, 5385 ToType); 5386 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5387 return Result; 5388 } 5389 } 5390 } else { 5391 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5392 IsUnbounded = true; 5393 if (!e) { 5394 // Cannot convert to zero-sized. 5395 Result.setBad(BadConversionSequence::too_few_initializers, From, 5396 ToType); 5397 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5398 return Result; 5399 } 5400 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5401 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5402 ArraySizeModifier::Normal, 0); 5403 } 5404 } 5405 5406 Result.setStandard(); 5407 Result.Standard.setAsIdentityConversion(); 5408 Result.Standard.setFromType(InitTy); 5409 Result.Standard.setAllToTypes(InitTy); 5410 for (unsigned i = 0; i < e; ++i) { 5411 Expr *Init = From->getInit(i); 5412 ImplicitConversionSequence ICS = TryCopyInitialization( 5413 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5414 AllowObjCWritebackConversion); 5415 5416 // Keep the worse conversion seen so far. 5417 // FIXME: Sequences are not totally ordered, so 'worse' can be 5418 // ambiguous. CWG has been informed. 5419 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5420 Result) == 5421 ImplicitConversionSequence::Worse) { 5422 Result = ICS; 5423 // Bail as soon as we find something unconvertible. 5424 if (Result.isBad()) { 5425 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5426 return Result; 5427 } 5428 } 5429 } 5430 5431 // If we needed any implicit {} initialization, compare that now. 5432 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5433 // has been informed that this might not be the best thing. 5434 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5435 S, From->getEndLoc(), DfltElt, Result) == 5436 ImplicitConversionSequence::Worse) 5437 Result = DfltElt; 5438 // Record the type being initialized so that we may compare sequences 5439 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5440 return Result; 5441 } 5442 5443 // C++14 [over.ics.list]p4: 5444 // C++11 [over.ics.list]p3: 5445 // Otherwise, if the parameter is a non-aggregate class X and overload 5446 // resolution chooses a single best constructor [...] the implicit 5447 // conversion sequence is a user-defined conversion sequence. If multiple 5448 // constructors are viable but none is better than the others, the 5449 // implicit conversion sequence is a user-defined conversion sequence. 5450 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5451 // This function can deal with initializer lists. 5452 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5453 AllowedExplicit::None, 5454 InOverloadResolution, /*CStyle=*/false, 5455 AllowObjCWritebackConversion, 5456 /*AllowObjCConversionOnExplicit=*/false); 5457 } 5458 5459 // C++14 [over.ics.list]p5: 5460 // C++11 [over.ics.list]p4: 5461 // Otherwise, if the parameter has an aggregate type which can be 5462 // initialized from the initializer list [...] the implicit conversion 5463 // sequence is a user-defined conversion sequence. 5464 if (ToType->isAggregateType()) { 5465 // Type is an aggregate, argument is an init list. At this point it comes 5466 // down to checking whether the initialization works. 5467 // FIXME: Find out whether this parameter is consumed or not. 5468 InitializedEntity Entity = 5469 InitializedEntity::InitializeParameter(S.Context, ToType, 5470 /*Consumed=*/false); 5471 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5472 From)) { 5473 Result.setUserDefined(); 5474 Result.UserDefined.Before.setAsIdentityConversion(); 5475 // Initializer lists don't have a type. 5476 Result.UserDefined.Before.setFromType(QualType()); 5477 Result.UserDefined.Before.setAllToTypes(QualType()); 5478 5479 Result.UserDefined.After.setAsIdentityConversion(); 5480 Result.UserDefined.After.setFromType(ToType); 5481 Result.UserDefined.After.setAllToTypes(ToType); 5482 Result.UserDefined.ConversionFunction = nullptr; 5483 } 5484 return Result; 5485 } 5486 5487 // C++14 [over.ics.list]p6: 5488 // C++11 [over.ics.list]p5: 5489 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5490 if (ToType->isReferenceType()) { 5491 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5492 // mention initializer lists in any way. So we go by what list- 5493 // initialization would do and try to extrapolate from that. 5494 5495 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5496 5497 // If the initializer list has a single element that is reference-related 5498 // to the parameter type, we initialize the reference from that. 5499 if (From->getNumInits() == 1 && !IsDesignatedInit) { 5500 Expr *Init = From->getInit(0); 5501 5502 QualType T2 = Init->getType(); 5503 5504 // If the initializer is the address of an overloaded function, try 5505 // to resolve the overloaded function. If all goes well, T2 is the 5506 // type of the resulting function. 5507 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5508 DeclAccessPair Found; 5509 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5510 Init, ToType, false, Found)) 5511 T2 = Fn->getType(); 5512 } 5513 5514 // Compute some basic properties of the types and the initializer. 5515 Sema::ReferenceCompareResult RefRelationship = 5516 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5517 5518 if (RefRelationship >= Sema::Ref_Related) { 5519 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5520 SuppressUserConversions, 5521 /*AllowExplicit=*/false); 5522 } 5523 } 5524 5525 // Otherwise, we bind the reference to a temporary created from the 5526 // initializer list. 5527 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5528 InOverloadResolution, 5529 AllowObjCWritebackConversion); 5530 if (Result.isFailure()) 5531 return Result; 5532 assert(!Result.isEllipsis() && 5533 "Sub-initialization cannot result in ellipsis conversion."); 5534 5535 // Can we even bind to a temporary? 5536 if (ToType->isRValueReferenceType() || 5537 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5538 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5539 Result.UserDefined.After; 5540 SCS.ReferenceBinding = true; 5541 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5542 SCS.BindsToRvalue = true; 5543 SCS.BindsToFunctionLvalue = false; 5544 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5545 SCS.ObjCLifetimeConversionBinding = false; 5546 } else 5547 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5548 From, ToType); 5549 return Result; 5550 } 5551 5552 // C++14 [over.ics.list]p7: 5553 // C++11 [over.ics.list]p6: 5554 // Otherwise, if the parameter type is not a class: 5555 if (!ToType->isRecordType()) { 5556 // - if the initializer list has one element that is not itself an 5557 // initializer list, the implicit conversion sequence is the one 5558 // required to convert the element to the parameter type. 5559 unsigned NumInits = From->getNumInits(); 5560 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5561 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5562 SuppressUserConversions, 5563 InOverloadResolution, 5564 AllowObjCWritebackConversion); 5565 // - if the initializer list has no elements, the implicit conversion 5566 // sequence is the identity conversion. 5567 else if (NumInits == 0) { 5568 Result.setStandard(); 5569 Result.Standard.setAsIdentityConversion(); 5570 Result.Standard.setFromType(ToType); 5571 Result.Standard.setAllToTypes(ToType); 5572 } 5573 return Result; 5574 } 5575 5576 // C++14 [over.ics.list]p8: 5577 // C++11 [over.ics.list]p7: 5578 // In all cases other than those enumerated above, no conversion is possible 5579 return Result; 5580 } 5581 5582 /// TryCopyInitialization - Try to copy-initialize a value of type 5583 /// ToType from the expression From. Return the implicit conversion 5584 /// sequence required to pass this argument, which may be a bad 5585 /// conversion sequence (meaning that the argument cannot be passed to 5586 /// a parameter of this type). If @p SuppressUserConversions, then we 5587 /// do not permit any user-defined conversion sequences. 5588 static ImplicitConversionSequence 5589 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5590 bool SuppressUserConversions, 5591 bool InOverloadResolution, 5592 bool AllowObjCWritebackConversion, 5593 bool AllowExplicit) { 5594 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5595 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5596 InOverloadResolution,AllowObjCWritebackConversion); 5597 5598 if (ToType->isReferenceType()) 5599 return TryReferenceInit(S, From, ToType, 5600 /*FIXME:*/ From->getBeginLoc(), 5601 SuppressUserConversions, AllowExplicit); 5602 5603 return TryImplicitConversion(S, From, ToType, 5604 SuppressUserConversions, 5605 AllowedExplicit::None, 5606 InOverloadResolution, 5607 /*CStyle=*/false, 5608 AllowObjCWritebackConversion, 5609 /*AllowObjCConversionOnExplicit=*/false); 5610 } 5611 5612 static bool TryCopyInitialization(const CanQualType FromQTy, 5613 const CanQualType ToQTy, 5614 Sema &S, 5615 SourceLocation Loc, 5616 ExprValueKind FromVK) { 5617 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5618 ImplicitConversionSequence ICS = 5619 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5620 5621 return !ICS.isBad(); 5622 } 5623 5624 /// TryObjectArgumentInitialization - Try to initialize the object 5625 /// parameter of the given member function (@c Method) from the 5626 /// expression @p From. 5627 static ImplicitConversionSequence TryObjectArgumentInitialization( 5628 Sema &S, SourceLocation Loc, QualType FromType, 5629 Expr::Classification FromClassification, CXXMethodDecl *Method, 5630 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false, 5631 QualType ExplicitParameterType = QualType(), 5632 bool SuppressUserConversion = false) { 5633 5634 // We need to have an object of class type. 5635 if (const auto *PT = FromType->getAs<PointerType>()) { 5636 FromType = PT->getPointeeType(); 5637 5638 // When we had a pointer, it's implicitly dereferenced, so we 5639 // better have an lvalue. 5640 assert(FromClassification.isLValue()); 5641 } 5642 5643 auto ValueKindFromClassification = [](Expr::Classification C) { 5644 if (C.isPRValue()) 5645 return clang::VK_PRValue; 5646 if (C.isXValue()) 5647 return VK_XValue; 5648 return clang::VK_LValue; 5649 }; 5650 5651 if (Method->isExplicitObjectMemberFunction()) { 5652 if (ExplicitParameterType.isNull()) 5653 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType(); 5654 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(), 5655 ValueKindFromClassification(FromClassification)); 5656 ImplicitConversionSequence ICS = TryCopyInitialization( 5657 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion, 5658 /*InOverloadResolution=*/true, false); 5659 if (ICS.isBad()) 5660 ICS.Bad.FromExpr = nullptr; 5661 return ICS; 5662 } 5663 5664 assert(FromType->isRecordType()); 5665 5666 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5667 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5668 // const volatile object. 5669 Qualifiers Quals = Method->getMethodQualifiers(); 5670 if (isa<CXXDestructorDecl>(Method)) { 5671 Quals.addConst(); 5672 Quals.addVolatile(); 5673 } 5674 5675 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5676 5677 // Set up the conversion sequence as a "bad" conversion, to allow us 5678 // to exit early. 5679 ImplicitConversionSequence ICS; 5680 5681 // C++0x [over.match.funcs]p4: 5682 // For non-static member functions, the type of the implicit object 5683 // parameter is 5684 // 5685 // - "lvalue reference to cv X" for functions declared without a 5686 // ref-qualifier or with the & ref-qualifier 5687 // - "rvalue reference to cv X" for functions declared with the && 5688 // ref-qualifier 5689 // 5690 // where X is the class of which the function is a member and cv is the 5691 // cv-qualification on the member function declaration. 5692 // 5693 // However, when finding an implicit conversion sequence for the argument, we 5694 // are not allowed to perform user-defined conversions 5695 // (C++ [over.match.funcs]p5). We perform a simplified version of 5696 // reference binding here, that allows class rvalues to bind to 5697 // non-constant references. 5698 5699 // First check the qualifiers. 5700 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5701 // MSVC ignores __unaligned qualifier for overload candidates; do the same. 5702 if (ImplicitParamType.getCVRQualifiers() != 5703 FromTypeCanon.getLocalCVRQualifiers() && 5704 !ImplicitParamType.isAtLeastAsQualifiedAs( 5705 withoutUnaligned(S.Context, FromTypeCanon))) { 5706 ICS.setBad(BadConversionSequence::bad_qualifiers, 5707 FromType, ImplicitParamType); 5708 return ICS; 5709 } 5710 5711 if (FromTypeCanon.hasAddressSpace()) { 5712 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5713 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5714 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5715 ICS.setBad(BadConversionSequence::bad_qualifiers, 5716 FromType, ImplicitParamType); 5717 return ICS; 5718 } 5719 } 5720 5721 // Check that we have either the same type or a derived type. It 5722 // affects the conversion rank. 5723 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5724 ImplicitConversionKind SecondKind; 5725 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5726 SecondKind = ICK_Identity; 5727 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) { 5728 SecondKind = ICK_Derived_To_Base; 5729 } else if (!Method->isExplicitObjectMemberFunction()) { 5730 ICS.setBad(BadConversionSequence::unrelated_class, 5731 FromType, ImplicitParamType); 5732 return ICS; 5733 } 5734 5735 // Check the ref-qualifier. 5736 switch (Method->getRefQualifier()) { 5737 case RQ_None: 5738 // Do nothing; we don't care about lvalueness or rvalueness. 5739 break; 5740 5741 case RQ_LValue: 5742 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5743 // non-const lvalue reference cannot bind to an rvalue 5744 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5745 ImplicitParamType); 5746 return ICS; 5747 } 5748 break; 5749 5750 case RQ_RValue: 5751 if (!FromClassification.isRValue()) { 5752 // rvalue reference cannot bind to an lvalue 5753 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5754 ImplicitParamType); 5755 return ICS; 5756 } 5757 break; 5758 } 5759 5760 // Success. Mark this as a reference binding. 5761 ICS.setStandard(); 5762 ICS.Standard.setAsIdentityConversion(); 5763 ICS.Standard.Second = SecondKind; 5764 ICS.Standard.setFromType(FromType); 5765 ICS.Standard.setAllToTypes(ImplicitParamType); 5766 ICS.Standard.ReferenceBinding = true; 5767 ICS.Standard.DirectBinding = true; 5768 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5769 ICS.Standard.BindsToFunctionLvalue = false; 5770 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5771 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5772 = (Method->getRefQualifier() == RQ_None); 5773 return ICS; 5774 } 5775 5776 /// PerformObjectArgumentInitialization - Perform initialization of 5777 /// the implicit object parameter for the given Method with the given 5778 /// expression. 5779 ExprResult Sema::PerformImplicitObjectArgumentInitialization( 5780 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, 5781 CXXMethodDecl *Method) { 5782 QualType FromRecordType, DestType; 5783 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType(); 5784 5785 Expr::Classification FromClassification; 5786 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5787 FromRecordType = PT->getPointeeType(); 5788 DestType = Method->getThisType(); 5789 FromClassification = Expr::Classification::makeSimpleLValue(); 5790 } else { 5791 FromRecordType = From->getType(); 5792 DestType = ImplicitParamRecordType; 5793 FromClassification = From->Classify(Context); 5794 5795 // When performing member access on a prvalue, materialize a temporary. 5796 if (From->isPRValue()) { 5797 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5798 Method->getRefQualifier() != 5799 RefQualifierKind::RQ_RValue); 5800 } 5801 } 5802 5803 // Note that we always use the true parent context when performing 5804 // the actual argument initialization. 5805 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5806 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5807 Method->getParent()); 5808 if (ICS.isBad()) { 5809 switch (ICS.Bad.Kind) { 5810 case BadConversionSequence::bad_qualifiers: { 5811 Qualifiers FromQs = FromRecordType.getQualifiers(); 5812 Qualifiers ToQs = DestType.getQualifiers(); 5813 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5814 if (CVR) { 5815 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5816 << Method->getDeclName() << FromRecordType << (CVR - 1) 5817 << From->getSourceRange(); 5818 Diag(Method->getLocation(), diag::note_previous_decl) 5819 << Method->getDeclName(); 5820 return ExprError(); 5821 } 5822 break; 5823 } 5824 5825 case BadConversionSequence::lvalue_ref_to_rvalue: 5826 case BadConversionSequence::rvalue_ref_to_lvalue: { 5827 bool IsRValueQualified = 5828 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5829 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5830 << Method->getDeclName() << FromClassification.isRValue() 5831 << IsRValueQualified; 5832 Diag(Method->getLocation(), diag::note_previous_decl) 5833 << Method->getDeclName(); 5834 return ExprError(); 5835 } 5836 5837 case BadConversionSequence::no_conversion: 5838 case BadConversionSequence::unrelated_class: 5839 break; 5840 5841 case BadConversionSequence::too_few_initializers: 5842 case BadConversionSequence::too_many_initializers: 5843 llvm_unreachable("Lists are not objects"); 5844 } 5845 5846 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5847 << ImplicitParamRecordType << FromRecordType 5848 << From->getSourceRange(); 5849 } 5850 5851 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5852 ExprResult FromRes = 5853 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5854 if (FromRes.isInvalid()) 5855 return ExprError(); 5856 From = FromRes.get(); 5857 } 5858 5859 if (!Context.hasSameType(From->getType(), DestType)) { 5860 CastKind CK; 5861 QualType PteeTy = DestType->getPointeeType(); 5862 LangAS DestAS = 5863 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5864 if (FromRecordType.getAddressSpace() != DestAS) 5865 CK = CK_AddressSpaceConversion; 5866 else 5867 CK = CK_NoOp; 5868 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5869 } 5870 return From; 5871 } 5872 5873 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5874 /// expression From to bool (C++0x [conv]p3). 5875 static ImplicitConversionSequence 5876 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5877 // C++ [dcl.init]/17.8: 5878 // - Otherwise, if the initialization is direct-initialization, the source 5879 // type is std::nullptr_t, and the destination type is bool, the initial 5880 // value of the object being initialized is false. 5881 if (From->getType()->isNullPtrType()) 5882 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5883 S.Context.BoolTy, 5884 From->isGLValue()); 5885 5886 // All other direct-initialization of bool is equivalent to an implicit 5887 // conversion to bool in which explicit conversions are permitted. 5888 return TryImplicitConversion(S, From, S.Context.BoolTy, 5889 /*SuppressUserConversions=*/false, 5890 AllowedExplicit::Conversions, 5891 /*InOverloadResolution=*/false, 5892 /*CStyle=*/false, 5893 /*AllowObjCWritebackConversion=*/false, 5894 /*AllowObjCConversionOnExplicit=*/false); 5895 } 5896 5897 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5898 /// of the expression From to bool (C++0x [conv]p3). 5899 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5900 if (checkPlaceholderForOverload(*this, From)) 5901 return ExprError(); 5902 5903 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5904 if (!ICS.isBad()) 5905 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5906 5907 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5908 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5909 << From->getType() << From->getSourceRange(); 5910 return ExprError(); 5911 } 5912 5913 /// Check that the specified conversion is permitted in a converted constant 5914 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5915 /// is acceptable. 5916 static bool CheckConvertedConstantConversions(Sema &S, 5917 StandardConversionSequence &SCS) { 5918 // Since we know that the target type is an integral or unscoped enumeration 5919 // type, most conversion kinds are impossible. All possible First and Third 5920 // conversions are fine. 5921 switch (SCS.Second) { 5922 case ICK_Identity: 5923 case ICK_Integral_Promotion: 5924 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5925 case ICK_Zero_Queue_Conversion: 5926 return true; 5927 5928 case ICK_Boolean_Conversion: 5929 // Conversion from an integral or unscoped enumeration type to bool is 5930 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5931 // conversion, so we allow it in a converted constant expression. 5932 // 5933 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5934 // a lot of popular code. We should at least add a warning for this 5935 // (non-conforming) extension. 5936 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5937 SCS.getToType(2)->isBooleanType(); 5938 5939 case ICK_Pointer_Conversion: 5940 case ICK_Pointer_Member: 5941 // C++1z: null pointer conversions and null member pointer conversions are 5942 // only permitted if the source type is std::nullptr_t. 5943 return SCS.getFromType()->isNullPtrType(); 5944 5945 case ICK_Floating_Promotion: 5946 case ICK_Complex_Promotion: 5947 case ICK_Floating_Conversion: 5948 case ICK_Complex_Conversion: 5949 case ICK_Floating_Integral: 5950 case ICK_Compatible_Conversion: 5951 case ICK_Derived_To_Base: 5952 case ICK_Vector_Conversion: 5953 case ICK_SVE_Vector_Conversion: 5954 case ICK_RVV_Vector_Conversion: 5955 case ICK_Vector_Splat: 5956 case ICK_Complex_Real: 5957 case ICK_Block_Pointer_Conversion: 5958 case ICK_TransparentUnionConversion: 5959 case ICK_Writeback_Conversion: 5960 case ICK_Zero_Event_Conversion: 5961 case ICK_C_Only_Conversion: 5962 case ICK_Incompatible_Pointer_Conversion: 5963 case ICK_Fixed_Point_Conversion: 5964 return false; 5965 5966 case ICK_Lvalue_To_Rvalue: 5967 case ICK_Array_To_Pointer: 5968 case ICK_Function_To_Pointer: 5969 llvm_unreachable("found a first conversion kind in Second"); 5970 5971 case ICK_Function_Conversion: 5972 case ICK_Qualification: 5973 llvm_unreachable("found a third conversion kind in Second"); 5974 5975 case ICK_Num_Conversion_Kinds: 5976 break; 5977 } 5978 5979 llvm_unreachable("unknown conversion kind"); 5980 } 5981 5982 /// BuildConvertedConstantExpression - Check that the expression From is a 5983 /// converted constant expression of type T, perform the conversion but 5984 /// does not evaluate the expression 5985 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, 5986 QualType T, 5987 Sema::CCEKind CCE, 5988 NamedDecl *Dest, 5989 APValue &PreNarrowingValue) { 5990 assert(S.getLangOpts().CPlusPlus11 && 5991 "converted constant expression outside C++11"); 5992 5993 if (checkPlaceholderForOverload(S, From)) 5994 return ExprError(); 5995 5996 // C++1z [expr.const]p3: 5997 // A converted constant expression of type T is an expression, 5998 // implicitly converted to type T, where the converted 5999 // expression is a constant expression and the implicit conversion 6000 // sequence contains only [... list of conversions ...]. 6001 ImplicitConversionSequence ICS = 6002 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 6003 ? TryContextuallyConvertToBool(S, From) 6004 : TryCopyInitialization(S, From, T, 6005 /*SuppressUserConversions=*/false, 6006 /*InOverloadResolution=*/false, 6007 /*AllowObjCWritebackConversion=*/false, 6008 /*AllowExplicit=*/false); 6009 StandardConversionSequence *SCS = nullptr; 6010 switch (ICS.getKind()) { 6011 case ImplicitConversionSequence::StandardConversion: 6012 SCS = &ICS.Standard; 6013 break; 6014 case ImplicitConversionSequence::UserDefinedConversion: 6015 if (T->isRecordType()) 6016 SCS = &ICS.UserDefined.Before; 6017 else 6018 SCS = &ICS.UserDefined.After; 6019 break; 6020 case ImplicitConversionSequence::AmbiguousConversion: 6021 case ImplicitConversionSequence::BadConversion: 6022 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 6023 return S.Diag(From->getBeginLoc(), 6024 diag::err_typecheck_converted_constant_expression) 6025 << From->getType() << From->getSourceRange() << T; 6026 return ExprError(); 6027 6028 case ImplicitConversionSequence::EllipsisConversion: 6029 case ImplicitConversionSequence::StaticObjectArgumentConversion: 6030 llvm_unreachable("bad conversion in converted constant expression"); 6031 } 6032 6033 // Check that we would only use permitted conversions. 6034 if (!CheckConvertedConstantConversions(S, *SCS)) { 6035 return S.Diag(From->getBeginLoc(), 6036 diag::err_typecheck_converted_constant_expression_disallowed) 6037 << From->getType() << From->getSourceRange() << T; 6038 } 6039 // [...] and where the reference binding (if any) binds directly. 6040 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 6041 return S.Diag(From->getBeginLoc(), 6042 diag::err_typecheck_converted_constant_expression_indirect) 6043 << From->getType() << From->getSourceRange() << T; 6044 } 6045 // 'TryCopyInitialization' returns incorrect info for attempts to bind 6046 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely, 6047 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not 6048 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this 6049 // case explicitly. 6050 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) { 6051 return S.Diag(From->getBeginLoc(), 6052 diag::err_reference_bind_to_bitfield_in_cce) 6053 << From->getSourceRange(); 6054 } 6055 6056 // Usually we can simply apply the ImplicitConversionSequence we formed 6057 // earlier, but that's not guaranteed to work when initializing an object of 6058 // class type. 6059 ExprResult Result; 6060 if (T->isRecordType()) { 6061 assert(CCE == Sema::CCEK_TemplateArg && 6062 "unexpected class type converted constant expr"); 6063 Result = S.PerformCopyInitialization( 6064 InitializedEntity::InitializeTemplateParameter( 6065 T, cast<NonTypeTemplateParmDecl>(Dest)), 6066 SourceLocation(), From); 6067 } else { 6068 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 6069 } 6070 if (Result.isInvalid()) 6071 return Result; 6072 6073 // C++2a [intro.execution]p5: 6074 // A full-expression is [...] a constant-expression [...] 6075 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 6076 /*DiscardedValue=*/false, /*IsConstexpr=*/true, 6077 CCE == Sema::CCEKind::CCEK_TemplateArg); 6078 if (Result.isInvalid()) 6079 return Result; 6080 6081 // Check for a narrowing implicit conversion. 6082 bool ReturnPreNarrowingValue = false; 6083 QualType PreNarrowingType; 6084 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 6085 PreNarrowingType)) { 6086 case NK_Dependent_Narrowing: 6087 // Implicit conversion to a narrower type, but the expression is 6088 // value-dependent so we can't tell whether it's actually narrowing. 6089 case NK_Variable_Narrowing: 6090 // Implicit conversion to a narrower type, and the value is not a constant 6091 // expression. We'll diagnose this in a moment. 6092 case NK_Not_Narrowing: 6093 break; 6094 6095 case NK_Constant_Narrowing: 6096 if (CCE == Sema::CCEK_ArrayBound && 6097 PreNarrowingType->isIntegralOrEnumerationType() && 6098 PreNarrowingValue.isInt()) { 6099 // Don't diagnose array bound narrowing here; we produce more precise 6100 // errors by allowing the un-narrowed value through. 6101 ReturnPreNarrowingValue = true; 6102 break; 6103 } 6104 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 6105 << CCE << /*Constant*/ 1 6106 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 6107 break; 6108 6109 case NK_Type_Narrowing: 6110 // FIXME: It would be better to diagnose that the expression is not a 6111 // constant expression. 6112 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 6113 << CCE << /*Constant*/ 0 << From->getType() << T; 6114 break; 6115 } 6116 if (!ReturnPreNarrowingValue) 6117 PreNarrowingValue = {}; 6118 6119 return Result; 6120 } 6121 6122 /// CheckConvertedConstantExpression - Check that the expression From is a 6123 /// converted constant expression of type T, perform the conversion and produce 6124 /// the converted expression, per C++11 [expr.const]p3. 6125 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 6126 QualType T, APValue &Value, 6127 Sema::CCEKind CCE, 6128 bool RequireInt, 6129 NamedDecl *Dest) { 6130 6131 APValue PreNarrowingValue; 6132 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest, 6133 PreNarrowingValue); 6134 if (Result.isInvalid() || Result.get()->isValueDependent()) { 6135 Value = APValue(); 6136 return Result; 6137 } 6138 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE, 6139 RequireInt, PreNarrowingValue); 6140 } 6141 6142 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T, 6143 CCEKind CCE, 6144 NamedDecl *Dest) { 6145 APValue PreNarrowingValue; 6146 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest, 6147 PreNarrowingValue); 6148 } 6149 6150 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 6151 APValue &Value, CCEKind CCE, 6152 NamedDecl *Dest) { 6153 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 6154 Dest); 6155 } 6156 6157 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 6158 llvm::APSInt &Value, 6159 CCEKind CCE) { 6160 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 6161 6162 APValue V; 6163 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 6164 /*Dest=*/nullptr); 6165 if (!R.isInvalid() && !R.get()->isValueDependent()) 6166 Value = V.getInt(); 6167 return R; 6168 } 6169 6170 /// EvaluateConvertedConstantExpression - Evaluate an Expression 6171 /// That is a converted constant expression 6172 /// (which was built with BuildConvertedConstantExpression) 6173 ExprResult 6174 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, 6175 Sema::CCEKind CCE, bool RequireInt, 6176 const APValue &PreNarrowingValue) { 6177 6178 ExprResult Result = E; 6179 // Check the expression is a constant expression. 6180 SmallVector<PartialDiagnosticAt, 8> Notes; 6181 Expr::EvalResult Eval; 6182 Eval.Diag = &Notes; 6183 6184 ConstantExprKind Kind; 6185 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 6186 Kind = ConstantExprKind::ClassTemplateArgument; 6187 else if (CCE == Sema::CCEK_TemplateArg) 6188 Kind = ConstantExprKind::NonClassTemplateArgument; 6189 else 6190 Kind = ConstantExprKind::Normal; 6191 6192 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) || 6193 (RequireInt && !Eval.Val.isInt())) { 6194 // The expression can't be folded, so we can't keep it at this position in 6195 // the AST. 6196 Result = ExprError(); 6197 } else { 6198 Value = Eval.Val; 6199 6200 if (Notes.empty()) { 6201 // It's a constant expression. 6202 Expr *E = Result.get(); 6203 if (const auto *CE = dyn_cast<ConstantExpr>(E)) { 6204 // We expect a ConstantExpr to have a value associated with it 6205 // by this point. 6206 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None && 6207 "ConstantExpr has no value associated with it"); 6208 } else { 6209 E = ConstantExpr::Create(Context, Result.get(), Value); 6210 } 6211 if (!PreNarrowingValue.isAbsent()) 6212 Value = std::move(PreNarrowingValue); 6213 return E; 6214 } 6215 } 6216 6217 // It's not a constant expression. Produce an appropriate diagnostic. 6218 if (Notes.size() == 1 && 6219 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 6220 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 6221 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 6222 diag::note_constexpr_invalid_template_arg) { 6223 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 6224 for (unsigned I = 0; I < Notes.size(); ++I) 6225 Diag(Notes[I].first, Notes[I].second); 6226 } else { 6227 Diag(E->getBeginLoc(), diag::err_expr_not_cce) 6228 << CCE << E->getSourceRange(); 6229 for (unsigned I = 0; I < Notes.size(); ++I) 6230 Diag(Notes[I].first, Notes[I].second); 6231 } 6232 return ExprError(); 6233 } 6234 6235 /// dropPointerConversions - If the given standard conversion sequence 6236 /// involves any pointer conversions, remove them. This may change 6237 /// the result type of the conversion sequence. 6238 static void dropPointerConversion(StandardConversionSequence &SCS) { 6239 if (SCS.Second == ICK_Pointer_Conversion) { 6240 SCS.Second = ICK_Identity; 6241 SCS.Third = ICK_Identity; 6242 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 6243 } 6244 } 6245 6246 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 6247 /// convert the expression From to an Objective-C pointer type. 6248 static ImplicitConversionSequence 6249 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 6250 // Do an implicit conversion to 'id'. 6251 QualType Ty = S.Context.getObjCIdType(); 6252 ImplicitConversionSequence ICS 6253 = TryImplicitConversion(S, From, Ty, 6254 // FIXME: Are these flags correct? 6255 /*SuppressUserConversions=*/false, 6256 AllowedExplicit::Conversions, 6257 /*InOverloadResolution=*/false, 6258 /*CStyle=*/false, 6259 /*AllowObjCWritebackConversion=*/false, 6260 /*AllowObjCConversionOnExplicit=*/true); 6261 6262 // Strip off any final conversions to 'id'. 6263 switch (ICS.getKind()) { 6264 case ImplicitConversionSequence::BadConversion: 6265 case ImplicitConversionSequence::AmbiguousConversion: 6266 case ImplicitConversionSequence::EllipsisConversion: 6267 case ImplicitConversionSequence::StaticObjectArgumentConversion: 6268 break; 6269 6270 case ImplicitConversionSequence::UserDefinedConversion: 6271 dropPointerConversion(ICS.UserDefined.After); 6272 break; 6273 6274 case ImplicitConversionSequence::StandardConversion: 6275 dropPointerConversion(ICS.Standard); 6276 break; 6277 } 6278 6279 return ICS; 6280 } 6281 6282 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 6283 /// conversion of the expression From to an Objective-C pointer type. 6284 /// Returns a valid but null ExprResult if no conversion sequence exists. 6285 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 6286 if (checkPlaceholderForOverload(*this, From)) 6287 return ExprError(); 6288 6289 QualType Ty = Context.getObjCIdType(); 6290 ImplicitConversionSequence ICS = 6291 TryContextuallyConvertToObjCPointer(*this, From); 6292 if (!ICS.isBad()) 6293 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 6294 return ExprResult(); 6295 } 6296 6297 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) { 6298 const Expr *Base = nullptr; 6299 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) && 6300 "expected a member expression"); 6301 6302 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE); 6303 M && !M->isImplicitAccess()) 6304 Base = M->getBase(); 6305 else if (const auto M = dyn_cast<MemberExpr>(MemExprE); 6306 M && !M->isImplicitAccess()) 6307 Base = M->getBase(); 6308 6309 QualType T = Base ? Base->getType() : S.getCurrentThisType(); 6310 6311 if (T->isPointerType()) 6312 T = T->getPointeeType(); 6313 6314 return T; 6315 } 6316 6317 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj, 6318 const FunctionDecl *Fun) { 6319 QualType ObjType = Obj->getType(); 6320 if (ObjType->isPointerType()) { 6321 ObjType = ObjType->getPointeeType(); 6322 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType, 6323 VK_LValue, OK_Ordinary, SourceLocation(), 6324 /*CanOverflow=*/false, FPOptionsOverride()); 6325 } 6326 if (Obj->Classify(S.getASTContext()).isPRValue()) { 6327 Obj = S.CreateMaterializeTemporaryExpr( 6328 ObjType, Obj, 6329 !Fun->getParamDecl(0)->getType()->isRValueReferenceType()); 6330 } 6331 return Obj; 6332 } 6333 6334 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj, 6335 FunctionDecl *Fun) { 6336 Obj = GetExplicitObjectExpr(S, Obj, Fun); 6337 return S.PerformCopyInitialization( 6338 InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)), 6339 Obj->getExprLoc(), Obj); 6340 } 6341 6342 static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, 6343 Expr *Object, MultiExprArg &Args, 6344 SmallVectorImpl<Expr *> &NewArgs) { 6345 assert(Method->isExplicitObjectMemberFunction() && 6346 "Method is not an explicit member function"); 6347 assert(NewArgs.empty() && "NewArgs should be empty"); 6348 NewArgs.reserve(Args.size() + 1); 6349 Expr *This = GetExplicitObjectExpr(S, Object, Method); 6350 NewArgs.push_back(This); 6351 NewArgs.append(Args.begin(), Args.end()); 6352 Args = NewArgs; 6353 } 6354 6355 /// Determine whether the provided type is an integral type, or an enumeration 6356 /// type of a permitted flavor. 6357 bool Sema::ICEConvertDiagnoser::match(QualType T) { 6358 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 6359 : T->isIntegralOrUnscopedEnumerationType(); 6360 } 6361 6362 static ExprResult 6363 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 6364 Sema::ContextualImplicitConverter &Converter, 6365 QualType T, UnresolvedSetImpl &ViableConversions) { 6366 6367 if (Converter.Suppress) 6368 return ExprError(); 6369 6370 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 6371 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6372 CXXConversionDecl *Conv = 6373 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 6374 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 6375 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 6376 } 6377 return From; 6378 } 6379 6380 static bool 6381 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6382 Sema::ContextualImplicitConverter &Converter, 6383 QualType T, bool HadMultipleCandidates, 6384 UnresolvedSetImpl &ExplicitConversions) { 6385 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 6386 DeclAccessPair Found = ExplicitConversions[0]; 6387 CXXConversionDecl *Conversion = 6388 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6389 6390 // The user probably meant to invoke the given explicit 6391 // conversion; use it. 6392 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 6393 std::string TypeStr; 6394 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 6395 6396 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 6397 << FixItHint::CreateInsertion(From->getBeginLoc(), 6398 "static_cast<" + TypeStr + ">(") 6399 << FixItHint::CreateInsertion( 6400 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 6401 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 6402 6403 // If we aren't in a SFINAE context, build a call to the 6404 // explicit conversion function. 6405 if (SemaRef.isSFINAEContext()) 6406 return true; 6407 6408 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6409 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6410 HadMultipleCandidates); 6411 if (Result.isInvalid()) 6412 return true; 6413 // Record usage of conversion in an implicit cast. 6414 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6415 CK_UserDefinedConversion, Result.get(), 6416 nullptr, Result.get()->getValueKind(), 6417 SemaRef.CurFPFeatureOverrides()); 6418 } 6419 return false; 6420 } 6421 6422 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6423 Sema::ContextualImplicitConverter &Converter, 6424 QualType T, bool HadMultipleCandidates, 6425 DeclAccessPair &Found) { 6426 CXXConversionDecl *Conversion = 6427 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6428 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6429 6430 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6431 if (!Converter.SuppressConversion) { 6432 if (SemaRef.isSFINAEContext()) 6433 return true; 6434 6435 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6436 << From->getSourceRange(); 6437 } 6438 6439 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6440 HadMultipleCandidates); 6441 if (Result.isInvalid()) 6442 return true; 6443 // Record usage of conversion in an implicit cast. 6444 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6445 CK_UserDefinedConversion, Result.get(), 6446 nullptr, Result.get()->getValueKind(), 6447 SemaRef.CurFPFeatureOverrides()); 6448 return false; 6449 } 6450 6451 static ExprResult finishContextualImplicitConversion( 6452 Sema &SemaRef, SourceLocation Loc, Expr *From, 6453 Sema::ContextualImplicitConverter &Converter) { 6454 if (!Converter.match(From->getType()) && !Converter.Suppress) 6455 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6456 << From->getSourceRange(); 6457 6458 return SemaRef.DefaultLvalueConversion(From); 6459 } 6460 6461 static void 6462 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6463 UnresolvedSetImpl &ViableConversions, 6464 OverloadCandidateSet &CandidateSet) { 6465 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6466 DeclAccessPair FoundDecl = ViableConversions[I]; 6467 NamedDecl *D = FoundDecl.getDecl(); 6468 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6469 if (isa<UsingShadowDecl>(D)) 6470 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6471 6472 CXXConversionDecl *Conv; 6473 FunctionTemplateDecl *ConvTemplate; 6474 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6475 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6476 else 6477 Conv = cast<CXXConversionDecl>(D); 6478 6479 if (ConvTemplate) 6480 SemaRef.AddTemplateConversionCandidate( 6481 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6482 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6483 else 6484 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6485 ToType, CandidateSet, 6486 /*AllowObjCConversionOnExplicit=*/false, 6487 /*AllowExplicit*/ true); 6488 } 6489 } 6490 6491 /// Attempt to convert the given expression to a type which is accepted 6492 /// by the given converter. 6493 /// 6494 /// This routine will attempt to convert an expression of class type to a 6495 /// type accepted by the specified converter. In C++11 and before, the class 6496 /// must have a single non-explicit conversion function converting to a matching 6497 /// type. In C++1y, there can be multiple such conversion functions, but only 6498 /// one target type. 6499 /// 6500 /// \param Loc The source location of the construct that requires the 6501 /// conversion. 6502 /// 6503 /// \param From The expression we're converting from. 6504 /// 6505 /// \param Converter Used to control and diagnose the conversion process. 6506 /// 6507 /// \returns The expression, converted to an integral or enumeration type if 6508 /// successful. 6509 ExprResult Sema::PerformContextualImplicitConversion( 6510 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6511 // We can't perform any more checking for type-dependent expressions. 6512 if (From->isTypeDependent()) 6513 return From; 6514 6515 // Process placeholders immediately. 6516 if (From->hasPlaceholderType()) { 6517 ExprResult result = CheckPlaceholderExpr(From); 6518 if (result.isInvalid()) 6519 return result; 6520 From = result.get(); 6521 } 6522 6523 // Try converting the expression to an Lvalue first, to get rid of qualifiers. 6524 ExprResult Converted = DefaultLvalueConversion(From); 6525 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType(); 6526 // If the expression already has a matching type, we're golden. 6527 if (Converter.match(T)) 6528 return Converted; 6529 6530 // FIXME: Check for missing '()' if T is a function type? 6531 6532 // We can only perform contextual implicit conversions on objects of class 6533 // type. 6534 const RecordType *RecordTy = T->getAs<RecordType>(); 6535 if (!RecordTy || !getLangOpts().CPlusPlus) { 6536 if (!Converter.Suppress) 6537 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6538 return From; 6539 } 6540 6541 // We must have a complete class type. 6542 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6543 ContextualImplicitConverter &Converter; 6544 Expr *From; 6545 6546 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6547 : Converter(Converter), From(From) {} 6548 6549 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6550 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6551 } 6552 } IncompleteDiagnoser(Converter, From); 6553 6554 if (Converter.Suppress ? !isCompleteType(Loc, T) 6555 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6556 return From; 6557 6558 // Look for a conversion to an integral or enumeration type. 6559 UnresolvedSet<4> 6560 ViableConversions; // These are *potentially* viable in C++1y. 6561 UnresolvedSet<4> ExplicitConversions; 6562 const auto &Conversions = 6563 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6564 6565 bool HadMultipleCandidates = 6566 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6567 6568 // To check that there is only one target type, in C++1y: 6569 QualType ToType; 6570 bool HasUniqueTargetType = true; 6571 6572 // Collect explicit or viable (potentially in C++1y) conversions. 6573 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6574 NamedDecl *D = (*I)->getUnderlyingDecl(); 6575 CXXConversionDecl *Conversion; 6576 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6577 if (ConvTemplate) { 6578 if (getLangOpts().CPlusPlus14) 6579 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6580 else 6581 continue; // C++11 does not consider conversion operator templates(?). 6582 } else 6583 Conversion = cast<CXXConversionDecl>(D); 6584 6585 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6586 "Conversion operator templates are considered potentially " 6587 "viable in C++1y"); 6588 6589 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6590 if (Converter.match(CurToType) || ConvTemplate) { 6591 6592 if (Conversion->isExplicit()) { 6593 // FIXME: For C++1y, do we need this restriction? 6594 // cf. diagnoseNoViableConversion() 6595 if (!ConvTemplate) 6596 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6597 } else { 6598 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6599 if (ToType.isNull()) 6600 ToType = CurToType.getUnqualifiedType(); 6601 else if (HasUniqueTargetType && 6602 (CurToType.getUnqualifiedType() != ToType)) 6603 HasUniqueTargetType = false; 6604 } 6605 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6606 } 6607 } 6608 } 6609 6610 if (getLangOpts().CPlusPlus14) { 6611 // C++1y [conv]p6: 6612 // ... An expression e of class type E appearing in such a context 6613 // is said to be contextually implicitly converted to a specified 6614 // type T and is well-formed if and only if e can be implicitly 6615 // converted to a type T that is determined as follows: E is searched 6616 // for conversion functions whose return type is cv T or reference to 6617 // cv T such that T is allowed by the context. There shall be 6618 // exactly one such T. 6619 6620 // If no unique T is found: 6621 if (ToType.isNull()) { 6622 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6623 HadMultipleCandidates, 6624 ExplicitConversions)) 6625 return ExprError(); 6626 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6627 } 6628 6629 // If more than one unique Ts are found: 6630 if (!HasUniqueTargetType) 6631 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6632 ViableConversions); 6633 6634 // If one unique T is found: 6635 // First, build a candidate set from the previously recorded 6636 // potentially viable conversions. 6637 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6638 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6639 CandidateSet); 6640 6641 // Then, perform overload resolution over the candidate set. 6642 OverloadCandidateSet::iterator Best; 6643 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6644 case OR_Success: { 6645 // Apply this conversion. 6646 DeclAccessPair Found = 6647 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6648 if (recordConversion(*this, Loc, From, Converter, T, 6649 HadMultipleCandidates, Found)) 6650 return ExprError(); 6651 break; 6652 } 6653 case OR_Ambiguous: 6654 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6655 ViableConversions); 6656 case OR_No_Viable_Function: 6657 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6658 HadMultipleCandidates, 6659 ExplicitConversions)) 6660 return ExprError(); 6661 [[fallthrough]]; 6662 case OR_Deleted: 6663 // We'll complain below about a non-integral condition type. 6664 break; 6665 } 6666 } else { 6667 switch (ViableConversions.size()) { 6668 case 0: { 6669 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6670 HadMultipleCandidates, 6671 ExplicitConversions)) 6672 return ExprError(); 6673 6674 // We'll complain below about a non-integral condition type. 6675 break; 6676 } 6677 case 1: { 6678 // Apply this conversion. 6679 DeclAccessPair Found = ViableConversions[0]; 6680 if (recordConversion(*this, Loc, From, Converter, T, 6681 HadMultipleCandidates, Found)) 6682 return ExprError(); 6683 break; 6684 } 6685 default: 6686 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6687 ViableConversions); 6688 } 6689 } 6690 6691 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6692 } 6693 6694 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6695 /// an acceptable non-member overloaded operator for a call whose 6696 /// arguments have types T1 (and, if non-empty, T2). This routine 6697 /// implements the check in C++ [over.match.oper]p3b2 concerning 6698 /// enumeration types. 6699 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6700 FunctionDecl *Fn, 6701 ArrayRef<Expr *> Args) { 6702 QualType T1 = Args[0]->getType(); 6703 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6704 6705 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6706 return true; 6707 6708 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6709 return true; 6710 6711 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6712 if (Proto->getNumParams() < 1) 6713 return false; 6714 6715 if (T1->isEnumeralType()) { 6716 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6717 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6718 return true; 6719 } 6720 6721 if (Proto->getNumParams() < 2) 6722 return false; 6723 6724 if (!T2.isNull() && T2->isEnumeralType()) { 6725 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6726 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6727 return true; 6728 } 6729 6730 return false; 6731 } 6732 6733 /// AddOverloadCandidate - Adds the given function to the set of 6734 /// candidate functions, using the given function call arguments. If 6735 /// @p SuppressUserConversions, then don't allow user-defined 6736 /// conversions via constructors or conversion operators. 6737 /// 6738 /// \param PartialOverloading true if we are performing "partial" overloading 6739 /// based on an incomplete set of function arguments. This feature is used by 6740 /// code completion. 6741 void Sema::AddOverloadCandidate( 6742 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6743 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6744 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6745 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6746 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { 6747 const FunctionProtoType *Proto 6748 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6749 assert(Proto && "Functions without a prototype cannot be overloaded"); 6750 assert(!Function->getDescribedFunctionTemplate() && 6751 "Use AddTemplateOverloadCandidate for function templates"); 6752 6753 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6754 if (!isa<CXXConstructorDecl>(Method)) { 6755 // If we get here, it's because we're calling a member function 6756 // that is named without a member access expression (e.g., 6757 // "this->f") that was either written explicitly or created 6758 // implicitly. This can happen with a qualified call to a member 6759 // function, e.g., X::f(). We use an empty type for the implied 6760 // object argument (C++ [over.call.func]p3), and the acting context 6761 // is irrelevant. 6762 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6763 Expr::Classification::makeSimpleLValue(), Args, 6764 CandidateSet, SuppressUserConversions, 6765 PartialOverloading, EarlyConversions, PO); 6766 return; 6767 } 6768 // We treat a constructor like a non-member function, since its object 6769 // argument doesn't participate in overload resolution. 6770 } 6771 6772 if (!CandidateSet.isNewCandidate(Function, PO)) 6773 return; 6774 6775 // C++11 [class.copy]p11: [DR1402] 6776 // A defaulted move constructor that is defined as deleted is ignored by 6777 // overload resolution. 6778 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6779 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6780 Constructor->isMoveConstructor()) 6781 return; 6782 6783 // Overload resolution is always an unevaluated context. 6784 EnterExpressionEvaluationContext Unevaluated( 6785 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6786 6787 // C++ [over.match.oper]p3: 6788 // if no operand has a class type, only those non-member functions in the 6789 // lookup set that have a first parameter of type T1 or "reference to 6790 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6791 // is a right operand) a second parameter of type T2 or "reference to 6792 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6793 // candidate functions. 6794 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6795 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6796 return; 6797 6798 // Add this candidate 6799 OverloadCandidate &Candidate = 6800 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6801 Candidate.FoundDecl = FoundDecl; 6802 Candidate.Function = Function; 6803 Candidate.Viable = true; 6804 Candidate.RewriteKind = 6805 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6806 Candidate.IsSurrogate = false; 6807 Candidate.IsADLCandidate = IsADLCandidate; 6808 Candidate.IgnoreObjectArgument = false; 6809 Candidate.ExplicitCallArguments = Args.size(); 6810 6811 // Explicit functions are not actually candidates at all if we're not 6812 // allowing them in this context, but keep them around so we can point 6813 // to them in diagnostics. 6814 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6815 Candidate.Viable = false; 6816 Candidate.FailureKind = ovl_fail_explicit; 6817 return; 6818 } 6819 6820 // Functions with internal linkage are only viable in the same module unit. 6821 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) { 6822 /// FIXME: Currently, the semantics of linkage in clang is slightly 6823 /// different from the semantics in C++ spec. In C++ spec, only names 6824 /// have linkage. So that all entities of the same should share one 6825 /// linkage. But in clang, different entities of the same could have 6826 /// different linkage. 6827 NamedDecl *ND = Function; 6828 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) 6829 ND = SpecInfo->getTemplate(); 6830 6831 if (ND->getFormalLinkage() == Linkage::Internal) { 6832 Candidate.Viable = false; 6833 Candidate.FailureKind = ovl_fail_module_mismatched; 6834 return; 6835 } 6836 } 6837 6838 if (Function->isMultiVersion() && 6839 ((Function->hasAttr<TargetAttr>() && 6840 !Function->getAttr<TargetAttr>()->isDefaultVersion()) || 6841 (Function->hasAttr<TargetVersionAttr>() && 6842 !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { 6843 Candidate.Viable = false; 6844 Candidate.FailureKind = ovl_non_default_multiversion_function; 6845 return; 6846 } 6847 6848 if (Constructor) { 6849 // C++ [class.copy]p3: 6850 // A member function template is never instantiated to perform the copy 6851 // of a class object to an object of its class type. 6852 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6853 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6854 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6855 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6856 ClassType))) { 6857 Candidate.Viable = false; 6858 Candidate.FailureKind = ovl_fail_illegal_constructor; 6859 return; 6860 } 6861 6862 // C++ [over.match.funcs]p8: (proposed DR resolution) 6863 // A constructor inherited from class type C that has a first parameter 6864 // of type "reference to P" (including such a constructor instantiated 6865 // from a template) is excluded from the set of candidate functions when 6866 // constructing an object of type cv D if the argument list has exactly 6867 // one argument and D is reference-related to P and P is reference-related 6868 // to C. 6869 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6870 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6871 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6872 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6873 QualType C = Context.getRecordType(Constructor->getParent()); 6874 QualType D = Context.getRecordType(Shadow->getParent()); 6875 SourceLocation Loc = Args.front()->getExprLoc(); 6876 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6877 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6878 Candidate.Viable = false; 6879 Candidate.FailureKind = ovl_fail_inhctor_slice; 6880 return; 6881 } 6882 } 6883 6884 // Check that the constructor is capable of constructing an object in the 6885 // destination address space. 6886 if (!Qualifiers::isAddressSpaceSupersetOf( 6887 Constructor->getMethodQualifiers().getAddressSpace(), 6888 CandidateSet.getDestAS())) { 6889 Candidate.Viable = false; 6890 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6891 } 6892 } 6893 6894 unsigned NumParams = Proto->getNumParams(); 6895 6896 // (C++ 13.3.2p2): A candidate function having fewer than m 6897 // parameters is viable only if it has an ellipsis in its parameter 6898 // list (8.3.5). 6899 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6900 !Proto->isVariadic() && 6901 shouldEnforceArgLimit(PartialOverloading, Function)) { 6902 Candidate.Viable = false; 6903 Candidate.FailureKind = ovl_fail_too_many_arguments; 6904 return; 6905 } 6906 6907 // (C++ 13.3.2p2): A candidate function having more than m parameters 6908 // is viable only if the (m+1)st parameter has a default argument 6909 // (8.3.6). For the purposes of overload resolution, the 6910 // parameter list is truncated on the right, so that there are 6911 // exactly m parameters. 6912 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6913 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs && 6914 !PartialOverloading) { 6915 // Not enough arguments. 6916 Candidate.Viable = false; 6917 Candidate.FailureKind = ovl_fail_too_few_arguments; 6918 return; 6919 } 6920 6921 // (CUDA B.1): Check for invalid calls between targets. 6922 if (getLangOpts().CUDA) { 6923 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 6924 // Skip the check for callers that are implicit members, because in this 6925 // case we may not yet know what the member's target is; the target is 6926 // inferred for the member automatically, based on the bases and fields of 6927 // the class. 6928 if (!(Caller && Caller->isImplicit()) && 6929 !IsAllowedCUDACall(Caller, Function)) { 6930 Candidate.Viable = false; 6931 Candidate.FailureKind = ovl_fail_bad_target; 6932 return; 6933 } 6934 } 6935 6936 if (Function->getTrailingRequiresClause()) { 6937 ConstraintSatisfaction Satisfaction; 6938 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {}, 6939 /*ForOverloadResolution*/ true) || 6940 !Satisfaction.IsSatisfied) { 6941 Candidate.Viable = false; 6942 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6943 return; 6944 } 6945 } 6946 6947 // Determine the implicit conversion sequences for each of the 6948 // arguments. 6949 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6950 unsigned ConvIdx = 6951 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6952 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6953 // We already formed a conversion sequence for this parameter during 6954 // template argument deduction. 6955 } else if (ArgIdx < NumParams) { 6956 // (C++ 13.3.2p3): for F to be a viable function, there shall 6957 // exist for each argument an implicit conversion sequence 6958 // (13.3.3.1) that converts that argument to the corresponding 6959 // parameter of F. 6960 QualType ParamType = Proto->getParamType(ArgIdx); 6961 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6962 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6963 /*InOverloadResolution=*/true, 6964 /*AllowObjCWritebackConversion=*/ 6965 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6966 if (Candidate.Conversions[ConvIdx].isBad()) { 6967 Candidate.Viable = false; 6968 Candidate.FailureKind = ovl_fail_bad_conversion; 6969 return; 6970 } 6971 } else { 6972 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6973 // argument for which there is no corresponding parameter is 6974 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6975 Candidate.Conversions[ConvIdx].setEllipsis(); 6976 } 6977 } 6978 6979 if (EnableIfAttr *FailedAttr = 6980 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6981 Candidate.Viable = false; 6982 Candidate.FailureKind = ovl_fail_enable_if; 6983 Candidate.DeductionFailure.Data = FailedAttr; 6984 return; 6985 } 6986 } 6987 6988 ObjCMethodDecl * 6989 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6990 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6991 if (Methods.size() <= 1) 6992 return nullptr; 6993 6994 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6995 bool Match = true; 6996 ObjCMethodDecl *Method = Methods[b]; 6997 unsigned NumNamedArgs = Sel.getNumArgs(); 6998 // Method might have more arguments than selector indicates. This is due 6999 // to addition of c-style arguments in method. 7000 if (Method->param_size() > NumNamedArgs) 7001 NumNamedArgs = Method->param_size(); 7002 if (Args.size() < NumNamedArgs) 7003 continue; 7004 7005 for (unsigned i = 0; i < NumNamedArgs; i++) { 7006 // We can't do any type-checking on a type-dependent argument. 7007 if (Args[i]->isTypeDependent()) { 7008 Match = false; 7009 break; 7010 } 7011 7012 ParmVarDecl *param = Method->parameters()[i]; 7013 Expr *argExpr = Args[i]; 7014 assert(argExpr && "SelectBestMethod(): missing expression"); 7015 7016 // Strip the unbridged-cast placeholder expression off unless it's 7017 // a consumed argument. 7018 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 7019 !param->hasAttr<CFConsumedAttr>()) 7020 argExpr = stripARCUnbridgedCast(argExpr); 7021 7022 // If the parameter is __unknown_anytype, move on to the next method. 7023 if (param->getType() == Context.UnknownAnyTy) { 7024 Match = false; 7025 break; 7026 } 7027 7028 ImplicitConversionSequence ConversionState 7029 = TryCopyInitialization(*this, argExpr, param->getType(), 7030 /*SuppressUserConversions*/false, 7031 /*InOverloadResolution=*/true, 7032 /*AllowObjCWritebackConversion=*/ 7033 getLangOpts().ObjCAutoRefCount, 7034 /*AllowExplicit*/false); 7035 // This function looks for a reasonably-exact match, so we consider 7036 // incompatible pointer conversions to be a failure here. 7037 if (ConversionState.isBad() || 7038 (ConversionState.isStandard() && 7039 ConversionState.Standard.Second == 7040 ICK_Incompatible_Pointer_Conversion)) { 7041 Match = false; 7042 break; 7043 } 7044 } 7045 // Promote additional arguments to variadic methods. 7046 if (Match && Method->isVariadic()) { 7047 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 7048 if (Args[i]->isTypeDependent()) { 7049 Match = false; 7050 break; 7051 } 7052 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 7053 nullptr); 7054 if (Arg.isInvalid()) { 7055 Match = false; 7056 break; 7057 } 7058 } 7059 } else { 7060 // Check for extra arguments to non-variadic methods. 7061 if (Args.size() != NumNamedArgs) 7062 Match = false; 7063 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 7064 // Special case when selectors have no argument. In this case, select 7065 // one with the most general result type of 'id'. 7066 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 7067 QualType ReturnT = Methods[b]->getReturnType(); 7068 if (ReturnT->isObjCIdType()) 7069 return Methods[b]; 7070 } 7071 } 7072 } 7073 7074 if (Match) 7075 return Method; 7076 } 7077 return nullptr; 7078 } 7079 7080 static bool convertArgsForAvailabilityChecks( 7081 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 7082 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 7083 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 7084 if (ThisArg) { 7085 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 7086 assert(!isa<CXXConstructorDecl>(Method) && 7087 "Shouldn't have `this` for ctors!"); 7088 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 7089 ExprResult R = S.PerformImplicitObjectArgumentInitialization( 7090 ThisArg, /*Qualifier=*/nullptr, Method, Method); 7091 if (R.isInvalid()) 7092 return false; 7093 ConvertedThis = R.get(); 7094 } else { 7095 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 7096 (void)MD; 7097 assert((MissingImplicitThis || MD->isStatic() || 7098 isa<CXXConstructorDecl>(MD)) && 7099 "Expected `this` for non-ctor instance methods"); 7100 } 7101 ConvertedThis = nullptr; 7102 } 7103 7104 // Ignore any variadic arguments. Converting them is pointless, since the 7105 // user can't refer to them in the function condition. 7106 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 7107 7108 // Convert the arguments. 7109 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 7110 ExprResult R; 7111 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 7112 S.Context, Function->getParamDecl(I)), 7113 SourceLocation(), Args[I]); 7114 7115 if (R.isInvalid()) 7116 return false; 7117 7118 ConvertedArgs.push_back(R.get()); 7119 } 7120 7121 if (Trap.hasErrorOccurred()) 7122 return false; 7123 7124 // Push default arguments if needed. 7125 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 7126 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 7127 ParmVarDecl *P = Function->getParamDecl(i); 7128 if (!P->hasDefaultArg()) 7129 return false; 7130 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 7131 if (R.isInvalid()) 7132 return false; 7133 ConvertedArgs.push_back(R.get()); 7134 } 7135 7136 if (Trap.hasErrorOccurred()) 7137 return false; 7138 } 7139 return true; 7140 } 7141 7142 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 7143 SourceLocation CallLoc, 7144 ArrayRef<Expr *> Args, 7145 bool MissingImplicitThis) { 7146 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 7147 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 7148 return nullptr; 7149 7150 SFINAETrap Trap(*this); 7151 SmallVector<Expr *, 16> ConvertedArgs; 7152 // FIXME: We should look into making enable_if late-parsed. 7153 Expr *DiscardedThis; 7154 if (!convertArgsForAvailabilityChecks( 7155 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 7156 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 7157 return *EnableIfAttrs.begin(); 7158 7159 for (auto *EIA : EnableIfAttrs) { 7160 APValue Result; 7161 // FIXME: This doesn't consider value-dependent cases, because doing so is 7162 // very difficult. Ideally, we should handle them more gracefully. 7163 if (EIA->getCond()->isValueDependent() || 7164 !EIA->getCond()->EvaluateWithSubstitution( 7165 Result, Context, Function, llvm::ArrayRef(ConvertedArgs))) 7166 return EIA; 7167 7168 if (!Result.isInt() || !Result.getInt().getBoolValue()) 7169 return EIA; 7170 } 7171 return nullptr; 7172 } 7173 7174 template <typename CheckFn> 7175 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 7176 bool ArgDependent, SourceLocation Loc, 7177 CheckFn &&IsSuccessful) { 7178 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 7179 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 7180 if (ArgDependent == DIA->getArgDependent()) 7181 Attrs.push_back(DIA); 7182 } 7183 7184 // Common case: No diagnose_if attributes, so we can quit early. 7185 if (Attrs.empty()) 7186 return false; 7187 7188 auto WarningBegin = std::stable_partition( 7189 Attrs.begin(), Attrs.end(), 7190 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 7191 7192 // Note that diagnose_if attributes are late-parsed, so they appear in the 7193 // correct order (unlike enable_if attributes). 7194 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 7195 IsSuccessful); 7196 if (ErrAttr != WarningBegin) { 7197 const DiagnoseIfAttr *DIA = *ErrAttr; 7198 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 7199 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 7200 << DIA->getParent() << DIA->getCond()->getSourceRange(); 7201 return true; 7202 } 7203 7204 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 7205 if (IsSuccessful(DIA)) { 7206 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 7207 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 7208 << DIA->getParent() << DIA->getCond()->getSourceRange(); 7209 } 7210 7211 return false; 7212 } 7213 7214 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 7215 const Expr *ThisArg, 7216 ArrayRef<const Expr *> Args, 7217 SourceLocation Loc) { 7218 return diagnoseDiagnoseIfAttrsWith( 7219 *this, Function, /*ArgDependent=*/true, Loc, 7220 [&](const DiagnoseIfAttr *DIA) { 7221 APValue Result; 7222 // It's sane to use the same Args for any redecl of this function, since 7223 // EvaluateWithSubstitution only cares about the position of each 7224 // argument in the arg list, not the ParmVarDecl* it maps to. 7225 if (!DIA->getCond()->EvaluateWithSubstitution( 7226 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 7227 return false; 7228 return Result.isInt() && Result.getInt().getBoolValue(); 7229 }); 7230 } 7231 7232 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 7233 SourceLocation Loc) { 7234 return diagnoseDiagnoseIfAttrsWith( 7235 *this, ND, /*ArgDependent=*/false, Loc, 7236 [&](const DiagnoseIfAttr *DIA) { 7237 bool Result; 7238 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 7239 Result; 7240 }); 7241 } 7242 7243 /// Add all of the function declarations in the given function set to 7244 /// the overload candidate set. 7245 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 7246 ArrayRef<Expr *> Args, 7247 OverloadCandidateSet &CandidateSet, 7248 TemplateArgumentListInfo *ExplicitTemplateArgs, 7249 bool SuppressUserConversions, 7250 bool PartialOverloading, 7251 bool FirstArgumentIsBase) { 7252 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7253 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7254 ArrayRef<Expr *> FunctionArgs = Args; 7255 7256 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7257 FunctionDecl *FD = 7258 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7259 7260 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 7261 QualType ObjectType; 7262 Expr::Classification ObjectClassification; 7263 if (Args.size() > 0) { 7264 if (Expr *E = Args[0]) { 7265 // Use the explicit base to restrict the lookup: 7266 ObjectType = E->getType(); 7267 // Pointers in the object arguments are implicitly dereferenced, so we 7268 // always classify them as l-values. 7269 if (!ObjectType.isNull() && ObjectType->isPointerType()) 7270 ObjectClassification = Expr::Classification::makeSimpleLValue(); 7271 else 7272 ObjectClassification = E->Classify(Context); 7273 } // .. else there is an implicit base. 7274 FunctionArgs = Args.slice(1); 7275 } 7276 if (FunTmpl) { 7277 AddMethodTemplateCandidate( 7278 FunTmpl, F.getPair(), 7279 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 7280 ExplicitTemplateArgs, ObjectType, ObjectClassification, 7281 FunctionArgs, CandidateSet, SuppressUserConversions, 7282 PartialOverloading); 7283 } else { 7284 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 7285 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 7286 ObjectClassification, FunctionArgs, CandidateSet, 7287 SuppressUserConversions, PartialOverloading); 7288 } 7289 } else { 7290 // This branch handles both standalone functions and static methods. 7291 7292 // Slice the first argument (which is the base) when we access 7293 // static method as non-static. 7294 if (Args.size() > 0 && 7295 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 7296 !isa<CXXConstructorDecl>(FD)))) { 7297 assert(cast<CXXMethodDecl>(FD)->isStatic()); 7298 FunctionArgs = Args.slice(1); 7299 } 7300 if (FunTmpl) { 7301 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 7302 ExplicitTemplateArgs, FunctionArgs, 7303 CandidateSet, SuppressUserConversions, 7304 PartialOverloading); 7305 } else { 7306 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 7307 SuppressUserConversions, PartialOverloading); 7308 } 7309 } 7310 } 7311 } 7312 7313 /// AddMethodCandidate - Adds a named decl (which is some kind of 7314 /// method) as a method candidate to the given overload set. 7315 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 7316 Expr::Classification ObjectClassification, 7317 ArrayRef<Expr *> Args, 7318 OverloadCandidateSet &CandidateSet, 7319 bool SuppressUserConversions, 7320 OverloadCandidateParamOrder PO) { 7321 NamedDecl *Decl = FoundDecl.getDecl(); 7322 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 7323 7324 if (isa<UsingShadowDecl>(Decl)) 7325 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 7326 7327 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 7328 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 7329 "Expected a member function template"); 7330 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 7331 /*ExplicitArgs*/ nullptr, ObjectType, 7332 ObjectClassification, Args, CandidateSet, 7333 SuppressUserConversions, false, PO); 7334 } else { 7335 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 7336 ObjectType, ObjectClassification, Args, CandidateSet, 7337 SuppressUserConversions, false, std::nullopt, PO); 7338 } 7339 } 7340 7341 /// AddMethodCandidate - Adds the given C++ member function to the set 7342 /// of candidate functions, using the given function call arguments 7343 /// and the object argument (@c Object). For example, in a call 7344 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 7345 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 7346 /// allow user-defined conversions via constructors or conversion 7347 /// operators. 7348 void 7349 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 7350 CXXRecordDecl *ActingContext, QualType ObjectType, 7351 Expr::Classification ObjectClassification, 7352 ArrayRef<Expr *> Args, 7353 OverloadCandidateSet &CandidateSet, 7354 bool SuppressUserConversions, 7355 bool PartialOverloading, 7356 ConversionSequenceList EarlyConversions, 7357 OverloadCandidateParamOrder PO) { 7358 const FunctionProtoType *Proto 7359 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 7360 assert(Proto && "Methods without a prototype cannot be overloaded"); 7361 assert(!isa<CXXConstructorDecl>(Method) && 7362 "Use AddOverloadCandidate for constructors"); 7363 7364 if (!CandidateSet.isNewCandidate(Method, PO)) 7365 return; 7366 7367 // C++11 [class.copy]p23: [DR1402] 7368 // A defaulted move assignment operator that is defined as deleted is 7369 // ignored by overload resolution. 7370 if (Method->isDefaulted() && Method->isDeleted() && 7371 Method->isMoveAssignmentOperator()) 7372 return; 7373 7374 // Overload resolution is always an unevaluated context. 7375 EnterExpressionEvaluationContext Unevaluated( 7376 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7377 7378 // Add this candidate 7379 OverloadCandidate &Candidate = 7380 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 7381 Candidate.FoundDecl = FoundDecl; 7382 Candidate.Function = Method; 7383 Candidate.RewriteKind = 7384 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 7385 Candidate.IsSurrogate = false; 7386 Candidate.IgnoreObjectArgument = false; 7387 Candidate.ExplicitCallArguments = Args.size(); 7388 7389 unsigned NumParams = Method->getNumExplicitParams(); 7390 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0; 7391 7392 // (C++ 13.3.2p2): A candidate function having fewer than m 7393 // parameters is viable only if it has an ellipsis in its parameter 7394 // list (8.3.5). 7395 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 7396 !Proto->isVariadic() && 7397 shouldEnforceArgLimit(PartialOverloading, Method)) { 7398 Candidate.Viable = false; 7399 Candidate.FailureKind = ovl_fail_too_many_arguments; 7400 return; 7401 } 7402 7403 // (C++ 13.3.2p2): A candidate function having more than m parameters 7404 // is viable only if the (m+1)st parameter has a default argument 7405 // (8.3.6). For the purposes of overload resolution, the 7406 // parameter list is truncated on the right, so that there are 7407 // exactly m parameters. 7408 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments(); 7409 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 7410 // Not enough arguments. 7411 Candidate.Viable = false; 7412 Candidate.FailureKind = ovl_fail_too_few_arguments; 7413 return; 7414 } 7415 7416 Candidate.Viable = true; 7417 7418 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7419 if (ObjectType.isNull()) 7420 Candidate.IgnoreObjectArgument = true; 7421 else if (Method->isStatic()) { 7422 // [over.best.ics.general]p8 7423 // When the parameter is the implicit object parameter of a static member 7424 // function, the implicit conversion sequence is a standard conversion 7425 // sequence that is neither better nor worse than any other standard 7426 // conversion sequence. 7427 // 7428 // This is a rule that was introduced in C++23 to support static lambdas. We 7429 // apply it retroactively because we want to support static lambdas as an 7430 // extension and it doesn't hurt previous code. 7431 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument(); 7432 } else { 7433 // Determine the implicit conversion sequence for the object 7434 // parameter. 7435 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization( 7436 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7437 Method, ActingContext, /*InOverloadResolution=*/true); 7438 if (Candidate.Conversions[FirstConvIdx].isBad()) { 7439 Candidate.Viable = false; 7440 Candidate.FailureKind = ovl_fail_bad_conversion; 7441 return; 7442 } 7443 } 7444 7445 // (CUDA B.1): Check for invalid calls between targets. 7446 if (getLangOpts().CUDA) 7447 if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) { 7448 Candidate.Viable = false; 7449 Candidate.FailureKind = ovl_fail_bad_target; 7450 return; 7451 } 7452 7453 if (Method->getTrailingRequiresClause()) { 7454 ConstraintSatisfaction Satisfaction; 7455 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {}, 7456 /*ForOverloadResolution*/ true) || 7457 !Satisfaction.IsSatisfied) { 7458 Candidate.Viable = false; 7459 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7460 return; 7461 } 7462 } 7463 7464 // Determine the implicit conversion sequences for each of the 7465 // arguments. 7466 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7467 unsigned ConvIdx = 7468 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7469 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7470 // We already formed a conversion sequence for this parameter during 7471 // template argument deduction. 7472 } else if (ArgIdx < NumParams) { 7473 // (C++ 13.3.2p3): for F to be a viable function, there shall 7474 // exist for each argument an implicit conversion sequence 7475 // (13.3.3.1) that converts that argument to the corresponding 7476 // parameter of F. 7477 QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset); 7478 Candidate.Conversions[ConvIdx] 7479 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7480 SuppressUserConversions, 7481 /*InOverloadResolution=*/true, 7482 /*AllowObjCWritebackConversion=*/ 7483 getLangOpts().ObjCAutoRefCount); 7484 if (Candidate.Conversions[ConvIdx].isBad()) { 7485 Candidate.Viable = false; 7486 Candidate.FailureKind = ovl_fail_bad_conversion; 7487 return; 7488 } 7489 } else { 7490 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7491 // argument for which there is no corresponding parameter is 7492 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7493 Candidate.Conversions[ConvIdx].setEllipsis(); 7494 } 7495 } 7496 7497 if (EnableIfAttr *FailedAttr = 7498 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7499 Candidate.Viable = false; 7500 Candidate.FailureKind = ovl_fail_enable_if; 7501 Candidate.DeductionFailure.Data = FailedAttr; 7502 return; 7503 } 7504 7505 if (Method->isMultiVersion() && 7506 ((Method->hasAttr<TargetAttr>() && 7507 !Method->getAttr<TargetAttr>()->isDefaultVersion()) || 7508 (Method->hasAttr<TargetVersionAttr>() && 7509 !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { 7510 Candidate.Viable = false; 7511 Candidate.FailureKind = ovl_non_default_multiversion_function; 7512 } 7513 } 7514 7515 /// Add a C++ member function template as a candidate to the candidate 7516 /// set, using template argument deduction to produce an appropriate member 7517 /// function template specialization. 7518 void Sema::AddMethodTemplateCandidate( 7519 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7520 CXXRecordDecl *ActingContext, 7521 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7522 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7523 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7524 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7525 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7526 return; 7527 7528 // C++ [over.match.funcs]p7: 7529 // In each case where a candidate is a function template, candidate 7530 // function template specializations are generated using template argument 7531 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7532 // candidate functions in the usual way.113) A given name can refer to one 7533 // or more function templates and also to a set of overloaded non-template 7534 // functions. In such a case, the candidate functions generated from each 7535 // function template are combined with the set of non-template candidate 7536 // functions. 7537 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7538 FunctionDecl *Specialization = nullptr; 7539 ConversionSequenceList Conversions; 7540 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7541 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7542 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType, 7543 ObjectClassification, [&](ArrayRef<QualType> ParamTypes) { 7544 return CheckNonDependentConversions( 7545 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7546 SuppressUserConversions, ActingContext, ObjectType, 7547 ObjectClassification, PO); 7548 })) { 7549 OverloadCandidate &Candidate = 7550 CandidateSet.addCandidate(Conversions.size(), Conversions); 7551 Candidate.FoundDecl = FoundDecl; 7552 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7553 Candidate.Viable = false; 7554 Candidate.RewriteKind = 7555 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7556 Candidate.IsSurrogate = false; 7557 Candidate.IgnoreObjectArgument = 7558 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7559 ObjectType.isNull(); 7560 Candidate.ExplicitCallArguments = Args.size(); 7561 if (Result == TDK_NonDependentConversionFailure) 7562 Candidate.FailureKind = ovl_fail_bad_conversion; 7563 else { 7564 Candidate.FailureKind = ovl_fail_bad_deduction; 7565 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7566 Info); 7567 } 7568 return; 7569 } 7570 7571 // Add the function template specialization produced by template argument 7572 // deduction as a candidate. 7573 assert(Specialization && "Missing member function template specialization?"); 7574 assert(isa<CXXMethodDecl>(Specialization) && 7575 "Specialization is not a member function?"); 7576 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7577 ActingContext, ObjectType, ObjectClassification, Args, 7578 CandidateSet, SuppressUserConversions, PartialOverloading, 7579 Conversions, PO); 7580 } 7581 7582 /// Determine whether a given function template has a simple explicit specifier 7583 /// or a non-value-dependent explicit-specification that evaluates to true. 7584 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7585 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7586 } 7587 7588 /// Add a C++ function template specialization as a candidate 7589 /// in the candidate set, using template argument deduction to produce 7590 /// an appropriate function template specialization. 7591 void Sema::AddTemplateOverloadCandidate( 7592 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7593 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7594 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7595 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7596 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { 7597 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7598 return; 7599 7600 // If the function template has a non-dependent explicit specification, 7601 // exclude it now if appropriate; we are not permitted to perform deduction 7602 // and substitution in this case. 7603 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7604 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7605 Candidate.FoundDecl = FoundDecl; 7606 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7607 Candidate.Viable = false; 7608 Candidate.FailureKind = ovl_fail_explicit; 7609 return; 7610 } 7611 7612 // C++ [over.match.funcs]p7: 7613 // In each case where a candidate is a function template, candidate 7614 // function template specializations are generated using template argument 7615 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7616 // candidate functions in the usual way.113) A given name can refer to one 7617 // or more function templates and also to a set of overloaded non-template 7618 // functions. In such a case, the candidate functions generated from each 7619 // function template are combined with the set of non-template candidate 7620 // functions. 7621 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7622 FunctionDecl *Specialization = nullptr; 7623 ConversionSequenceList Conversions; 7624 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7625 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7626 PartialOverloading, AggregateCandidateDeduction, 7627 /*ObjectType=*/QualType(), 7628 /*ObjectClassification=*/Expr::Classification(), 7629 [&](ArrayRef<QualType> ParamTypes) { 7630 return CheckNonDependentConversions( 7631 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7632 SuppressUserConversions, nullptr, QualType(), {}, PO); 7633 })) { 7634 OverloadCandidate &Candidate = 7635 CandidateSet.addCandidate(Conversions.size(), Conversions); 7636 Candidate.FoundDecl = FoundDecl; 7637 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7638 Candidate.Viable = false; 7639 Candidate.RewriteKind = 7640 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7641 Candidate.IsSurrogate = false; 7642 Candidate.IsADLCandidate = IsADLCandidate; 7643 // Ignore the object argument if there is one, since we don't have an object 7644 // type. 7645 Candidate.IgnoreObjectArgument = 7646 isa<CXXMethodDecl>(Candidate.Function) && 7647 !isa<CXXConstructorDecl>(Candidate.Function); 7648 Candidate.ExplicitCallArguments = Args.size(); 7649 if (Result == TDK_NonDependentConversionFailure) 7650 Candidate.FailureKind = ovl_fail_bad_conversion; 7651 else { 7652 Candidate.FailureKind = ovl_fail_bad_deduction; 7653 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7654 Info); 7655 } 7656 return; 7657 } 7658 7659 // Add the function template specialization produced by template argument 7660 // deduction as a candidate. 7661 assert(Specialization && "Missing function template specialization?"); 7662 AddOverloadCandidate( 7663 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7664 PartialOverloading, AllowExplicit, 7665 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO, 7666 Info.AggregateDeductionCandidateHasMismatchedArity); 7667 } 7668 7669 /// Check that implicit conversion sequences can be formed for each argument 7670 /// whose corresponding parameter has a non-dependent type, per DR1391's 7671 /// [temp.deduct.call]p10. 7672 bool Sema::CheckNonDependentConversions( 7673 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7674 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7675 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7676 CXXRecordDecl *ActingContext, QualType ObjectType, 7677 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7678 // FIXME: The cases in which we allow explicit conversions for constructor 7679 // arguments never consider calling a constructor template. It's not clear 7680 // that is correct. 7681 const bool AllowExplicit = false; 7682 7683 auto *FD = FunctionTemplate->getTemplatedDecl(); 7684 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7685 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7686 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7687 7688 Conversions = 7689 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7690 7691 // Overload resolution is always an unevaluated context. 7692 EnterExpressionEvaluationContext Unevaluated( 7693 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7694 7695 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7696 // require that, but this check should never result in a hard error, and 7697 // overload resolution is permitted to sidestep instantiations. 7698 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7699 !ObjectType.isNull()) { 7700 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7701 if (!FD->hasCXXExplicitFunctionObjectParameter() || 7702 !ParamTypes[0]->isDependentType()) { 7703 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7704 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7705 Method, ActingContext, /*InOverloadResolution=*/true, 7706 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0] 7707 : QualType()); 7708 if (Conversions[ConvIdx].isBad()) 7709 return true; 7710 } 7711 } 7712 7713 unsigned Offset = 7714 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0; 7715 7716 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7717 ++I) { 7718 QualType ParamType = ParamTypes[I + Offset]; 7719 if (!ParamType->isDependentType()) { 7720 unsigned ConvIdx; 7721 if (PO == OverloadCandidateParamOrder::Reversed) { 7722 ConvIdx = Args.size() - 1 - I; 7723 assert(Args.size() + ThisConversions == 2 && 7724 "number of args (including 'this') must be exactly 2 for " 7725 "reversed order"); 7726 // For members, there would be only one arg 'Args[0]' whose ConvIdx 7727 // would also be 0. 'this' got ConvIdx = 1 previously. 7728 assert(!HasThisConversion || (ConvIdx == 0 && I == 0)); 7729 } else { 7730 // For members, 'this' got ConvIdx = 0 previously. 7731 ConvIdx = ThisConversions + I; 7732 } 7733 Conversions[ConvIdx] 7734 = TryCopyInitialization(*this, Args[I], ParamType, 7735 SuppressUserConversions, 7736 /*InOverloadResolution=*/true, 7737 /*AllowObjCWritebackConversion=*/ 7738 getLangOpts().ObjCAutoRefCount, 7739 AllowExplicit); 7740 if (Conversions[ConvIdx].isBad()) 7741 return true; 7742 } 7743 } 7744 7745 return false; 7746 } 7747 7748 /// Determine whether this is an allowable conversion from the result 7749 /// of an explicit conversion operator to the expected type, per C++ 7750 /// [over.match.conv]p1 and [over.match.ref]p1. 7751 /// 7752 /// \param ConvType The return type of the conversion function. 7753 /// 7754 /// \param ToType The type we are converting to. 7755 /// 7756 /// \param AllowObjCPointerConversion Allow a conversion from one 7757 /// Objective-C pointer to another. 7758 /// 7759 /// \returns true if the conversion is allowable, false otherwise. 7760 static bool isAllowableExplicitConversion(Sema &S, 7761 QualType ConvType, QualType ToType, 7762 bool AllowObjCPointerConversion) { 7763 QualType ToNonRefType = ToType.getNonReferenceType(); 7764 7765 // Easy case: the types are the same. 7766 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7767 return true; 7768 7769 // Allow qualification conversions. 7770 bool ObjCLifetimeConversion; 7771 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7772 ObjCLifetimeConversion)) 7773 return true; 7774 7775 // If we're not allowed to consider Objective-C pointer conversions, 7776 // we're done. 7777 if (!AllowObjCPointerConversion) 7778 return false; 7779 7780 // Is this an Objective-C pointer conversion? 7781 bool IncompatibleObjC = false; 7782 QualType ConvertedType; 7783 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7784 IncompatibleObjC); 7785 } 7786 7787 /// AddConversionCandidate - Add a C++ conversion function as a 7788 /// candidate in the candidate set (C++ [over.match.conv], 7789 /// C++ [over.match.copy]). From is the expression we're converting from, 7790 /// and ToType is the type that we're eventually trying to convert to 7791 /// (which may or may not be the same type as the type that the 7792 /// conversion function produces). 7793 void Sema::AddConversionCandidate( 7794 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7795 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7796 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7797 bool AllowExplicit, bool AllowResultConversion) { 7798 assert(!Conversion->getDescribedFunctionTemplate() && 7799 "Conversion function templates use AddTemplateConversionCandidate"); 7800 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7801 if (!CandidateSet.isNewCandidate(Conversion)) 7802 return; 7803 7804 // If the conversion function has an undeduced return type, trigger its 7805 // deduction now. 7806 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7807 if (DeduceReturnType(Conversion, From->getExprLoc())) 7808 return; 7809 ConvType = Conversion->getConversionType().getNonReferenceType(); 7810 } 7811 7812 // If we don't allow any conversion of the result type, ignore conversion 7813 // functions that don't convert to exactly (possibly cv-qualified) T. 7814 if (!AllowResultConversion && 7815 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7816 return; 7817 7818 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7819 // operator is only a candidate if its return type is the target type or 7820 // can be converted to the target type with a qualification conversion. 7821 // 7822 // FIXME: Include such functions in the candidate list and explain why we 7823 // can't select them. 7824 if (Conversion->isExplicit() && 7825 !isAllowableExplicitConversion(*this, ConvType, ToType, 7826 AllowObjCConversionOnExplicit)) 7827 return; 7828 7829 // Overload resolution is always an unevaluated context. 7830 EnterExpressionEvaluationContext Unevaluated( 7831 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7832 7833 // Add this candidate 7834 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7835 Candidate.FoundDecl = FoundDecl; 7836 Candidate.Function = Conversion; 7837 Candidate.IsSurrogate = false; 7838 Candidate.IgnoreObjectArgument = false; 7839 Candidate.FinalConversion.setAsIdentityConversion(); 7840 Candidate.FinalConversion.setFromType(ConvType); 7841 Candidate.FinalConversion.setAllToTypes(ToType); 7842 Candidate.Viable = true; 7843 Candidate.ExplicitCallArguments = 1; 7844 7845 // Explicit functions are not actually candidates at all if we're not 7846 // allowing them in this context, but keep them around so we can point 7847 // to them in diagnostics. 7848 if (!AllowExplicit && Conversion->isExplicit()) { 7849 Candidate.Viable = false; 7850 Candidate.FailureKind = ovl_fail_explicit; 7851 return; 7852 } 7853 7854 // C++ [over.match.funcs]p4: 7855 // For conversion functions, the function is considered to be a member of 7856 // the class of the implicit implied object argument for the purpose of 7857 // defining the type of the implicit object parameter. 7858 // 7859 // Determine the implicit conversion sequence for the implicit 7860 // object parameter. 7861 QualType ObjectType = From->getType(); 7862 if (const auto *FromPtrType = ObjectType->getAs<PointerType>()) 7863 ObjectType = FromPtrType->getPointeeType(); 7864 const auto *ConversionContext = 7865 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl()); 7866 7867 // C++23 [over.best.ics.general] 7868 // However, if the target is [...] 7869 // - the object parameter of a user-defined conversion function 7870 // [...] user-defined conversion sequences are not considered. 7871 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7872 *this, CandidateSet.getLocation(), From->getType(), 7873 From->Classify(Context), Conversion, ConversionContext, 7874 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(), 7875 /*SuppressUserConversion*/ true); 7876 7877 if (Candidate.Conversions[0].isBad()) { 7878 Candidate.Viable = false; 7879 Candidate.FailureKind = ovl_fail_bad_conversion; 7880 return; 7881 } 7882 7883 if (Conversion->getTrailingRequiresClause()) { 7884 ConstraintSatisfaction Satisfaction; 7885 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7886 !Satisfaction.IsSatisfied) { 7887 Candidate.Viable = false; 7888 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7889 return; 7890 } 7891 } 7892 7893 // We won't go through a user-defined type conversion function to convert a 7894 // derived to base as such conversions are given Conversion Rank. They only 7895 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7896 QualType FromCanon 7897 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7898 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7899 if (FromCanon == ToCanon || 7900 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7901 Candidate.Viable = false; 7902 Candidate.FailureKind = ovl_fail_trivial_conversion; 7903 return; 7904 } 7905 7906 // To determine what the conversion from the result of calling the 7907 // conversion function to the type we're eventually trying to 7908 // convert to (ToType), we need to synthesize a call to the 7909 // conversion function and attempt copy initialization from it. This 7910 // makes sure that we get the right semantics with respect to 7911 // lvalues/rvalues and the type. Fortunately, we can allocate this 7912 // call on the stack and we don't need its arguments to be 7913 // well-formed. 7914 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7915 VK_LValue, From->getBeginLoc()); 7916 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7917 Context.getPointerType(Conversion->getType()), 7918 CK_FunctionToPointerDecay, &ConversionRef, 7919 VK_PRValue, FPOptionsOverride()); 7920 7921 QualType ConversionType = Conversion->getConversionType(); 7922 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7923 Candidate.Viable = false; 7924 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7925 return; 7926 } 7927 7928 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7929 7930 // Note that it is safe to allocate CallExpr on the stack here because 7931 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7932 // allocator). 7933 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7934 7935 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7936 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7937 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7938 7939 ImplicitConversionSequence ICS = 7940 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7941 /*SuppressUserConversions=*/true, 7942 /*InOverloadResolution=*/false, 7943 /*AllowObjCWritebackConversion=*/false); 7944 7945 switch (ICS.getKind()) { 7946 case ImplicitConversionSequence::StandardConversion: 7947 Candidate.FinalConversion = ICS.Standard; 7948 7949 // C++ [over.ics.user]p3: 7950 // If the user-defined conversion is specified by a specialization of a 7951 // conversion function template, the second standard conversion sequence 7952 // shall have exact match rank. 7953 if (Conversion->getPrimaryTemplate() && 7954 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7955 Candidate.Viable = false; 7956 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7957 return; 7958 } 7959 7960 // C++0x [dcl.init.ref]p5: 7961 // In the second case, if the reference is an rvalue reference and 7962 // the second standard conversion sequence of the user-defined 7963 // conversion sequence includes an lvalue-to-rvalue conversion, the 7964 // program is ill-formed. 7965 if (ToType->isRValueReferenceType() && 7966 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7967 Candidate.Viable = false; 7968 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7969 return; 7970 } 7971 break; 7972 7973 case ImplicitConversionSequence::BadConversion: 7974 Candidate.Viable = false; 7975 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7976 return; 7977 7978 default: 7979 llvm_unreachable( 7980 "Can only end up with a standard conversion sequence or failure"); 7981 } 7982 7983 if (EnableIfAttr *FailedAttr = 7984 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { 7985 Candidate.Viable = false; 7986 Candidate.FailureKind = ovl_fail_enable_if; 7987 Candidate.DeductionFailure.Data = FailedAttr; 7988 return; 7989 } 7990 7991 if (Conversion->isMultiVersion() && 7992 ((Conversion->hasAttr<TargetAttr>() && 7993 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) || 7994 (Conversion->hasAttr<TargetVersionAttr>() && 7995 !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { 7996 Candidate.Viable = false; 7997 Candidate.FailureKind = ovl_non_default_multiversion_function; 7998 } 7999 } 8000 8001 /// Adds a conversion function template specialization 8002 /// candidate to the overload set, using template argument deduction 8003 /// to deduce the template arguments of the conversion function 8004 /// template from the type that we are converting to (C++ 8005 /// [temp.deduct.conv]). 8006 void Sema::AddTemplateConversionCandidate( 8007 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 8008 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 8009 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 8010 bool AllowExplicit, bool AllowResultConversion) { 8011 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 8012 "Only conversion function templates permitted here"); 8013 8014 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 8015 return; 8016 8017 // If the function template has a non-dependent explicit specification, 8018 // exclude it now if appropriate; we are not permitted to perform deduction 8019 // and substitution in this case. 8020 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 8021 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 8022 Candidate.FoundDecl = FoundDecl; 8023 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 8024 Candidate.Viable = false; 8025 Candidate.FailureKind = ovl_fail_explicit; 8026 return; 8027 } 8028 8029 QualType ObjectType = From->getType(); 8030 Expr::Classification ObjectClassification = From->Classify(getASTContext()); 8031 8032 TemplateDeductionInfo Info(CandidateSet.getLocation()); 8033 CXXConversionDecl *Specialization = nullptr; 8034 if (TemplateDeductionResult Result = DeduceTemplateArguments( 8035 FunctionTemplate, ObjectType, ObjectClassification, ToType, 8036 Specialization, Info)) { 8037 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 8038 Candidate.FoundDecl = FoundDecl; 8039 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 8040 Candidate.Viable = false; 8041 Candidate.FailureKind = ovl_fail_bad_deduction; 8042 Candidate.IsSurrogate = false; 8043 Candidate.IgnoreObjectArgument = false; 8044 Candidate.ExplicitCallArguments = 1; 8045 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 8046 Info); 8047 return; 8048 } 8049 8050 // Add the conversion function template specialization produced by 8051 // template argument deduction as a candidate. 8052 assert(Specialization && "Missing function template specialization?"); 8053 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 8054 CandidateSet, AllowObjCConversionOnExplicit, 8055 AllowExplicit, AllowResultConversion); 8056 } 8057 8058 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 8059 /// converts the given @c Object to a function pointer via the 8060 /// conversion function @c Conversion, and then attempts to call it 8061 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 8062 /// the type of function that we'll eventually be calling. 8063 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 8064 DeclAccessPair FoundDecl, 8065 CXXRecordDecl *ActingContext, 8066 const FunctionProtoType *Proto, 8067 Expr *Object, 8068 ArrayRef<Expr *> Args, 8069 OverloadCandidateSet& CandidateSet) { 8070 if (!CandidateSet.isNewCandidate(Conversion)) 8071 return; 8072 8073 // Overload resolution is always an unevaluated context. 8074 EnterExpressionEvaluationContext Unevaluated( 8075 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8076 8077 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 8078 Candidate.FoundDecl = FoundDecl; 8079 Candidate.Function = nullptr; 8080 Candidate.Surrogate = Conversion; 8081 Candidate.Viable = true; 8082 Candidate.IsSurrogate = true; 8083 Candidate.IgnoreObjectArgument = false; 8084 Candidate.ExplicitCallArguments = Args.size(); 8085 8086 // Determine the implicit conversion sequence for the implicit 8087 // object parameter. 8088 ImplicitConversionSequence ObjectInit; 8089 if (Conversion->hasCXXExplicitFunctionObjectParameter()) { 8090 ObjectInit = TryCopyInitialization(*this, Object, 8091 Conversion->getParamDecl(0)->getType(), 8092 /*SuppressUserConversions=*/false, 8093 /*InOverloadResolution=*/true, false); 8094 } else { 8095 ObjectInit = TryObjectArgumentInitialization( 8096 *this, CandidateSet.getLocation(), Object->getType(), 8097 Object->Classify(Context), Conversion, ActingContext); 8098 } 8099 8100 if (ObjectInit.isBad()) { 8101 Candidate.Viable = false; 8102 Candidate.FailureKind = ovl_fail_bad_conversion; 8103 Candidate.Conversions[0] = ObjectInit; 8104 return; 8105 } 8106 8107 // The first conversion is actually a user-defined conversion whose 8108 // first conversion is ObjectInit's standard conversion (which is 8109 // effectively a reference binding). Record it as such. 8110 Candidate.Conversions[0].setUserDefined(); 8111 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 8112 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 8113 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 8114 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 8115 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 8116 Candidate.Conversions[0].UserDefined.After 8117 = Candidate.Conversions[0].UserDefined.Before; 8118 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 8119 8120 // Find the 8121 unsigned NumParams = Proto->getNumParams(); 8122 8123 // (C++ 13.3.2p2): A candidate function having fewer than m 8124 // parameters is viable only if it has an ellipsis in its parameter 8125 // list (8.3.5). 8126 if (Args.size() > NumParams && !Proto->isVariadic()) { 8127 Candidate.Viable = false; 8128 Candidate.FailureKind = ovl_fail_too_many_arguments; 8129 return; 8130 } 8131 8132 // Function types don't have any default arguments, so just check if 8133 // we have enough arguments. 8134 if (Args.size() < NumParams) { 8135 // Not enough arguments. 8136 Candidate.Viable = false; 8137 Candidate.FailureKind = ovl_fail_too_few_arguments; 8138 return; 8139 } 8140 8141 // Determine the implicit conversion sequences for each of the 8142 // arguments. 8143 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8144 if (ArgIdx < NumParams) { 8145 // (C++ 13.3.2p3): for F to be a viable function, there shall 8146 // exist for each argument an implicit conversion sequence 8147 // (13.3.3.1) that converts that argument to the corresponding 8148 // parameter of F. 8149 QualType ParamType = Proto->getParamType(ArgIdx); 8150 Candidate.Conversions[ArgIdx + 1] 8151 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 8152 /*SuppressUserConversions=*/false, 8153 /*InOverloadResolution=*/false, 8154 /*AllowObjCWritebackConversion=*/ 8155 getLangOpts().ObjCAutoRefCount); 8156 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 8157 Candidate.Viable = false; 8158 Candidate.FailureKind = ovl_fail_bad_conversion; 8159 return; 8160 } 8161 } else { 8162 // (C++ 13.3.2p2): For the purposes of overload resolution, any 8163 // argument for which there is no corresponding parameter is 8164 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 8165 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 8166 } 8167 } 8168 8169 if (Conversion->getTrailingRequiresClause()) { 8170 ConstraintSatisfaction Satisfaction; 8171 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {}, 8172 /*ForOverloadResolution*/ true) || 8173 !Satisfaction.IsSatisfied) { 8174 Candidate.Viable = false; 8175 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 8176 return; 8177 } 8178 } 8179 8180 if (EnableIfAttr *FailedAttr = 8181 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { 8182 Candidate.Viable = false; 8183 Candidate.FailureKind = ovl_fail_enable_if; 8184 Candidate.DeductionFailure.Data = FailedAttr; 8185 return; 8186 } 8187 } 8188 8189 /// Add all of the non-member operator function declarations in the given 8190 /// function set to the overload candidate set. 8191 void Sema::AddNonMemberOperatorCandidates( 8192 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 8193 OverloadCandidateSet &CandidateSet, 8194 TemplateArgumentListInfo *ExplicitTemplateArgs) { 8195 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 8196 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 8197 ArrayRef<Expr *> FunctionArgs = Args; 8198 8199 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 8200 FunctionDecl *FD = 8201 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 8202 8203 // Don't consider rewritten functions if we're not rewriting. 8204 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 8205 continue; 8206 8207 assert(!isa<CXXMethodDecl>(FD) && 8208 "unqualified operator lookup found a member function"); 8209 8210 if (FunTmpl) { 8211 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 8212 FunctionArgs, CandidateSet); 8213 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) 8214 AddTemplateOverloadCandidate( 8215 FunTmpl, F.getPair(), ExplicitTemplateArgs, 8216 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 8217 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 8218 } else { 8219 if (ExplicitTemplateArgs) 8220 continue; 8221 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 8222 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) 8223 AddOverloadCandidate( 8224 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 8225 false, false, true, false, ADLCallKind::NotADL, std::nullopt, 8226 OverloadCandidateParamOrder::Reversed); 8227 } 8228 } 8229 } 8230 8231 /// Add overload candidates for overloaded operators that are 8232 /// member functions. 8233 /// 8234 /// Add the overloaded operator candidates that are member functions 8235 /// for the operator Op that was used in an operator expression such 8236 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 8237 /// CandidateSet will store the added overload candidates. (C++ 8238 /// [over.match.oper]). 8239 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 8240 SourceLocation OpLoc, 8241 ArrayRef<Expr *> Args, 8242 OverloadCandidateSet &CandidateSet, 8243 OverloadCandidateParamOrder PO) { 8244 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8245 8246 // C++ [over.match.oper]p3: 8247 // For a unary operator @ with an operand of a type whose 8248 // cv-unqualified version is T1, and for a binary operator @ with 8249 // a left operand of a type whose cv-unqualified version is T1 and 8250 // a right operand of a type whose cv-unqualified version is T2, 8251 // three sets of candidate functions, designated member 8252 // candidates, non-member candidates and built-in candidates, are 8253 // constructed as follows: 8254 QualType T1 = Args[0]->getType(); 8255 8256 // -- If T1 is a complete class type or a class currently being 8257 // defined, the set of member candidates is the result of the 8258 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 8259 // the set of member candidates is empty. 8260 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 8261 // Complete the type if it can be completed. 8262 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 8263 return; 8264 // If the type is neither complete nor being defined, bail out now. 8265 if (!T1Rec->getDecl()->getDefinition()) 8266 return; 8267 8268 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 8269 LookupQualifiedName(Operators, T1Rec->getDecl()); 8270 Operators.suppressAccessDiagnostics(); 8271 8272 for (LookupResult::iterator Oper = Operators.begin(), 8273 OperEnd = Operators.end(); 8274 Oper != OperEnd; ++Oper) { 8275 if (Oper->getAsFunction() && 8276 PO == OverloadCandidateParamOrder::Reversed && 8277 !CandidateSet.getRewriteInfo().shouldAddReversed( 8278 *this, {Args[1], Args[0]}, Oper->getAsFunction())) 8279 continue; 8280 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 8281 Args[0]->Classify(Context), Args.slice(1), 8282 CandidateSet, /*SuppressUserConversion=*/false, PO); 8283 } 8284 } 8285 } 8286 8287 /// AddBuiltinCandidate - Add a candidate for a built-in 8288 /// operator. ResultTy and ParamTys are the result and parameter types 8289 /// of the built-in candidate, respectively. Args and NumArgs are the 8290 /// arguments being passed to the candidate. IsAssignmentOperator 8291 /// should be true when this built-in candidate is an assignment 8292 /// operator. NumContextualBoolArguments is the number of arguments 8293 /// (at the beginning of the argument list) that will be contextually 8294 /// converted to bool. 8295 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 8296 OverloadCandidateSet& CandidateSet, 8297 bool IsAssignmentOperator, 8298 unsigned NumContextualBoolArguments) { 8299 // Overload resolution is always an unevaluated context. 8300 EnterExpressionEvaluationContext Unevaluated( 8301 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8302 8303 // Add this candidate 8304 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 8305 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 8306 Candidate.Function = nullptr; 8307 Candidate.IsSurrogate = false; 8308 Candidate.IgnoreObjectArgument = false; 8309 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 8310 8311 // Determine the implicit conversion sequences for each of the 8312 // arguments. 8313 Candidate.Viable = true; 8314 Candidate.ExplicitCallArguments = Args.size(); 8315 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8316 // C++ [over.match.oper]p4: 8317 // For the built-in assignment operators, conversions of the 8318 // left operand are restricted as follows: 8319 // -- no temporaries are introduced to hold the left operand, and 8320 // -- no user-defined conversions are applied to the left 8321 // operand to achieve a type match with the left-most 8322 // parameter of a built-in candidate. 8323 // 8324 // We block these conversions by turning off user-defined 8325 // conversions, since that is the only way that initialization of 8326 // a reference to a non-class type can occur from something that 8327 // is not of the same type. 8328 if (ArgIdx < NumContextualBoolArguments) { 8329 assert(ParamTys[ArgIdx] == Context.BoolTy && 8330 "Contextual conversion to bool requires bool type"); 8331 Candidate.Conversions[ArgIdx] 8332 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 8333 } else { 8334 Candidate.Conversions[ArgIdx] 8335 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 8336 ArgIdx == 0 && IsAssignmentOperator, 8337 /*InOverloadResolution=*/false, 8338 /*AllowObjCWritebackConversion=*/ 8339 getLangOpts().ObjCAutoRefCount); 8340 } 8341 if (Candidate.Conversions[ArgIdx].isBad()) { 8342 Candidate.Viable = false; 8343 Candidate.FailureKind = ovl_fail_bad_conversion; 8344 break; 8345 } 8346 } 8347 } 8348 8349 namespace { 8350 8351 /// BuiltinCandidateTypeSet - A set of types that will be used for the 8352 /// candidate operator functions for built-in operators (C++ 8353 /// [over.built]). The types are separated into pointer types and 8354 /// enumeration types. 8355 class BuiltinCandidateTypeSet { 8356 /// TypeSet - A set of types. 8357 typedef llvm::SmallSetVector<QualType, 8> TypeSet; 8358 8359 /// PointerTypes - The set of pointer types that will be used in the 8360 /// built-in candidates. 8361 TypeSet PointerTypes; 8362 8363 /// MemberPointerTypes - The set of member pointer types that will be 8364 /// used in the built-in candidates. 8365 TypeSet MemberPointerTypes; 8366 8367 /// EnumerationTypes - The set of enumeration types that will be 8368 /// used in the built-in candidates. 8369 TypeSet EnumerationTypes; 8370 8371 /// The set of vector types that will be used in the built-in 8372 /// candidates. 8373 TypeSet VectorTypes; 8374 8375 /// The set of matrix types that will be used in the built-in 8376 /// candidates. 8377 TypeSet MatrixTypes; 8378 8379 /// A flag indicating non-record types are viable candidates 8380 bool HasNonRecordTypes; 8381 8382 /// A flag indicating whether either arithmetic or enumeration types 8383 /// were present in the candidate set. 8384 bool HasArithmeticOrEnumeralTypes; 8385 8386 /// A flag indicating whether the nullptr type was present in the 8387 /// candidate set. 8388 bool HasNullPtrType; 8389 8390 /// Sema - The semantic analysis instance where we are building the 8391 /// candidate type set. 8392 Sema &SemaRef; 8393 8394 /// Context - The AST context in which we will build the type sets. 8395 ASTContext &Context; 8396 8397 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8398 const Qualifiers &VisibleQuals); 8399 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 8400 8401 public: 8402 /// iterator - Iterates through the types that are part of the set. 8403 typedef TypeSet::iterator iterator; 8404 8405 BuiltinCandidateTypeSet(Sema &SemaRef) 8406 : HasNonRecordTypes(false), 8407 HasArithmeticOrEnumeralTypes(false), 8408 HasNullPtrType(false), 8409 SemaRef(SemaRef), 8410 Context(SemaRef.Context) { } 8411 8412 void AddTypesConvertedFrom(QualType Ty, 8413 SourceLocation Loc, 8414 bool AllowUserConversions, 8415 bool AllowExplicitConversions, 8416 const Qualifiers &VisibleTypeConversionsQuals); 8417 8418 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 8419 llvm::iterator_range<iterator> member_pointer_types() { 8420 return MemberPointerTypes; 8421 } 8422 llvm::iterator_range<iterator> enumeration_types() { 8423 return EnumerationTypes; 8424 } 8425 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 8426 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 8427 8428 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 8429 bool hasNonRecordTypes() { return HasNonRecordTypes; } 8430 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 8431 bool hasNullPtrType() const { return HasNullPtrType; } 8432 }; 8433 8434 } // end anonymous namespace 8435 8436 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 8437 /// the set of pointer types along with any more-qualified variants of 8438 /// that type. For example, if @p Ty is "int const *", this routine 8439 /// will add "int const *", "int const volatile *", "int const 8440 /// restrict *", and "int const volatile restrict *" to the set of 8441 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8442 /// false otherwise. 8443 /// 8444 /// FIXME: what to do about extended qualifiers? 8445 bool 8446 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8447 const Qualifiers &VisibleQuals) { 8448 8449 // Insert this type. 8450 if (!PointerTypes.insert(Ty)) 8451 return false; 8452 8453 QualType PointeeTy; 8454 const PointerType *PointerTy = Ty->getAs<PointerType>(); 8455 bool buildObjCPtr = false; 8456 if (!PointerTy) { 8457 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 8458 PointeeTy = PTy->getPointeeType(); 8459 buildObjCPtr = true; 8460 } else { 8461 PointeeTy = PointerTy->getPointeeType(); 8462 } 8463 8464 // Don't add qualified variants of arrays. For one, they're not allowed 8465 // (the qualifier would sink to the element type), and for another, the 8466 // only overload situation where it matters is subscript or pointer +- int, 8467 // and those shouldn't have qualifier variants anyway. 8468 if (PointeeTy->isArrayType()) 8469 return true; 8470 8471 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8472 bool hasVolatile = VisibleQuals.hasVolatile(); 8473 bool hasRestrict = VisibleQuals.hasRestrict(); 8474 8475 // Iterate through all strict supersets of BaseCVR. 8476 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8477 if ((CVR | BaseCVR) != CVR) continue; 8478 // Skip over volatile if no volatile found anywhere in the types. 8479 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 8480 8481 // Skip over restrict if no restrict found anywhere in the types, or if 8482 // the type cannot be restrict-qualified. 8483 if ((CVR & Qualifiers::Restrict) && 8484 (!hasRestrict || 8485 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 8486 continue; 8487 8488 // Build qualified pointee type. 8489 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8490 8491 // Build qualified pointer type. 8492 QualType QPointerTy; 8493 if (!buildObjCPtr) 8494 QPointerTy = Context.getPointerType(QPointeeTy); 8495 else 8496 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 8497 8498 // Insert qualified pointer type. 8499 PointerTypes.insert(QPointerTy); 8500 } 8501 8502 return true; 8503 } 8504 8505 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 8506 /// to the set of pointer types along with any more-qualified variants of 8507 /// that type. For example, if @p Ty is "int const *", this routine 8508 /// will add "int const *", "int const volatile *", "int const 8509 /// restrict *", and "int const volatile restrict *" to the set of 8510 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8511 /// false otherwise. 8512 /// 8513 /// FIXME: what to do about extended qualifiers? 8514 bool 8515 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 8516 QualType Ty) { 8517 // Insert this type. 8518 if (!MemberPointerTypes.insert(Ty)) 8519 return false; 8520 8521 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8522 assert(PointerTy && "type was not a member pointer type!"); 8523 8524 QualType PointeeTy = PointerTy->getPointeeType(); 8525 // Don't add qualified variants of arrays. For one, they're not allowed 8526 // (the qualifier would sink to the element type), and for another, the 8527 // only overload situation where it matters is subscript or pointer +- int, 8528 // and those shouldn't have qualifier variants anyway. 8529 if (PointeeTy->isArrayType()) 8530 return true; 8531 const Type *ClassTy = PointerTy->getClass(); 8532 8533 // Iterate through all strict supersets of the pointee type's CVR 8534 // qualifiers. 8535 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8536 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8537 if ((CVR | BaseCVR) != CVR) continue; 8538 8539 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8540 MemberPointerTypes.insert( 8541 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8542 } 8543 8544 return true; 8545 } 8546 8547 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8548 /// Ty can be implicit converted to the given set of @p Types. We're 8549 /// primarily interested in pointer types and enumeration types. We also 8550 /// take member pointer types, for the conditional operator. 8551 /// AllowUserConversions is true if we should look at the conversion 8552 /// functions of a class type, and AllowExplicitConversions if we 8553 /// should also include the explicit conversion functions of a class 8554 /// type. 8555 void 8556 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8557 SourceLocation Loc, 8558 bool AllowUserConversions, 8559 bool AllowExplicitConversions, 8560 const Qualifiers &VisibleQuals) { 8561 // Only deal with canonical types. 8562 Ty = Context.getCanonicalType(Ty); 8563 8564 // Look through reference types; they aren't part of the type of an 8565 // expression for the purposes of conversions. 8566 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8567 Ty = RefTy->getPointeeType(); 8568 8569 // If we're dealing with an array type, decay to the pointer. 8570 if (Ty->isArrayType()) 8571 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8572 8573 // Otherwise, we don't care about qualifiers on the type. 8574 Ty = Ty.getLocalUnqualifiedType(); 8575 8576 // Flag if we ever add a non-record type. 8577 const RecordType *TyRec = Ty->getAs<RecordType>(); 8578 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8579 8580 // Flag if we encounter an arithmetic type. 8581 HasArithmeticOrEnumeralTypes = 8582 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8583 8584 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8585 PointerTypes.insert(Ty); 8586 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8587 // Insert our type, and its more-qualified variants, into the set 8588 // of types. 8589 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8590 return; 8591 } else if (Ty->isMemberPointerType()) { 8592 // Member pointers are far easier, since the pointee can't be converted. 8593 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8594 return; 8595 } else if (Ty->isEnumeralType()) { 8596 HasArithmeticOrEnumeralTypes = true; 8597 EnumerationTypes.insert(Ty); 8598 } else if (Ty->isVectorType()) { 8599 // We treat vector types as arithmetic types in many contexts as an 8600 // extension. 8601 HasArithmeticOrEnumeralTypes = true; 8602 VectorTypes.insert(Ty); 8603 } else if (Ty->isMatrixType()) { 8604 // Similar to vector types, we treat vector types as arithmetic types in 8605 // many contexts as an extension. 8606 HasArithmeticOrEnumeralTypes = true; 8607 MatrixTypes.insert(Ty); 8608 } else if (Ty->isNullPtrType()) { 8609 HasNullPtrType = true; 8610 } else if (AllowUserConversions && TyRec) { 8611 // No conversion functions in incomplete types. 8612 if (!SemaRef.isCompleteType(Loc, Ty)) 8613 return; 8614 8615 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8616 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8617 if (isa<UsingShadowDecl>(D)) 8618 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8619 8620 // Skip conversion function templates; they don't tell us anything 8621 // about which builtin types we can convert to. 8622 if (isa<FunctionTemplateDecl>(D)) 8623 continue; 8624 8625 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8626 if (AllowExplicitConversions || !Conv->isExplicit()) { 8627 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8628 VisibleQuals); 8629 } 8630 } 8631 } 8632 } 8633 /// Helper function for adjusting address spaces for the pointer or reference 8634 /// operands of builtin operators depending on the argument. 8635 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8636 Expr *Arg) { 8637 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8638 } 8639 8640 /// Helper function for AddBuiltinOperatorCandidates() that adds 8641 /// the volatile- and non-volatile-qualified assignment operators for the 8642 /// given type to the candidate set. 8643 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8644 QualType T, 8645 ArrayRef<Expr *> Args, 8646 OverloadCandidateSet &CandidateSet) { 8647 QualType ParamTypes[2]; 8648 8649 // T& operator=(T&, T) 8650 ParamTypes[0] = S.Context.getLValueReferenceType( 8651 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8652 ParamTypes[1] = T; 8653 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8654 /*IsAssignmentOperator=*/true); 8655 8656 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8657 // volatile T& operator=(volatile T&, T) 8658 ParamTypes[0] = S.Context.getLValueReferenceType( 8659 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8660 Args[0])); 8661 ParamTypes[1] = T; 8662 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8663 /*IsAssignmentOperator=*/true); 8664 } 8665 } 8666 8667 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8668 /// if any, found in visible type conversion functions found in ArgExpr's type. 8669 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8670 Qualifiers VRQuals; 8671 const RecordType *TyRec; 8672 if (const MemberPointerType *RHSMPType = 8673 ArgExpr->getType()->getAs<MemberPointerType>()) 8674 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8675 else 8676 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8677 if (!TyRec) { 8678 // Just to be safe, assume the worst case. 8679 VRQuals.addVolatile(); 8680 VRQuals.addRestrict(); 8681 return VRQuals; 8682 } 8683 8684 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8685 if (!ClassDecl->hasDefinition()) 8686 return VRQuals; 8687 8688 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8689 if (isa<UsingShadowDecl>(D)) 8690 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8691 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8692 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8693 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8694 CanTy = ResTypeRef->getPointeeType(); 8695 // Need to go down the pointer/mempointer chain and add qualifiers 8696 // as see them. 8697 bool done = false; 8698 while (!done) { 8699 if (CanTy.isRestrictQualified()) 8700 VRQuals.addRestrict(); 8701 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8702 CanTy = ResTypePtr->getPointeeType(); 8703 else if (const MemberPointerType *ResTypeMPtr = 8704 CanTy->getAs<MemberPointerType>()) 8705 CanTy = ResTypeMPtr->getPointeeType(); 8706 else 8707 done = true; 8708 if (CanTy.isVolatileQualified()) 8709 VRQuals.addVolatile(); 8710 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8711 return VRQuals; 8712 } 8713 } 8714 } 8715 return VRQuals; 8716 } 8717 8718 // Note: We're currently only handling qualifiers that are meaningful for the 8719 // LHS of compound assignment overloading. 8720 static void forAllQualifierCombinationsImpl( 8721 QualifiersAndAtomic Available, QualifiersAndAtomic Applied, 8722 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8723 // _Atomic 8724 if (Available.hasAtomic()) { 8725 Available.removeAtomic(); 8726 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); 8727 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8728 return; 8729 } 8730 8731 // volatile 8732 if (Available.hasVolatile()) { 8733 Available.removeVolatile(); 8734 assert(!Applied.hasVolatile()); 8735 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), 8736 Callback); 8737 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8738 return; 8739 } 8740 8741 Callback(Applied); 8742 } 8743 8744 static void forAllQualifierCombinations( 8745 QualifiersAndAtomic Quals, 8746 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8747 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), 8748 Callback); 8749 } 8750 8751 static QualType makeQualifiedLValueReferenceType(QualType Base, 8752 QualifiersAndAtomic Quals, 8753 Sema &S) { 8754 if (Quals.hasAtomic()) 8755 Base = S.Context.getAtomicType(Base); 8756 if (Quals.hasVolatile()) 8757 Base = S.Context.getVolatileType(Base); 8758 return S.Context.getLValueReferenceType(Base); 8759 } 8760 8761 namespace { 8762 8763 /// Helper class to manage the addition of builtin operator overload 8764 /// candidates. It provides shared state and utility methods used throughout 8765 /// the process, as well as a helper method to add each group of builtin 8766 /// operator overloads from the standard to a candidate set. 8767 class BuiltinOperatorOverloadBuilder { 8768 // Common instance state available to all overload candidate addition methods. 8769 Sema &S; 8770 ArrayRef<Expr *> Args; 8771 QualifiersAndAtomic VisibleTypeConversionsQuals; 8772 bool HasArithmeticOrEnumeralCandidateType; 8773 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8774 OverloadCandidateSet &CandidateSet; 8775 8776 static constexpr int ArithmeticTypesCap = 24; 8777 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8778 8779 // Define some indices used to iterate over the arithmetic types in 8780 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8781 // types are that preserved by promotion (C++ [over.built]p2). 8782 unsigned FirstIntegralType, 8783 LastIntegralType; 8784 unsigned FirstPromotedIntegralType, 8785 LastPromotedIntegralType; 8786 unsigned FirstPromotedArithmeticType, 8787 LastPromotedArithmeticType; 8788 unsigned NumArithmeticTypes; 8789 8790 void InitArithmeticTypes() { 8791 // Start of promoted types. 8792 FirstPromotedArithmeticType = 0; 8793 ArithmeticTypes.push_back(S.Context.FloatTy); 8794 ArithmeticTypes.push_back(S.Context.DoubleTy); 8795 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8796 if (S.Context.getTargetInfo().hasFloat128Type()) 8797 ArithmeticTypes.push_back(S.Context.Float128Ty); 8798 if (S.Context.getTargetInfo().hasIbm128Type()) 8799 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8800 8801 // Start of integral types. 8802 FirstIntegralType = ArithmeticTypes.size(); 8803 FirstPromotedIntegralType = ArithmeticTypes.size(); 8804 ArithmeticTypes.push_back(S.Context.IntTy); 8805 ArithmeticTypes.push_back(S.Context.LongTy); 8806 ArithmeticTypes.push_back(S.Context.LongLongTy); 8807 if (S.Context.getTargetInfo().hasInt128Type() || 8808 (S.Context.getAuxTargetInfo() && 8809 S.Context.getAuxTargetInfo()->hasInt128Type())) 8810 ArithmeticTypes.push_back(S.Context.Int128Ty); 8811 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8812 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8813 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8814 if (S.Context.getTargetInfo().hasInt128Type() || 8815 (S.Context.getAuxTargetInfo() && 8816 S.Context.getAuxTargetInfo()->hasInt128Type())) 8817 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8818 LastPromotedIntegralType = ArithmeticTypes.size(); 8819 LastPromotedArithmeticType = ArithmeticTypes.size(); 8820 // End of promoted types. 8821 8822 ArithmeticTypes.push_back(S.Context.BoolTy); 8823 ArithmeticTypes.push_back(S.Context.CharTy); 8824 ArithmeticTypes.push_back(S.Context.WCharTy); 8825 if (S.Context.getLangOpts().Char8) 8826 ArithmeticTypes.push_back(S.Context.Char8Ty); 8827 ArithmeticTypes.push_back(S.Context.Char16Ty); 8828 ArithmeticTypes.push_back(S.Context.Char32Ty); 8829 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8830 ArithmeticTypes.push_back(S.Context.ShortTy); 8831 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8832 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8833 LastIntegralType = ArithmeticTypes.size(); 8834 NumArithmeticTypes = ArithmeticTypes.size(); 8835 // End of integral types. 8836 // FIXME: What about complex? What about half? 8837 8838 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8839 "Enough inline storage for all arithmetic types."); 8840 } 8841 8842 /// Helper method to factor out the common pattern of adding overloads 8843 /// for '++' and '--' builtin operators. 8844 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8845 bool HasVolatile, 8846 bool HasRestrict) { 8847 QualType ParamTypes[2] = { 8848 S.Context.getLValueReferenceType(CandidateTy), 8849 S.Context.IntTy 8850 }; 8851 8852 // Non-volatile version. 8853 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8854 8855 // Use a heuristic to reduce number of builtin candidates in the set: 8856 // add volatile version only if there are conversions to a volatile type. 8857 if (HasVolatile) { 8858 ParamTypes[0] = 8859 S.Context.getLValueReferenceType( 8860 S.Context.getVolatileType(CandidateTy)); 8861 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8862 } 8863 8864 // Add restrict version only if there are conversions to a restrict type 8865 // and our candidate type is a non-restrict-qualified pointer. 8866 if (HasRestrict && CandidateTy->isAnyPointerType() && 8867 !CandidateTy.isRestrictQualified()) { 8868 ParamTypes[0] 8869 = S.Context.getLValueReferenceType( 8870 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8871 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8872 8873 if (HasVolatile) { 8874 ParamTypes[0] 8875 = S.Context.getLValueReferenceType( 8876 S.Context.getCVRQualifiedType(CandidateTy, 8877 (Qualifiers::Volatile | 8878 Qualifiers::Restrict))); 8879 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8880 } 8881 } 8882 8883 } 8884 8885 /// Helper to add an overload candidate for a binary builtin with types \p L 8886 /// and \p R. 8887 void AddCandidate(QualType L, QualType R) { 8888 QualType LandR[2] = {L, R}; 8889 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8890 } 8891 8892 public: 8893 BuiltinOperatorOverloadBuilder( 8894 Sema &S, ArrayRef<Expr *> Args, 8895 QualifiersAndAtomic VisibleTypeConversionsQuals, 8896 bool HasArithmeticOrEnumeralCandidateType, 8897 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8898 OverloadCandidateSet &CandidateSet) 8899 : S(S), Args(Args), 8900 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8901 HasArithmeticOrEnumeralCandidateType( 8902 HasArithmeticOrEnumeralCandidateType), 8903 CandidateTypes(CandidateTypes), 8904 CandidateSet(CandidateSet) { 8905 8906 InitArithmeticTypes(); 8907 } 8908 8909 // Increment is deprecated for bool since C++17. 8910 // 8911 // C++ [over.built]p3: 8912 // 8913 // For every pair (T, VQ), where T is an arithmetic type other 8914 // than bool, and VQ is either volatile or empty, there exist 8915 // candidate operator functions of the form 8916 // 8917 // VQ T& operator++(VQ T&); 8918 // T operator++(VQ T&, int); 8919 // 8920 // C++ [over.built]p4: 8921 // 8922 // For every pair (T, VQ), where T is an arithmetic type other 8923 // than bool, and VQ is either volatile or empty, there exist 8924 // candidate operator functions of the form 8925 // 8926 // VQ T& operator--(VQ T&); 8927 // T operator--(VQ T&, int); 8928 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8929 if (!HasArithmeticOrEnumeralCandidateType) 8930 return; 8931 8932 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8933 const auto TypeOfT = ArithmeticTypes[Arith]; 8934 if (TypeOfT == S.Context.BoolTy) { 8935 if (Op == OO_MinusMinus) 8936 continue; 8937 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8938 continue; 8939 } 8940 addPlusPlusMinusMinusStyleOverloads( 8941 TypeOfT, 8942 VisibleTypeConversionsQuals.hasVolatile(), 8943 VisibleTypeConversionsQuals.hasRestrict()); 8944 } 8945 } 8946 8947 // C++ [over.built]p5: 8948 // 8949 // For every pair (T, VQ), where T is a cv-qualified or 8950 // cv-unqualified object type, and VQ is either volatile or 8951 // empty, there exist candidate operator functions of the form 8952 // 8953 // T*VQ& operator++(T*VQ&); 8954 // T*VQ& operator--(T*VQ&); 8955 // T* operator++(T*VQ&, int); 8956 // T* operator--(T*VQ&, int); 8957 void addPlusPlusMinusMinusPointerOverloads() { 8958 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8959 // Skip pointer types that aren't pointers to object types. 8960 if (!PtrTy->getPointeeType()->isObjectType()) 8961 continue; 8962 8963 addPlusPlusMinusMinusStyleOverloads( 8964 PtrTy, 8965 (!PtrTy.isVolatileQualified() && 8966 VisibleTypeConversionsQuals.hasVolatile()), 8967 (!PtrTy.isRestrictQualified() && 8968 VisibleTypeConversionsQuals.hasRestrict())); 8969 } 8970 } 8971 8972 // C++ [over.built]p6: 8973 // For every cv-qualified or cv-unqualified object type T, there 8974 // exist candidate operator functions of the form 8975 // 8976 // T& operator*(T*); 8977 // 8978 // C++ [over.built]p7: 8979 // For every function type T that does not have cv-qualifiers or a 8980 // ref-qualifier, there exist candidate operator functions of the form 8981 // T& operator*(T*); 8982 void addUnaryStarPointerOverloads() { 8983 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8984 QualType PointeeTy = ParamTy->getPointeeType(); 8985 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8986 continue; 8987 8988 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8989 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8990 continue; 8991 8992 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8993 } 8994 } 8995 8996 // C++ [over.built]p9: 8997 // For every promoted arithmetic type T, there exist candidate 8998 // operator functions of the form 8999 // 9000 // T operator+(T); 9001 // T operator-(T); 9002 void addUnaryPlusOrMinusArithmeticOverloads() { 9003 if (!HasArithmeticOrEnumeralCandidateType) 9004 return; 9005 9006 for (unsigned Arith = FirstPromotedArithmeticType; 9007 Arith < LastPromotedArithmeticType; ++Arith) { 9008 QualType ArithTy = ArithmeticTypes[Arith]; 9009 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 9010 } 9011 9012 // Extension: We also add these operators for vector types. 9013 for (QualType VecTy : CandidateTypes[0].vector_types()) 9014 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 9015 } 9016 9017 // C++ [over.built]p8: 9018 // For every type T, there exist candidate operator functions of 9019 // the form 9020 // 9021 // T* operator+(T*); 9022 void addUnaryPlusPointerOverloads() { 9023 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 9024 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 9025 } 9026 9027 // C++ [over.built]p10: 9028 // For every promoted integral type T, there exist candidate 9029 // operator functions of the form 9030 // 9031 // T operator~(T); 9032 void addUnaryTildePromotedIntegralOverloads() { 9033 if (!HasArithmeticOrEnumeralCandidateType) 9034 return; 9035 9036 for (unsigned Int = FirstPromotedIntegralType; 9037 Int < LastPromotedIntegralType; ++Int) { 9038 QualType IntTy = ArithmeticTypes[Int]; 9039 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 9040 } 9041 9042 // Extension: We also add this operator for vector types. 9043 for (QualType VecTy : CandidateTypes[0].vector_types()) 9044 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 9045 } 9046 9047 // C++ [over.match.oper]p16: 9048 // For every pointer to member type T or type std::nullptr_t, there 9049 // exist candidate operator functions of the form 9050 // 9051 // bool operator==(T,T); 9052 // bool operator!=(T,T); 9053 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 9054 /// Set of (canonical) types that we've already handled. 9055 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9056 9057 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9058 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9059 // Don't add the same builtin candidate twice. 9060 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9061 continue; 9062 9063 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9064 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9065 } 9066 9067 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 9068 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 9069 if (AddedTypes.insert(NullPtrTy).second) { 9070 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 9071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9072 } 9073 } 9074 } 9075 } 9076 9077 // C++ [over.built]p15: 9078 // 9079 // For every T, where T is an enumeration type or a pointer type, 9080 // there exist candidate operator functions of the form 9081 // 9082 // bool operator<(T, T); 9083 // bool operator>(T, T); 9084 // bool operator<=(T, T); 9085 // bool operator>=(T, T); 9086 // bool operator==(T, T); 9087 // bool operator!=(T, T); 9088 // R operator<=>(T, T) 9089 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 9090 // C++ [over.match.oper]p3: 9091 // [...]the built-in candidates include all of the candidate operator 9092 // functions defined in 13.6 that, compared to the given operator, [...] 9093 // do not have the same parameter-type-list as any non-template non-member 9094 // candidate. 9095 // 9096 // Note that in practice, this only affects enumeration types because there 9097 // aren't any built-in candidates of record type, and a user-defined operator 9098 // must have an operand of record or enumeration type. Also, the only other 9099 // overloaded operator with enumeration arguments, operator=, 9100 // cannot be overloaded for enumeration types, so this is the only place 9101 // where we must suppress candidates like this. 9102 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 9103 UserDefinedBinaryOperators; 9104 9105 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9106 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 9107 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 9108 CEnd = CandidateSet.end(); 9109 C != CEnd; ++C) { 9110 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 9111 continue; 9112 9113 if (C->Function->isFunctionTemplateSpecialization()) 9114 continue; 9115 9116 // We interpret "same parameter-type-list" as applying to the 9117 // "synthesized candidate, with the order of the two parameters 9118 // reversed", not to the original function. 9119 bool Reversed = C->isReversed(); 9120 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 9121 ->getType() 9122 .getUnqualifiedType(); 9123 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 9124 ->getType() 9125 .getUnqualifiedType(); 9126 9127 // Skip if either parameter isn't of enumeral type. 9128 if (!FirstParamType->isEnumeralType() || 9129 !SecondParamType->isEnumeralType()) 9130 continue; 9131 9132 // Add this operator to the set of known user-defined operators. 9133 UserDefinedBinaryOperators.insert( 9134 std::make_pair(S.Context.getCanonicalType(FirstParamType), 9135 S.Context.getCanonicalType(SecondParamType))); 9136 } 9137 } 9138 } 9139 9140 /// Set of (canonical) types that we've already handled. 9141 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9142 9143 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9144 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9145 // Don't add the same builtin candidate twice. 9146 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9147 continue; 9148 if (IsSpaceship && PtrTy->isFunctionPointerType()) 9149 continue; 9150 9151 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9152 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9153 } 9154 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9155 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 9156 9157 // Don't add the same builtin candidate twice, or if a user defined 9158 // candidate exists. 9159 if (!AddedTypes.insert(CanonType).second || 9160 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 9161 CanonType))) 9162 continue; 9163 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9164 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9165 } 9166 } 9167 } 9168 9169 // C++ [over.built]p13: 9170 // 9171 // For every cv-qualified or cv-unqualified object type T 9172 // there exist candidate operator functions of the form 9173 // 9174 // T* operator+(T*, ptrdiff_t); 9175 // T& operator[](T*, ptrdiff_t); [BELOW] 9176 // T* operator-(T*, ptrdiff_t); 9177 // T* operator+(ptrdiff_t, T*); 9178 // T& operator[](ptrdiff_t, T*); [BELOW] 9179 // 9180 // C++ [over.built]p14: 9181 // 9182 // For every T, where T is a pointer to object type, there 9183 // exist candidate operator functions of the form 9184 // 9185 // ptrdiff_t operator-(T, T); 9186 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 9187 /// Set of (canonical) types that we've already handled. 9188 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9189 9190 for (int Arg = 0; Arg < 2; ++Arg) { 9191 QualType AsymmetricParamTypes[2] = { 9192 S.Context.getPointerDiffType(), 9193 S.Context.getPointerDiffType(), 9194 }; 9195 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 9196 QualType PointeeTy = PtrTy->getPointeeType(); 9197 if (!PointeeTy->isObjectType()) 9198 continue; 9199 9200 AsymmetricParamTypes[Arg] = PtrTy; 9201 if (Arg == 0 || Op == OO_Plus) { 9202 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 9203 // T* operator+(ptrdiff_t, T*); 9204 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 9205 } 9206 if (Op == OO_Minus) { 9207 // ptrdiff_t operator-(T, T); 9208 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9209 continue; 9210 9211 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9212 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9213 } 9214 } 9215 } 9216 } 9217 9218 // C++ [over.built]p12: 9219 // 9220 // For every pair of promoted arithmetic types L and R, there 9221 // exist candidate operator functions of the form 9222 // 9223 // LR operator*(L, R); 9224 // LR operator/(L, R); 9225 // LR operator+(L, R); 9226 // LR operator-(L, R); 9227 // bool operator<(L, R); 9228 // bool operator>(L, R); 9229 // bool operator<=(L, R); 9230 // bool operator>=(L, R); 9231 // bool operator==(L, R); 9232 // bool operator!=(L, R); 9233 // 9234 // where LR is the result of the usual arithmetic conversions 9235 // between types L and R. 9236 // 9237 // C++ [over.built]p24: 9238 // 9239 // For every pair of promoted arithmetic types L and R, there exist 9240 // candidate operator functions of the form 9241 // 9242 // LR operator?(bool, L, R); 9243 // 9244 // where LR is the result of the usual arithmetic conversions 9245 // between types L and R. 9246 // Our candidates ignore the first parameter. 9247 void addGenericBinaryArithmeticOverloads() { 9248 if (!HasArithmeticOrEnumeralCandidateType) 9249 return; 9250 9251 for (unsigned Left = FirstPromotedArithmeticType; 9252 Left < LastPromotedArithmeticType; ++Left) { 9253 for (unsigned Right = FirstPromotedArithmeticType; 9254 Right < LastPromotedArithmeticType; ++Right) { 9255 QualType LandR[2] = { ArithmeticTypes[Left], 9256 ArithmeticTypes[Right] }; 9257 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9258 } 9259 } 9260 9261 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 9262 // conditional operator for vector types. 9263 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9264 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 9265 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 9266 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9267 } 9268 } 9269 9270 /// Add binary operator overloads for each candidate matrix type M1, M2: 9271 /// * (M1, M1) -> M1 9272 /// * (M1, M1.getElementType()) -> M1 9273 /// * (M2.getElementType(), M2) -> M2 9274 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 9275 void addMatrixBinaryArithmeticOverloads() { 9276 if (!HasArithmeticOrEnumeralCandidateType) 9277 return; 9278 9279 for (QualType M1 : CandidateTypes[0].matrix_types()) { 9280 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 9281 AddCandidate(M1, M1); 9282 } 9283 9284 for (QualType M2 : CandidateTypes[1].matrix_types()) { 9285 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 9286 if (!CandidateTypes[0].containsMatrixType(M2)) 9287 AddCandidate(M2, M2); 9288 } 9289 } 9290 9291 // C++2a [over.built]p14: 9292 // 9293 // For every integral type T there exists a candidate operator function 9294 // of the form 9295 // 9296 // std::strong_ordering operator<=>(T, T) 9297 // 9298 // C++2a [over.built]p15: 9299 // 9300 // For every pair of floating-point types L and R, there exists a candidate 9301 // operator function of the form 9302 // 9303 // std::partial_ordering operator<=>(L, R); 9304 // 9305 // FIXME: The current specification for integral types doesn't play nice with 9306 // the direction of p0946r0, which allows mixed integral and unscoped-enum 9307 // comparisons. Under the current spec this can lead to ambiguity during 9308 // overload resolution. For example: 9309 // 9310 // enum A : int {a}; 9311 // auto x = (a <=> (long)42); 9312 // 9313 // error: call is ambiguous for arguments 'A' and 'long'. 9314 // note: candidate operator<=>(int, int) 9315 // note: candidate operator<=>(long, long) 9316 // 9317 // To avoid this error, this function deviates from the specification and adds 9318 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 9319 // arithmetic types (the same as the generic relational overloads). 9320 // 9321 // For now this function acts as a placeholder. 9322 void addThreeWayArithmeticOverloads() { 9323 addGenericBinaryArithmeticOverloads(); 9324 } 9325 9326 // C++ [over.built]p17: 9327 // 9328 // For every pair of promoted integral types L and R, there 9329 // exist candidate operator functions of the form 9330 // 9331 // LR operator%(L, R); 9332 // LR operator&(L, R); 9333 // LR operator^(L, R); 9334 // LR operator|(L, R); 9335 // L operator<<(L, R); 9336 // L operator>>(L, R); 9337 // 9338 // where LR is the result of the usual arithmetic conversions 9339 // between types L and R. 9340 void addBinaryBitwiseArithmeticOverloads() { 9341 if (!HasArithmeticOrEnumeralCandidateType) 9342 return; 9343 9344 for (unsigned Left = FirstPromotedIntegralType; 9345 Left < LastPromotedIntegralType; ++Left) { 9346 for (unsigned Right = FirstPromotedIntegralType; 9347 Right < LastPromotedIntegralType; ++Right) { 9348 QualType LandR[2] = { ArithmeticTypes[Left], 9349 ArithmeticTypes[Right] }; 9350 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9351 } 9352 } 9353 } 9354 9355 // C++ [over.built]p20: 9356 // 9357 // For every pair (T, VQ), where T is an enumeration or 9358 // pointer to member type and VQ is either volatile or 9359 // empty, there exist candidate operator functions of the form 9360 // 9361 // VQ T& operator=(VQ T&, T); 9362 void addAssignmentMemberPointerOrEnumeralOverloads() { 9363 /// Set of (canonical) types that we've already handled. 9364 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9365 9366 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9367 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9368 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9369 continue; 9370 9371 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 9372 } 9373 9374 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9375 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9376 continue; 9377 9378 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 9379 } 9380 } 9381 } 9382 9383 // C++ [over.built]p19: 9384 // 9385 // For every pair (T, VQ), where T is any type and VQ is either 9386 // volatile or empty, there exist candidate operator functions 9387 // of the form 9388 // 9389 // T*VQ& operator=(T*VQ&, T*); 9390 // 9391 // C++ [over.built]p21: 9392 // 9393 // For every pair (T, VQ), where T is a cv-qualified or 9394 // cv-unqualified object type and VQ is either volatile or 9395 // empty, there exist candidate operator functions of the form 9396 // 9397 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 9398 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 9399 void addAssignmentPointerOverloads(bool isEqualOp) { 9400 /// Set of (canonical) types that we've already handled. 9401 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9402 9403 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9404 // If this is operator=, keep track of the builtin candidates we added. 9405 if (isEqualOp) 9406 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 9407 else if (!PtrTy->getPointeeType()->isObjectType()) 9408 continue; 9409 9410 // non-volatile version 9411 QualType ParamTypes[2] = { 9412 S.Context.getLValueReferenceType(PtrTy), 9413 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 9414 }; 9415 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9416 /*IsAssignmentOperator=*/ isEqualOp); 9417 9418 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9419 VisibleTypeConversionsQuals.hasVolatile(); 9420 if (NeedVolatile) { 9421 // volatile version 9422 ParamTypes[0] = 9423 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 9424 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9425 /*IsAssignmentOperator=*/isEqualOp); 9426 } 9427 9428 if (!PtrTy.isRestrictQualified() && 9429 VisibleTypeConversionsQuals.hasRestrict()) { 9430 // restrict version 9431 ParamTypes[0] = 9432 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 9433 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9434 /*IsAssignmentOperator=*/isEqualOp); 9435 9436 if (NeedVolatile) { 9437 // volatile restrict version 9438 ParamTypes[0] = 9439 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9440 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9441 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9442 /*IsAssignmentOperator=*/isEqualOp); 9443 } 9444 } 9445 } 9446 9447 if (isEqualOp) { 9448 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9449 // Make sure we don't add the same candidate twice. 9450 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9451 continue; 9452 9453 QualType ParamTypes[2] = { 9454 S.Context.getLValueReferenceType(PtrTy), 9455 PtrTy, 9456 }; 9457 9458 // non-volatile version 9459 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9460 /*IsAssignmentOperator=*/true); 9461 9462 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9463 VisibleTypeConversionsQuals.hasVolatile(); 9464 if (NeedVolatile) { 9465 // volatile version 9466 ParamTypes[0] = S.Context.getLValueReferenceType( 9467 S.Context.getVolatileType(PtrTy)); 9468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9469 /*IsAssignmentOperator=*/true); 9470 } 9471 9472 if (!PtrTy.isRestrictQualified() && 9473 VisibleTypeConversionsQuals.hasRestrict()) { 9474 // restrict version 9475 ParamTypes[0] = S.Context.getLValueReferenceType( 9476 S.Context.getRestrictType(PtrTy)); 9477 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9478 /*IsAssignmentOperator=*/true); 9479 9480 if (NeedVolatile) { 9481 // volatile restrict version 9482 ParamTypes[0] = 9483 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9484 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9485 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9486 /*IsAssignmentOperator=*/true); 9487 } 9488 } 9489 } 9490 } 9491 } 9492 9493 // C++ [over.built]p18: 9494 // 9495 // For every triple (L, VQ, R), where L is an arithmetic type, 9496 // VQ is either volatile or empty, and R is a promoted 9497 // arithmetic type, there exist candidate operator functions of 9498 // the form 9499 // 9500 // VQ L& operator=(VQ L&, R); 9501 // VQ L& operator*=(VQ L&, R); 9502 // VQ L& operator/=(VQ L&, R); 9503 // VQ L& operator+=(VQ L&, R); 9504 // VQ L& operator-=(VQ L&, R); 9505 void addAssignmentArithmeticOverloads(bool isEqualOp) { 9506 if (!HasArithmeticOrEnumeralCandidateType) 9507 return; 9508 9509 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 9510 for (unsigned Right = FirstPromotedArithmeticType; 9511 Right < LastPromotedArithmeticType; ++Right) { 9512 QualType ParamTypes[2]; 9513 ParamTypes[1] = ArithmeticTypes[Right]; 9514 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9515 S, ArithmeticTypes[Left], Args[0]); 9516 9517 forAllQualifierCombinations( 9518 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9519 ParamTypes[0] = 9520 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9521 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9522 /*IsAssignmentOperator=*/isEqualOp); 9523 }); 9524 } 9525 } 9526 9527 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 9528 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9529 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 9530 QualType ParamTypes[2]; 9531 ParamTypes[1] = Vec2Ty; 9532 // Add this built-in operator as a candidate (VQ is empty). 9533 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 9534 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9535 /*IsAssignmentOperator=*/isEqualOp); 9536 9537 // Add this built-in operator as a candidate (VQ is 'volatile'). 9538 if (VisibleTypeConversionsQuals.hasVolatile()) { 9539 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 9540 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9541 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9542 /*IsAssignmentOperator=*/isEqualOp); 9543 } 9544 } 9545 } 9546 9547 // C++ [over.built]p22: 9548 // 9549 // For every triple (L, VQ, R), where L is an integral type, VQ 9550 // is either volatile or empty, and R is a promoted integral 9551 // type, there exist candidate operator functions of the form 9552 // 9553 // VQ L& operator%=(VQ L&, R); 9554 // VQ L& operator<<=(VQ L&, R); 9555 // VQ L& operator>>=(VQ L&, R); 9556 // VQ L& operator&=(VQ L&, R); 9557 // VQ L& operator^=(VQ L&, R); 9558 // VQ L& operator|=(VQ L&, R); 9559 void addAssignmentIntegralOverloads() { 9560 if (!HasArithmeticOrEnumeralCandidateType) 9561 return; 9562 9563 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9564 for (unsigned Right = FirstPromotedIntegralType; 9565 Right < LastPromotedIntegralType; ++Right) { 9566 QualType ParamTypes[2]; 9567 ParamTypes[1] = ArithmeticTypes[Right]; 9568 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9569 S, ArithmeticTypes[Left], Args[0]); 9570 9571 forAllQualifierCombinations( 9572 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9573 ParamTypes[0] = 9574 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9576 }); 9577 } 9578 } 9579 } 9580 9581 // C++ [over.operator]p23: 9582 // 9583 // There also exist candidate operator functions of the form 9584 // 9585 // bool operator!(bool); 9586 // bool operator&&(bool, bool); 9587 // bool operator||(bool, bool); 9588 void addExclaimOverload() { 9589 QualType ParamTy = S.Context.BoolTy; 9590 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9591 /*IsAssignmentOperator=*/false, 9592 /*NumContextualBoolArguments=*/1); 9593 } 9594 void addAmpAmpOrPipePipeOverload() { 9595 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9596 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9597 /*IsAssignmentOperator=*/false, 9598 /*NumContextualBoolArguments=*/2); 9599 } 9600 9601 // C++ [over.built]p13: 9602 // 9603 // For every cv-qualified or cv-unqualified object type T there 9604 // exist candidate operator functions of the form 9605 // 9606 // T* operator+(T*, ptrdiff_t); [ABOVE] 9607 // T& operator[](T*, ptrdiff_t); 9608 // T* operator-(T*, ptrdiff_t); [ABOVE] 9609 // T* operator+(ptrdiff_t, T*); [ABOVE] 9610 // T& operator[](ptrdiff_t, T*); 9611 void addSubscriptOverloads() { 9612 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9613 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9614 QualType PointeeType = PtrTy->getPointeeType(); 9615 if (!PointeeType->isObjectType()) 9616 continue; 9617 9618 // T& operator[](T*, ptrdiff_t) 9619 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9620 } 9621 9622 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9623 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9624 QualType PointeeType = PtrTy->getPointeeType(); 9625 if (!PointeeType->isObjectType()) 9626 continue; 9627 9628 // T& operator[](ptrdiff_t, T*) 9629 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9630 } 9631 } 9632 9633 // C++ [over.built]p11: 9634 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9635 // C1 is the same type as C2 or is a derived class of C2, T is an object 9636 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9637 // there exist candidate operator functions of the form 9638 // 9639 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9640 // 9641 // where CV12 is the union of CV1 and CV2. 9642 void addArrowStarOverloads() { 9643 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9644 QualType C1Ty = PtrTy; 9645 QualType C1; 9646 QualifierCollector Q1; 9647 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9648 if (!isa<RecordType>(C1)) 9649 continue; 9650 // heuristic to reduce number of builtin candidates in the set. 9651 // Add volatile/restrict version only if there are conversions to a 9652 // volatile/restrict type. 9653 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9654 continue; 9655 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9656 continue; 9657 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9658 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9659 QualType C2 = QualType(mptr->getClass(), 0); 9660 C2 = C2.getUnqualifiedType(); 9661 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9662 break; 9663 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9664 // build CV12 T& 9665 QualType T = mptr->getPointeeType(); 9666 if (!VisibleTypeConversionsQuals.hasVolatile() && 9667 T.isVolatileQualified()) 9668 continue; 9669 if (!VisibleTypeConversionsQuals.hasRestrict() && 9670 T.isRestrictQualified()) 9671 continue; 9672 T = Q1.apply(S.Context, T); 9673 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9674 } 9675 } 9676 } 9677 9678 // Note that we don't consider the first argument, since it has been 9679 // contextually converted to bool long ago. The candidates below are 9680 // therefore added as binary. 9681 // 9682 // C++ [over.built]p25: 9683 // For every type T, where T is a pointer, pointer-to-member, or scoped 9684 // enumeration type, there exist candidate operator functions of the form 9685 // 9686 // T operator?(bool, T, T); 9687 // 9688 void addConditionalOperatorOverloads() { 9689 /// Set of (canonical) types that we've already handled. 9690 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9691 9692 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9693 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9694 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9695 continue; 9696 9697 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9698 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9699 } 9700 9701 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9702 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9703 continue; 9704 9705 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9706 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9707 } 9708 9709 if (S.getLangOpts().CPlusPlus11) { 9710 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9711 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9712 continue; 9713 9714 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9715 continue; 9716 9717 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9718 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9719 } 9720 } 9721 } 9722 } 9723 }; 9724 9725 } // end anonymous namespace 9726 9727 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9728 /// operator overloads to the candidate set (C++ [over.built]), based 9729 /// on the operator @p Op and the arguments given. For example, if the 9730 /// operator is a binary '+', this routine might add "int 9731 /// operator+(int, int)" to cover integer addition. 9732 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9733 SourceLocation OpLoc, 9734 ArrayRef<Expr *> Args, 9735 OverloadCandidateSet &CandidateSet) { 9736 // Find all of the types that the arguments can convert to, but only 9737 // if the operator we're looking at has built-in operator candidates 9738 // that make use of these types. Also record whether we encounter non-record 9739 // candidate types or either arithmetic or enumeral candidate types. 9740 QualifiersAndAtomic VisibleTypeConversionsQuals; 9741 VisibleTypeConversionsQuals.addConst(); 9742 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9743 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9744 if (Args[ArgIdx]->getType()->isAtomicType()) 9745 VisibleTypeConversionsQuals.addAtomic(); 9746 } 9747 9748 bool HasNonRecordCandidateType = false; 9749 bool HasArithmeticOrEnumeralCandidateType = false; 9750 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9751 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9752 CandidateTypes.emplace_back(*this); 9753 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9754 OpLoc, 9755 true, 9756 (Op == OO_Exclaim || 9757 Op == OO_AmpAmp || 9758 Op == OO_PipePipe), 9759 VisibleTypeConversionsQuals); 9760 HasNonRecordCandidateType = HasNonRecordCandidateType || 9761 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9762 HasArithmeticOrEnumeralCandidateType = 9763 HasArithmeticOrEnumeralCandidateType || 9764 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9765 } 9766 9767 // Exit early when no non-record types have been added to the candidate set 9768 // for any of the arguments to the operator. 9769 // 9770 // We can't exit early for !, ||, or &&, since there we have always have 9771 // 'bool' overloads. 9772 if (!HasNonRecordCandidateType && 9773 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9774 return; 9775 9776 // Setup an object to manage the common state for building overloads. 9777 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9778 VisibleTypeConversionsQuals, 9779 HasArithmeticOrEnumeralCandidateType, 9780 CandidateTypes, CandidateSet); 9781 9782 // Dispatch over the operation to add in only those overloads which apply. 9783 switch (Op) { 9784 case OO_None: 9785 case NUM_OVERLOADED_OPERATORS: 9786 llvm_unreachable("Expected an overloaded operator"); 9787 9788 case OO_New: 9789 case OO_Delete: 9790 case OO_Array_New: 9791 case OO_Array_Delete: 9792 case OO_Call: 9793 llvm_unreachable( 9794 "Special operators don't use AddBuiltinOperatorCandidates"); 9795 9796 case OO_Comma: 9797 case OO_Arrow: 9798 case OO_Coawait: 9799 // C++ [over.match.oper]p3: 9800 // -- For the operator ',', the unary operator '&', the 9801 // operator '->', or the operator 'co_await', the 9802 // built-in candidates set is empty. 9803 break; 9804 9805 case OO_Plus: // '+' is either unary or binary 9806 if (Args.size() == 1) 9807 OpBuilder.addUnaryPlusPointerOverloads(); 9808 [[fallthrough]]; 9809 9810 case OO_Minus: // '-' is either unary or binary 9811 if (Args.size() == 1) { 9812 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9813 } else { 9814 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9815 OpBuilder.addGenericBinaryArithmeticOverloads(); 9816 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9817 } 9818 break; 9819 9820 case OO_Star: // '*' is either unary or binary 9821 if (Args.size() == 1) 9822 OpBuilder.addUnaryStarPointerOverloads(); 9823 else { 9824 OpBuilder.addGenericBinaryArithmeticOverloads(); 9825 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9826 } 9827 break; 9828 9829 case OO_Slash: 9830 OpBuilder.addGenericBinaryArithmeticOverloads(); 9831 break; 9832 9833 case OO_PlusPlus: 9834 case OO_MinusMinus: 9835 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9836 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9837 break; 9838 9839 case OO_EqualEqual: 9840 case OO_ExclaimEqual: 9841 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9842 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9843 OpBuilder.addGenericBinaryArithmeticOverloads(); 9844 break; 9845 9846 case OO_Less: 9847 case OO_Greater: 9848 case OO_LessEqual: 9849 case OO_GreaterEqual: 9850 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9851 OpBuilder.addGenericBinaryArithmeticOverloads(); 9852 break; 9853 9854 case OO_Spaceship: 9855 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9856 OpBuilder.addThreeWayArithmeticOverloads(); 9857 break; 9858 9859 case OO_Percent: 9860 case OO_Caret: 9861 case OO_Pipe: 9862 case OO_LessLess: 9863 case OO_GreaterGreater: 9864 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9865 break; 9866 9867 case OO_Amp: // '&' is either unary or binary 9868 if (Args.size() == 1) 9869 // C++ [over.match.oper]p3: 9870 // -- For the operator ',', the unary operator '&', or the 9871 // operator '->', the built-in candidates set is empty. 9872 break; 9873 9874 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9875 break; 9876 9877 case OO_Tilde: 9878 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9879 break; 9880 9881 case OO_Equal: 9882 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9883 [[fallthrough]]; 9884 9885 case OO_PlusEqual: 9886 case OO_MinusEqual: 9887 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9888 [[fallthrough]]; 9889 9890 case OO_StarEqual: 9891 case OO_SlashEqual: 9892 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9893 break; 9894 9895 case OO_PercentEqual: 9896 case OO_LessLessEqual: 9897 case OO_GreaterGreaterEqual: 9898 case OO_AmpEqual: 9899 case OO_CaretEqual: 9900 case OO_PipeEqual: 9901 OpBuilder.addAssignmentIntegralOverloads(); 9902 break; 9903 9904 case OO_Exclaim: 9905 OpBuilder.addExclaimOverload(); 9906 break; 9907 9908 case OO_AmpAmp: 9909 case OO_PipePipe: 9910 OpBuilder.addAmpAmpOrPipePipeOverload(); 9911 break; 9912 9913 case OO_Subscript: 9914 if (Args.size() == 2) 9915 OpBuilder.addSubscriptOverloads(); 9916 break; 9917 9918 case OO_ArrowStar: 9919 OpBuilder.addArrowStarOverloads(); 9920 break; 9921 9922 case OO_Conditional: 9923 OpBuilder.addConditionalOperatorOverloads(); 9924 OpBuilder.addGenericBinaryArithmeticOverloads(); 9925 break; 9926 } 9927 } 9928 9929 /// Add function candidates found via argument-dependent lookup 9930 /// to the set of overloading candidates. 9931 /// 9932 /// This routine performs argument-dependent name lookup based on the 9933 /// given function name (which may also be an operator name) and adds 9934 /// all of the overload candidates found by ADL to the overload 9935 /// candidate set (C++ [basic.lookup.argdep]). 9936 void 9937 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9938 SourceLocation Loc, 9939 ArrayRef<Expr *> Args, 9940 TemplateArgumentListInfo *ExplicitTemplateArgs, 9941 OverloadCandidateSet& CandidateSet, 9942 bool PartialOverloading) { 9943 ADLResult Fns; 9944 9945 // FIXME: This approach for uniquing ADL results (and removing 9946 // redundant candidates from the set) relies on pointer-equality, 9947 // which means we need to key off the canonical decl. However, 9948 // always going back to the canonical decl might not get us the 9949 // right set of default arguments. What default arguments are 9950 // we supposed to consider on ADL candidates, anyway? 9951 9952 // FIXME: Pass in the explicit template arguments? 9953 ArgumentDependentLookup(Name, Loc, Args, Fns); 9954 9955 // Erase all of the candidates we already knew about. 9956 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9957 CandEnd = CandidateSet.end(); 9958 Cand != CandEnd; ++Cand) 9959 if (Cand->Function) { 9960 Fns.erase(Cand->Function); 9961 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9962 Fns.erase(FunTmpl); 9963 } 9964 9965 // For each of the ADL candidates we found, add it to the overload 9966 // set. 9967 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9968 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9969 9970 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9971 if (ExplicitTemplateArgs) 9972 continue; 9973 9974 AddOverloadCandidate( 9975 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9976 PartialOverloading, /*AllowExplicit=*/true, 9977 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9978 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { 9979 AddOverloadCandidate( 9980 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9981 /*SuppressUserConversions=*/false, PartialOverloading, 9982 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9983 ADLCallKind::UsesADL, std::nullopt, 9984 OverloadCandidateParamOrder::Reversed); 9985 } 9986 } else { 9987 auto *FTD = cast<FunctionTemplateDecl>(*I); 9988 AddTemplateOverloadCandidate( 9989 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9990 /*SuppressUserConversions=*/false, PartialOverloading, 9991 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9992 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9993 *this, Args, FTD->getTemplatedDecl())) { 9994 AddTemplateOverloadCandidate( 9995 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9996 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9997 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9998 OverloadCandidateParamOrder::Reversed); 9999 } 10000 } 10001 } 10002 } 10003 10004 namespace { 10005 enum class Comparison { Equal, Better, Worse }; 10006 } 10007 10008 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 10009 /// overload resolution. 10010 /// 10011 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 10012 /// Cand1's first N enable_if attributes have precisely the same conditions as 10013 /// Cand2's first N enable_if attributes (where N = the number of enable_if 10014 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 10015 /// 10016 /// Note that you can have a pair of candidates such that Cand1's enable_if 10017 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 10018 /// worse than Cand1's. 10019 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 10020 const FunctionDecl *Cand2) { 10021 // Common case: One (or both) decls don't have enable_if attrs. 10022 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 10023 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 10024 if (!Cand1Attr || !Cand2Attr) { 10025 if (Cand1Attr == Cand2Attr) 10026 return Comparison::Equal; 10027 return Cand1Attr ? Comparison::Better : Comparison::Worse; 10028 } 10029 10030 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 10031 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 10032 10033 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 10034 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 10035 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 10036 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 10037 10038 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 10039 // has fewer enable_if attributes than Cand2, and vice versa. 10040 if (!Cand1A) 10041 return Comparison::Worse; 10042 if (!Cand2A) 10043 return Comparison::Better; 10044 10045 Cand1ID.clear(); 10046 Cand2ID.clear(); 10047 10048 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 10049 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 10050 if (Cand1ID != Cand2ID) 10051 return Comparison::Worse; 10052 } 10053 10054 return Comparison::Equal; 10055 } 10056 10057 static Comparison 10058 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 10059 const OverloadCandidate &Cand2) { 10060 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 10061 !Cand2.Function->isMultiVersion()) 10062 return Comparison::Equal; 10063 10064 // If both are invalid, they are equal. If one of them is invalid, the other 10065 // is better. 10066 if (Cand1.Function->isInvalidDecl()) { 10067 if (Cand2.Function->isInvalidDecl()) 10068 return Comparison::Equal; 10069 return Comparison::Worse; 10070 } 10071 if (Cand2.Function->isInvalidDecl()) 10072 return Comparison::Better; 10073 10074 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 10075 // cpu_dispatch, else arbitrarily based on the identifiers. 10076 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 10077 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 10078 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 10079 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 10080 10081 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 10082 return Comparison::Equal; 10083 10084 if (Cand1CPUDisp && !Cand2CPUDisp) 10085 return Comparison::Better; 10086 if (Cand2CPUDisp && !Cand1CPUDisp) 10087 return Comparison::Worse; 10088 10089 if (Cand1CPUSpec && Cand2CPUSpec) { 10090 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 10091 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 10092 ? Comparison::Better 10093 : Comparison::Worse; 10094 10095 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 10096 FirstDiff = std::mismatch( 10097 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 10098 Cand2CPUSpec->cpus_begin(), 10099 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 10100 return LHS->getName() == RHS->getName(); 10101 }); 10102 10103 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 10104 "Two different cpu-specific versions should not have the same " 10105 "identifier list, otherwise they'd be the same decl!"); 10106 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 10107 ? Comparison::Better 10108 : Comparison::Worse; 10109 } 10110 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 10111 } 10112 10113 /// Compute the type of the implicit object parameter for the given function, 10114 /// if any. Returns std::nullopt if there is no implicit object parameter, and a 10115 /// null QualType if there is a 'matches anything' implicit object parameter. 10116 static std::optional<QualType> 10117 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { 10118 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 10119 return std::nullopt; 10120 10121 auto *M = cast<CXXMethodDecl>(F); 10122 // Static member functions' object parameters match all types. 10123 if (M->isStatic()) 10124 return QualType(); 10125 return M->getFunctionObjectParameterReferenceType(); 10126 } 10127 10128 // As a Clang extension, allow ambiguity among F1 and F2 if they represent 10129 // represent the same entity. 10130 static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, 10131 const FunctionDecl *F2) { 10132 if (declaresSameEntity(F1, F2)) 10133 return true; 10134 auto PT1 = F1->getPrimaryTemplate(); 10135 auto PT2 = F2->getPrimaryTemplate(); 10136 if (PT1 && PT2) { 10137 if (declaresSameEntity(PT1, PT2) || 10138 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(), 10139 PT2->getInstantiatedFromMemberTemplate())) 10140 return true; 10141 } 10142 // TODO: It is not clear whether comparing parameters is necessary (i.e. 10143 // different functions with same params). Consider removing this (as no test 10144 // fail w/o it). 10145 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 10146 if (First) { 10147 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) 10148 return *T; 10149 } 10150 assert(I < F->getNumParams()); 10151 return F->getParamDecl(I++)->getType(); 10152 }; 10153 10154 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1); 10155 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2); 10156 10157 if (F1NumParams != F2NumParams) 10158 return false; 10159 10160 unsigned I1 = 0, I2 = 0; 10161 for (unsigned I = 0; I != F1NumParams; ++I) { 10162 QualType T1 = NextParam(F1, I1, I == 0); 10163 QualType T2 = NextParam(F2, I2, I == 0); 10164 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 10165 if (!Context.hasSameUnqualifiedType(T1, T2)) 10166 return false; 10167 } 10168 return true; 10169 } 10170 10171 /// We're allowed to use constraints partial ordering only if the candidates 10172 /// have the same parameter types: 10173 /// [over.match.best.general]p2.6 10174 /// F1 and F2 are non-template functions with the same 10175 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...] 10176 static bool sameFunctionParameterTypeLists(Sema &S, 10177 const OverloadCandidate &Cand1, 10178 const OverloadCandidate &Cand2) { 10179 if (!Cand1.Function || !Cand2.Function) 10180 return false; 10181 10182 FunctionDecl *Fn1 = Cand1.Function; 10183 FunctionDecl *Fn2 = Cand2.Function; 10184 10185 if (Fn1->isVariadic() != Fn1->isVariadic()) 10186 return false; 10187 10188 if (!S.FunctionNonObjectParamTypesAreEqual( 10189 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed())) 10190 return false; 10191 10192 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1); 10193 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2); 10194 if (Mem1 && Mem2) { 10195 // if they are member functions, both are direct members of the same class, 10196 // and 10197 if (Mem1->getParent() != Mem2->getParent()) 10198 return false; 10199 // if both are non-static member functions, they have the same types for 10200 // their object parameters 10201 if (Mem1->isInstance() && Mem2->isInstance() && 10202 !S.getASTContext().hasSameType( 10203 Mem1->getFunctionObjectParameterReferenceType(), 10204 Mem1->getFunctionObjectParameterReferenceType())) 10205 return false; 10206 } 10207 return true; 10208 } 10209 10210 /// isBetterOverloadCandidate - Determines whether the first overload 10211 /// candidate is a better candidate than the second (C++ 13.3.3p1). 10212 bool clang::isBetterOverloadCandidate( 10213 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 10214 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 10215 // Define viable functions to be better candidates than non-viable 10216 // functions. 10217 if (!Cand2.Viable) 10218 return Cand1.Viable; 10219 else if (!Cand1.Viable) 10220 return false; 10221 10222 // [CUDA] A function with 'never' preference is marked not viable, therefore 10223 // is never shown up here. The worst preference shown up here is 'wrong side', 10224 // e.g. an H function called by a HD function in device compilation. This is 10225 // valid AST as long as the HD function is not emitted, e.g. it is an inline 10226 // function which is called only by an H function. A deferred diagnostic will 10227 // be triggered if it is emitted. However a wrong-sided function is still 10228 // a viable candidate here. 10229 // 10230 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 10231 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 10232 // can be emitted, Cand1 is not better than Cand2. This rule should have 10233 // precedence over other rules. 10234 // 10235 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 10236 // other rules should be used to determine which is better. This is because 10237 // host/device based overloading resolution is mostly for determining 10238 // viability of a function. If two functions are both viable, other factors 10239 // should take precedence in preference, e.g. the standard-defined preferences 10240 // like argument conversion ranks or enable_if partial-ordering. The 10241 // preference for pass-object-size parameters is probably most similar to a 10242 // type-based-overloading decision and so should take priority. 10243 // 10244 // If other rules cannot determine which is better, CUDA preference will be 10245 // used again to determine which is better. 10246 // 10247 // TODO: Currently IdentifyCUDAPreference does not return correct values 10248 // for functions called in global variable initializers due to missing 10249 // correct context about device/host. Therefore we can only enforce this 10250 // rule when there is a caller. We should enforce this rule for functions 10251 // in global variable initializers once proper context is added. 10252 // 10253 // TODO: We can only enable the hostness based overloading resolution when 10254 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 10255 // overloading resolution diagnostics. 10256 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 10257 S.getLangOpts().GPUExcludeWrongSideOverloads) { 10258 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { 10259 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 10260 bool IsCand1ImplicitHD = 10261 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 10262 bool IsCand2ImplicitHD = 10263 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 10264 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 10265 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 10266 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 10267 // The implicit HD function may be a function in a system header which 10268 // is forced by pragma. In device compilation, if we prefer HD candidates 10269 // over wrong-sided candidates, overloading resolution may change, which 10270 // may result in non-deferrable diagnostics. As a workaround, we let 10271 // implicit HD candidates take equal preference as wrong-sided candidates. 10272 // This will preserve the overloading resolution. 10273 // TODO: We still need special handling of implicit HD functions since 10274 // they may incur other diagnostics to be deferred. We should make all 10275 // host/device related diagnostics deferrable and remove special handling 10276 // of implicit HD functions. 10277 auto EmitThreshold = 10278 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 10279 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 10280 ? Sema::CFP_Never 10281 : Sema::CFP_WrongSide; 10282 auto Cand1Emittable = P1 > EmitThreshold; 10283 auto Cand2Emittable = P2 > EmitThreshold; 10284 if (Cand1Emittable && !Cand2Emittable) 10285 return true; 10286 if (!Cand1Emittable && Cand2Emittable) 10287 return false; 10288 } 10289 } 10290 10291 // C++ [over.match.best]p1: (Changed in C++23) 10292 // 10293 // -- if F is a static member function, ICS1(F) is defined such 10294 // that ICS1(F) is neither better nor worse than ICS1(G) for 10295 // any function G, and, symmetrically, ICS1(G) is neither 10296 // better nor worse than ICS1(F). 10297 unsigned StartArg = 0; 10298 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 10299 StartArg = 1; 10300 10301 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 10302 // We don't allow incompatible pointer conversions in C++. 10303 if (!S.getLangOpts().CPlusPlus) 10304 return ICS.isStandard() && 10305 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 10306 10307 // The only ill-formed conversion we allow in C++ is the string literal to 10308 // char* conversion, which is only considered ill-formed after C++11. 10309 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 10310 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 10311 }; 10312 10313 // Define functions that don't require ill-formed conversions for a given 10314 // argument to be better candidates than functions that do. 10315 unsigned NumArgs = Cand1.Conversions.size(); 10316 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 10317 bool HasBetterConversion = false; 10318 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 10319 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 10320 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 10321 if (Cand1Bad != Cand2Bad) { 10322 if (Cand1Bad) 10323 return false; 10324 HasBetterConversion = true; 10325 } 10326 } 10327 10328 if (HasBetterConversion) 10329 return true; 10330 10331 // C++ [over.match.best]p1: 10332 // A viable function F1 is defined to be a better function than another 10333 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 10334 // conversion sequence than ICSi(F2), and then... 10335 bool HasWorseConversion = false; 10336 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 10337 switch (CompareImplicitConversionSequences(S, Loc, 10338 Cand1.Conversions[ArgIdx], 10339 Cand2.Conversions[ArgIdx])) { 10340 case ImplicitConversionSequence::Better: 10341 // Cand1 has a better conversion sequence. 10342 HasBetterConversion = true; 10343 break; 10344 10345 case ImplicitConversionSequence::Worse: 10346 if (Cand1.Function && Cand2.Function && 10347 Cand1.isReversed() != Cand2.isReversed() && 10348 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) { 10349 // Work around large-scale breakage caused by considering reversed 10350 // forms of operator== in C++20: 10351 // 10352 // When comparing a function against a reversed function, if we have a 10353 // better conversion for one argument and a worse conversion for the 10354 // other, the implicit conversion sequences are treated as being equally 10355 // good. 10356 // 10357 // This prevents a comparison function from being considered ambiguous 10358 // with a reversed form that is written in the same way. 10359 // 10360 // We diagnose this as an extension from CreateOverloadedBinOp. 10361 HasWorseConversion = true; 10362 break; 10363 } 10364 10365 // Cand1 can't be better than Cand2. 10366 return false; 10367 10368 case ImplicitConversionSequence::Indistinguishable: 10369 // Do nothing. 10370 break; 10371 } 10372 } 10373 10374 // -- for some argument j, ICSj(F1) is a better conversion sequence than 10375 // ICSj(F2), or, if not that, 10376 if (HasBetterConversion && !HasWorseConversion) 10377 return true; 10378 10379 // -- the context is an initialization by user-defined conversion 10380 // (see 8.5, 13.3.1.5) and the standard conversion sequence 10381 // from the return type of F1 to the destination type (i.e., 10382 // the type of the entity being initialized) is a better 10383 // conversion sequence than the standard conversion sequence 10384 // from the return type of F2 to the destination type. 10385 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 10386 Cand1.Function && Cand2.Function && 10387 isa<CXXConversionDecl>(Cand1.Function) && 10388 isa<CXXConversionDecl>(Cand2.Function)) { 10389 // First check whether we prefer one of the conversion functions over the 10390 // other. This only distinguishes the results in non-standard, extension 10391 // cases such as the conversion from a lambda closure type to a function 10392 // pointer or block. 10393 ImplicitConversionSequence::CompareKind Result = 10394 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 10395 if (Result == ImplicitConversionSequence::Indistinguishable) 10396 Result = CompareStandardConversionSequences(S, Loc, 10397 Cand1.FinalConversion, 10398 Cand2.FinalConversion); 10399 10400 if (Result != ImplicitConversionSequence::Indistinguishable) 10401 return Result == ImplicitConversionSequence::Better; 10402 10403 // FIXME: Compare kind of reference binding if conversion functions 10404 // convert to a reference type used in direct reference binding, per 10405 // C++14 [over.match.best]p1 section 2 bullet 3. 10406 } 10407 10408 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 10409 // as combined with the resolution to CWG issue 243. 10410 // 10411 // When the context is initialization by constructor ([over.match.ctor] or 10412 // either phase of [over.match.list]), a constructor is preferred over 10413 // a conversion function. 10414 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 10415 Cand1.Function && Cand2.Function && 10416 isa<CXXConstructorDecl>(Cand1.Function) != 10417 isa<CXXConstructorDecl>(Cand2.Function)) 10418 return isa<CXXConstructorDecl>(Cand1.Function); 10419 10420 // -- F1 is a non-template function and F2 is a function template 10421 // specialization, or, if not that, 10422 bool Cand1IsSpecialization = Cand1.Function && 10423 Cand1.Function->getPrimaryTemplate(); 10424 bool Cand2IsSpecialization = Cand2.Function && 10425 Cand2.Function->getPrimaryTemplate(); 10426 if (Cand1IsSpecialization != Cand2IsSpecialization) 10427 return Cand2IsSpecialization; 10428 10429 // -- F1 and F2 are function template specializations, and the function 10430 // template for F1 is more specialized than the template for F2 10431 // according to the partial ordering rules described in 14.5.5.2, or, 10432 // if not that, 10433 if (Cand1IsSpecialization && Cand2IsSpecialization) { 10434 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 10435 Cand1.Function->getPrimaryTemplate(), 10436 Cand2.Function->getPrimaryTemplate(), Loc, 10437 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 10438 : TPOC_Call, 10439 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 10440 Cand1.isReversed() ^ Cand2.isReversed())) 10441 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 10442 } 10443 10444 // -— F1 and F2 are non-template functions with the same 10445 // parameter-type-lists, and F1 is more constrained than F2 [...], 10446 if (!Cand1IsSpecialization && !Cand2IsSpecialization && 10447 sameFunctionParameterTypeLists(S, Cand1, Cand2)) { 10448 FunctionDecl *Function1 = Cand1.Function; 10449 FunctionDecl *Function2 = Cand2.Function; 10450 if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction()) 10451 Function1 = MF; 10452 if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction()) 10453 Function2 = MF; 10454 10455 const Expr *RC1 = Function1->getTrailingRequiresClause(); 10456 const Expr *RC2 = Function2->getTrailingRequiresClause(); 10457 if (RC1 && RC2) { 10458 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 10459 if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2, 10460 AtLeastAsConstrained1) || 10461 S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1, 10462 AtLeastAsConstrained2)) 10463 return false; 10464 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 10465 return AtLeastAsConstrained1; 10466 } else if (RC1 || RC2) { 10467 return RC1 != nullptr; 10468 } 10469 } 10470 10471 // -- F1 is a constructor for a class D, F2 is a constructor for a base 10472 // class B of D, and for all arguments the corresponding parameters of 10473 // F1 and F2 have the same type. 10474 // FIXME: Implement the "all parameters have the same type" check. 10475 bool Cand1IsInherited = 10476 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 10477 bool Cand2IsInherited = 10478 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 10479 if (Cand1IsInherited != Cand2IsInherited) 10480 return Cand2IsInherited; 10481 else if (Cand1IsInherited) { 10482 assert(Cand2IsInherited); 10483 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 10484 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 10485 if (Cand1Class->isDerivedFrom(Cand2Class)) 10486 return true; 10487 if (Cand2Class->isDerivedFrom(Cand1Class)) 10488 return false; 10489 // Inherited from sibling base classes: still ambiguous. 10490 } 10491 10492 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 10493 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 10494 // with reversed order of parameters and F1 is not 10495 // 10496 // We rank reversed + different operator as worse than just reversed, but 10497 // that comparison can never happen, because we only consider reversing for 10498 // the maximally-rewritten operator (== or <=>). 10499 if (Cand1.RewriteKind != Cand2.RewriteKind) 10500 return Cand1.RewriteKind < Cand2.RewriteKind; 10501 10502 // Check C++17 tie-breakers for deduction guides. 10503 { 10504 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 10505 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 10506 if (Guide1 && Guide2) { 10507 // -- F1 is generated from a deduction-guide and F2 is not 10508 if (Guide1->isImplicit() != Guide2->isImplicit()) 10509 return Guide2->isImplicit(); 10510 10511 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 10512 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy) 10513 return true; 10514 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy) 10515 return false; 10516 10517 // --F1 is generated from a non-template constructor and F2 is generated 10518 // from a constructor template 10519 const auto *Constructor1 = Guide1->getCorrespondingConstructor(); 10520 const auto *Constructor2 = Guide2->getCorrespondingConstructor(); 10521 if (Constructor1 && Constructor2) { 10522 bool isC1Templated = Constructor1->getTemplatedKind() != 10523 FunctionDecl::TemplatedKind::TK_NonTemplate; 10524 bool isC2Templated = Constructor2->getTemplatedKind() != 10525 FunctionDecl::TemplatedKind::TK_NonTemplate; 10526 if (isC1Templated != isC2Templated) 10527 return isC2Templated; 10528 } 10529 } 10530 } 10531 10532 // Check for enable_if value-based overload resolution. 10533 if (Cand1.Function && Cand2.Function) { 10534 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 10535 if (Cmp != Comparison::Equal) 10536 return Cmp == Comparison::Better; 10537 } 10538 10539 bool HasPS1 = Cand1.Function != nullptr && 10540 functionHasPassObjectSizeParams(Cand1.Function); 10541 bool HasPS2 = Cand2.Function != nullptr && 10542 functionHasPassObjectSizeParams(Cand2.Function); 10543 if (HasPS1 != HasPS2 && HasPS1) 10544 return true; 10545 10546 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 10547 if (MV == Comparison::Better) 10548 return true; 10549 if (MV == Comparison::Worse) 10550 return false; 10551 10552 // If other rules cannot determine which is better, CUDA preference is used 10553 // to determine which is better. 10554 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 10555 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10556 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 10557 S.IdentifyCUDAPreference(Caller, Cand2.Function); 10558 } 10559 10560 // General member function overloading is handled above, so this only handles 10561 // constructors with address spaces. 10562 // This only handles address spaces since C++ has no other 10563 // qualifier that can be used with constructors. 10564 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 10565 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 10566 if (CD1 && CD2) { 10567 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 10568 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 10569 if (AS1 != AS2) { 10570 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10571 return true; 10572 if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2)) 10573 return false; 10574 } 10575 } 10576 10577 return false; 10578 } 10579 10580 /// Determine whether two declarations are "equivalent" for the purposes of 10581 /// name lookup and overload resolution. This applies when the same internal/no 10582 /// linkage entity is defined by two modules (probably by textually including 10583 /// the same header). In such a case, we don't consider the declarations to 10584 /// declare the same entity, but we also don't want lookups with both 10585 /// declarations visible to be ambiguous in some cases (this happens when using 10586 /// a modularized libstdc++). 10587 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10588 const NamedDecl *B) { 10589 auto *VA = dyn_cast_or_null<ValueDecl>(A); 10590 auto *VB = dyn_cast_or_null<ValueDecl>(B); 10591 if (!VA || !VB) 10592 return false; 10593 10594 // The declarations must be declaring the same name as an internal linkage 10595 // entity in different modules. 10596 if (!VA->getDeclContext()->getRedeclContext()->Equals( 10597 VB->getDeclContext()->getRedeclContext()) || 10598 getOwningModule(VA) == getOwningModule(VB) || 10599 VA->isExternallyVisible() || VB->isExternallyVisible()) 10600 return false; 10601 10602 // Check that the declarations appear to be equivalent. 10603 // 10604 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 10605 // For constants and functions, we should check the initializer or body is 10606 // the same. For non-constant variables, we shouldn't allow it at all. 10607 if (Context.hasSameType(VA->getType(), VB->getType())) 10608 return true; 10609 10610 // Enum constants within unnamed enumerations will have different types, but 10611 // may still be similar enough to be interchangeable for our purposes. 10612 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 10613 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 10614 // Only handle anonymous enums. If the enumerations were named and 10615 // equivalent, they would have been merged to the same type. 10616 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 10617 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 10618 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 10619 !Context.hasSameType(EnumA->getIntegerType(), 10620 EnumB->getIntegerType())) 10621 return false; 10622 // Allow this only if the value is the same for both enumerators. 10623 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 10624 } 10625 } 10626 10627 // Nothing else is sufficiently similar. 10628 return false; 10629 } 10630 10631 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10632 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10633 assert(D && "Unknown declaration"); 10634 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10635 10636 Module *M = getOwningModule(D); 10637 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10638 << !M << (M ? M->getFullModuleName() : ""); 10639 10640 for (auto *E : Equiv) { 10641 Module *M = getOwningModule(E); 10642 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10643 << !M << (M ? M->getFullModuleName() : ""); 10644 } 10645 } 10646 10647 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { 10648 return FailureKind == ovl_fail_bad_deduction && 10649 DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied && 10650 static_cast<CNSInfo *>(DeductionFailure.Data) 10651 ->Satisfaction.ContainsErrors; 10652 } 10653 10654 /// Computes the best viable function (C++ 13.3.3) 10655 /// within an overload candidate set. 10656 /// 10657 /// \param Loc The location of the function name (or operator symbol) for 10658 /// which overload resolution occurs. 10659 /// 10660 /// \param Best If overload resolution was successful or found a deleted 10661 /// function, \p Best points to the candidate function found. 10662 /// 10663 /// \returns The result of overload resolution. 10664 OverloadingResult 10665 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10666 iterator &Best) { 10667 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10668 std::transform(begin(), end(), std::back_inserter(Candidates), 10669 [](OverloadCandidate &Cand) { return &Cand; }); 10670 10671 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10672 // are accepted by both clang and NVCC. However, during a particular 10673 // compilation mode only one call variant is viable. We need to 10674 // exclude non-viable overload candidates from consideration based 10675 // only on their host/device attributes. Specifically, if one 10676 // candidate call is WrongSide and the other is SameSide, we ignore 10677 // the WrongSide candidate. 10678 // We only need to remove wrong-sided candidates here if 10679 // -fgpu-exclude-wrong-side-overloads is off. When 10680 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10681 // uniformly in isBetterOverloadCandidate. 10682 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10683 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10684 bool ContainsSameSideCandidate = 10685 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10686 // Check viable function only. 10687 return Cand->Viable && Cand->Function && 10688 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10689 Sema::CFP_SameSide; 10690 }); 10691 if (ContainsSameSideCandidate) { 10692 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10693 // Check viable function only to avoid unnecessary data copying/moving. 10694 return Cand->Viable && Cand->Function && 10695 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10696 Sema::CFP_WrongSide; 10697 }; 10698 llvm::erase_if(Candidates, IsWrongSideCandidate); 10699 } 10700 } 10701 10702 // Find the best viable function. 10703 Best = end(); 10704 for (auto *Cand : Candidates) { 10705 Cand->Best = false; 10706 if (Cand->Viable) { 10707 if (Best == end() || 10708 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10709 Best = Cand; 10710 } else if (Cand->NotValidBecauseConstraintExprHasError()) { 10711 // This candidate has constraint that we were unable to evaluate because 10712 // it referenced an expression that contained an error. Rather than fall 10713 // back onto a potentially unintended candidate (made worse by 10714 // subsuming constraints), treat this as 'no viable candidate'. 10715 Best = end(); 10716 return OR_No_Viable_Function; 10717 } 10718 } 10719 10720 // If we didn't find any viable functions, abort. 10721 if (Best == end()) 10722 return OR_No_Viable_Function; 10723 10724 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10725 10726 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10727 PendingBest.push_back(&*Best); 10728 Best->Best = true; 10729 10730 // Make sure that this function is better than every other viable 10731 // function. If not, we have an ambiguity. 10732 while (!PendingBest.empty()) { 10733 auto *Curr = PendingBest.pop_back_val(); 10734 for (auto *Cand : Candidates) { 10735 if (Cand->Viable && !Cand->Best && 10736 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10737 PendingBest.push_back(Cand); 10738 Cand->Best = true; 10739 10740 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10741 Curr->Function)) 10742 EquivalentCands.push_back(Cand->Function); 10743 else 10744 Best = end(); 10745 } 10746 } 10747 } 10748 10749 // If we found more than one best candidate, this is ambiguous. 10750 if (Best == end()) 10751 return OR_Ambiguous; 10752 10753 // Best is the best viable function. 10754 if (Best->Function && Best->Function->isDeleted()) 10755 return OR_Deleted; 10756 10757 if (!EquivalentCands.empty()) 10758 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10759 EquivalentCands); 10760 10761 return OR_Success; 10762 } 10763 10764 namespace { 10765 10766 enum OverloadCandidateKind { 10767 oc_function, 10768 oc_method, 10769 oc_reversed_binary_operator, 10770 oc_constructor, 10771 oc_implicit_default_constructor, 10772 oc_implicit_copy_constructor, 10773 oc_implicit_move_constructor, 10774 oc_implicit_copy_assignment, 10775 oc_implicit_move_assignment, 10776 oc_implicit_equality_comparison, 10777 oc_inherited_constructor 10778 }; 10779 10780 enum OverloadCandidateSelect { 10781 ocs_non_template, 10782 ocs_template, 10783 ocs_described_template, 10784 }; 10785 10786 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10787 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found, 10788 const FunctionDecl *Fn, 10789 OverloadCandidateRewriteKind CRK, 10790 std::string &Description) { 10791 10792 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10793 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10794 isTemplate = true; 10795 Description = S.getTemplateArgumentBindingsText( 10796 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10797 } 10798 10799 OverloadCandidateSelect Select = [&]() { 10800 if (!Description.empty()) 10801 return ocs_described_template; 10802 return isTemplate ? ocs_template : ocs_non_template; 10803 }(); 10804 10805 OverloadCandidateKind Kind = [&]() { 10806 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10807 return oc_implicit_equality_comparison; 10808 10809 if (CRK & CRK_Reversed) 10810 return oc_reversed_binary_operator; 10811 10812 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10813 if (!Ctor->isImplicit()) { 10814 if (isa<ConstructorUsingShadowDecl>(Found)) 10815 return oc_inherited_constructor; 10816 else 10817 return oc_constructor; 10818 } 10819 10820 if (Ctor->isDefaultConstructor()) 10821 return oc_implicit_default_constructor; 10822 10823 if (Ctor->isMoveConstructor()) 10824 return oc_implicit_move_constructor; 10825 10826 assert(Ctor->isCopyConstructor() && 10827 "unexpected sort of implicit constructor"); 10828 return oc_implicit_copy_constructor; 10829 } 10830 10831 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10832 // This actually gets spelled 'candidate function' for now, but 10833 // it doesn't hurt to split it out. 10834 if (!Meth->isImplicit()) 10835 return oc_method; 10836 10837 if (Meth->isMoveAssignmentOperator()) 10838 return oc_implicit_move_assignment; 10839 10840 if (Meth->isCopyAssignmentOperator()) 10841 return oc_implicit_copy_assignment; 10842 10843 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10844 return oc_method; 10845 } 10846 10847 return oc_function; 10848 }(); 10849 10850 return std::make_pair(Kind, Select); 10851 } 10852 10853 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) { 10854 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10855 // set. 10856 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10857 S.Diag(FoundDecl->getLocation(), 10858 diag::note_ovl_candidate_inherited_constructor) 10859 << Shadow->getNominatedBaseClass(); 10860 } 10861 10862 } // end anonymous namespace 10863 10864 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10865 const FunctionDecl *FD) { 10866 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10867 bool AlwaysTrue; 10868 if (EnableIf->getCond()->isValueDependent() || 10869 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10870 return false; 10871 if (!AlwaysTrue) 10872 return false; 10873 } 10874 return true; 10875 } 10876 10877 /// Returns true if we can take the address of the function. 10878 /// 10879 /// \param Complain - If true, we'll emit a diagnostic 10880 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10881 /// we in overload resolution? 10882 /// \param Loc - The location of the statement we're complaining about. Ignored 10883 /// if we're not complaining, or if we're in overload resolution. 10884 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10885 bool Complain, 10886 bool InOverloadResolution, 10887 SourceLocation Loc) { 10888 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10889 if (Complain) { 10890 if (InOverloadResolution) 10891 S.Diag(FD->getBeginLoc(), 10892 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10893 else 10894 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10895 } 10896 return false; 10897 } 10898 10899 if (FD->getTrailingRequiresClause()) { 10900 ConstraintSatisfaction Satisfaction; 10901 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10902 return false; 10903 if (!Satisfaction.IsSatisfied) { 10904 if (Complain) { 10905 if (InOverloadResolution) { 10906 SmallString<128> TemplateArgString; 10907 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 10908 TemplateArgString += " "; 10909 TemplateArgString += S.getTemplateArgumentBindingsText( 10910 FunTmpl->getTemplateParameters(), 10911 *FD->getTemplateSpecializationArgs()); 10912 } 10913 10914 S.Diag(FD->getBeginLoc(), 10915 diag::note_ovl_candidate_unsatisfied_constraints) 10916 << TemplateArgString; 10917 } else 10918 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10919 << FD; 10920 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10921 } 10922 return false; 10923 } 10924 } 10925 10926 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10927 return P->hasAttr<PassObjectSizeAttr>(); 10928 }); 10929 if (I == FD->param_end()) 10930 return true; 10931 10932 if (Complain) { 10933 // Add one to ParamNo because it's user-facing 10934 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10935 if (InOverloadResolution) 10936 S.Diag(FD->getLocation(), 10937 diag::note_ovl_candidate_has_pass_object_size_params) 10938 << ParamNo; 10939 else 10940 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10941 << FD << ParamNo; 10942 } 10943 return false; 10944 } 10945 10946 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10947 const FunctionDecl *FD) { 10948 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10949 /*InOverloadResolution=*/true, 10950 /*Loc=*/SourceLocation()); 10951 } 10952 10953 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10954 bool Complain, 10955 SourceLocation Loc) { 10956 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10957 /*InOverloadResolution=*/false, 10958 Loc); 10959 } 10960 10961 // Don't print candidates other than the one that matches the calling 10962 // convention of the call operator, since that is guaranteed to exist. 10963 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) { 10964 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10965 10966 if (!ConvD) 10967 return false; 10968 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10969 if (!RD->isLambda()) 10970 return false; 10971 10972 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10973 CallingConv CallOpCC = 10974 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10975 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10976 CallingConv ConvToCC = 10977 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10978 10979 return ConvToCC != CallOpCC; 10980 } 10981 10982 // Notes the location of an overload candidate. 10983 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, 10984 OverloadCandidateRewriteKind RewriteKind, 10985 QualType DestType, bool TakingAddress) { 10986 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10987 return; 10988 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10989 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10990 return; 10991 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() && 10992 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion()) 10993 return; 10994 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10995 return; 10996 10997 std::string FnDesc; 10998 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10999 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 11000 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 11001 << (unsigned)KSPair.first << (unsigned)KSPair.second 11002 << Fn << FnDesc; 11003 11004 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 11005 Diag(Fn->getLocation(), PD); 11006 MaybeEmitInheritedConstructorNote(*this, Found); 11007 } 11008 11009 static void 11010 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 11011 // Perhaps the ambiguity was caused by two atomic constraints that are 11012 // 'identical' but not equivalent: 11013 // 11014 // void foo() requires (sizeof(T) > 4) { } // #1 11015 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 11016 // 11017 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 11018 // #2 to subsume #1, but these constraint are not considered equivalent 11019 // according to the subsumption rules because they are not the same 11020 // source-level construct. This behavior is quite confusing and we should try 11021 // to help the user figure out what happened. 11022 11023 SmallVector<const Expr *, 3> FirstAC, SecondAC; 11024 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 11025 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11026 if (!I->Function) 11027 continue; 11028 SmallVector<const Expr *, 3> AC; 11029 if (auto *Template = I->Function->getPrimaryTemplate()) 11030 Template->getAssociatedConstraints(AC); 11031 else 11032 I->Function->getAssociatedConstraints(AC); 11033 if (AC.empty()) 11034 continue; 11035 if (FirstCand == nullptr) { 11036 FirstCand = I->Function; 11037 FirstAC = AC; 11038 } else if (SecondCand == nullptr) { 11039 SecondCand = I->Function; 11040 SecondAC = AC; 11041 } else { 11042 // We have more than one pair of constrained functions - this check is 11043 // expensive and we'd rather not try to diagnose it. 11044 return; 11045 } 11046 } 11047 if (!SecondCand) 11048 return; 11049 // The diagnostic can only happen if there are associated constraints on 11050 // both sides (there needs to be some identical atomic constraint). 11051 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 11052 SecondCand, SecondAC)) 11053 // Just show the user one diagnostic, they'll probably figure it out 11054 // from here. 11055 return; 11056 } 11057 11058 // Notes the location of all overload candidates designated through 11059 // OverloadedExpr 11060 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 11061 bool TakingAddress) { 11062 assert(OverloadedExpr->getType() == Context.OverloadTy); 11063 11064 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 11065 OverloadExpr *OvlExpr = Ovl.Expression; 11066 11067 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11068 IEnd = OvlExpr->decls_end(); 11069 I != IEnd; ++I) { 11070 if (FunctionTemplateDecl *FunTmpl = 11071 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 11072 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 11073 TakingAddress); 11074 } else if (FunctionDecl *Fun 11075 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 11076 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 11077 } 11078 } 11079 } 11080 11081 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 11082 /// "lead" diagnostic; it will be given two arguments, the source and 11083 /// target types of the conversion. 11084 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 11085 Sema &S, 11086 SourceLocation CaretLoc, 11087 const PartialDiagnostic &PDiag) const { 11088 S.Diag(CaretLoc, PDiag) 11089 << Ambiguous.getFromType() << Ambiguous.getToType(); 11090 unsigned CandsShown = 0; 11091 AmbiguousConversionSequence::const_iterator I, E; 11092 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 11093 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 11094 break; 11095 ++CandsShown; 11096 S.NoteOverloadCandidate(I->first, I->second); 11097 } 11098 S.Diags.overloadCandidatesShown(CandsShown); 11099 if (I != E) 11100 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 11101 } 11102 11103 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 11104 unsigned I, bool TakingCandidateAddress) { 11105 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 11106 assert(Conv.isBad()); 11107 assert(Cand->Function && "for now, candidate must be a function"); 11108 FunctionDecl *Fn = Cand->Function; 11109 11110 // There's a conversion slot for the object argument if this is a 11111 // non-constructor method. Note that 'I' corresponds the 11112 // conversion-slot index. 11113 bool isObjectArgument = false; 11114 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 11115 if (I == 0) 11116 isObjectArgument = true; 11117 else 11118 I--; 11119 } 11120 11121 std::string FnDesc; 11122 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11123 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 11124 FnDesc); 11125 11126 Expr *FromExpr = Conv.Bad.FromExpr; 11127 QualType FromTy = Conv.Bad.getFromType(); 11128 QualType ToTy = Conv.Bad.getToType(); 11129 SourceRange ToParamRange = 11130 !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange(); 11131 11132 if (FromTy == S.Context.OverloadTy) { 11133 assert(FromExpr && "overload set argument came from implicit argument?"); 11134 Expr *E = FromExpr->IgnoreParens(); 11135 if (isa<UnaryOperator>(E)) 11136 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11137 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 11138 11139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 11140 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11141 << ToParamRange << ToTy << Name << I + 1; 11142 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11143 return; 11144 } 11145 11146 // Do some hand-waving analysis to see if the non-viability is due 11147 // to a qualifier mismatch. 11148 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 11149 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 11150 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 11151 CToTy = RT->getPointeeType(); 11152 else { 11153 // TODO: detect and diagnose the full richness of const mismatches. 11154 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 11155 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 11156 CFromTy = FromPT->getPointeeType(); 11157 CToTy = ToPT->getPointeeType(); 11158 } 11159 } 11160 11161 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 11162 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 11163 Qualifiers FromQs = CFromTy.getQualifiers(); 11164 Qualifiers ToQs = CToTy.getQualifiers(); 11165 11166 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 11167 if (isObjectArgument) 11168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 11169 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11170 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 11171 else 11172 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 11173 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11174 << FnDesc << ToParamRange << FromQs.getAddressSpace() 11175 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1; 11176 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11177 return; 11178 } 11179 11180 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 11181 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 11182 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11183 << ToParamRange << FromTy << FromQs.getObjCLifetime() 11184 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1; 11185 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11186 return; 11187 } 11188 11189 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 11190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 11191 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11192 << ToParamRange << FromTy << FromQs.getObjCGCAttr() 11193 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1; 11194 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11195 return; 11196 } 11197 11198 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 11199 assert(CVR && "expected qualifiers mismatch"); 11200 11201 if (isObjectArgument) { 11202 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 11203 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11204 << FromTy << (CVR - 1); 11205 } else { 11206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 11207 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11208 << ToParamRange << FromTy << (CVR - 1) << I + 1; 11209 } 11210 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11211 return; 11212 } 11213 11214 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 11215 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 11216 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 11217 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11218 << (unsigned)isObjectArgument << I + 1 11219 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 11220 << ToParamRange; 11221 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11222 return; 11223 } 11224 11225 // Special diagnostic for failure to convert an initializer list, since 11226 // telling the user that it has type void is not useful. 11227 if (FromExpr && isa<InitListExpr>(FromExpr)) { 11228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 11229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11230 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11231 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 11232 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 11233 ? 2 11234 : 0); 11235 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11236 return; 11237 } 11238 11239 // Diagnose references or pointers to incomplete types differently, 11240 // since it's far from impossible that the incompleteness triggered 11241 // the failure. 11242 QualType TempFromTy = FromTy.getNonReferenceType(); 11243 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 11244 TempFromTy = PTy->getPointeeType(); 11245 if (TempFromTy->isIncompleteType()) { 11246 // Emit the generic diagnostic and, optionally, add the hints to it. 11247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 11248 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11249 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11250 << (unsigned)(Cand->Fix.Kind); 11251 11252 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11253 return; 11254 } 11255 11256 // Diagnose base -> derived pointer conversions. 11257 unsigned BaseToDerivedConversion = 0; 11258 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 11259 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 11260 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 11261 FromPtrTy->getPointeeType()) && 11262 !FromPtrTy->getPointeeType()->isIncompleteType() && 11263 !ToPtrTy->getPointeeType()->isIncompleteType() && 11264 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 11265 FromPtrTy->getPointeeType())) 11266 BaseToDerivedConversion = 1; 11267 } 11268 } else if (const ObjCObjectPointerType *FromPtrTy 11269 = FromTy->getAs<ObjCObjectPointerType>()) { 11270 if (const ObjCObjectPointerType *ToPtrTy 11271 = ToTy->getAs<ObjCObjectPointerType>()) 11272 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 11273 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 11274 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 11275 FromPtrTy->getPointeeType()) && 11276 FromIface->isSuperClassOf(ToIface)) 11277 BaseToDerivedConversion = 2; 11278 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 11279 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 11280 !FromTy->isIncompleteType() && 11281 !ToRefTy->getPointeeType()->isIncompleteType() && 11282 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 11283 BaseToDerivedConversion = 3; 11284 } 11285 } 11286 11287 if (BaseToDerivedConversion) { 11288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 11289 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11290 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy 11291 << I + 1; 11292 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11293 return; 11294 } 11295 11296 if (isa<ObjCObjectPointerType>(CFromTy) && 11297 isa<PointerType>(CToTy)) { 11298 Qualifiers FromQs = CFromTy.getQualifiers(); 11299 Qualifiers ToQs = CToTy.getQualifiers(); 11300 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 11301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 11302 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11303 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument 11304 << I + 1; 11305 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11306 return; 11307 } 11308 } 11309 11310 if (TakingCandidateAddress && 11311 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 11312 return; 11313 11314 // Emit the generic diagnostic and, optionally, add the hints to it. 11315 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 11316 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11317 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11318 << (unsigned)(Cand->Fix.Kind); 11319 11320 // Check that location of Fn is not in system header. 11321 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) { 11322 // If we can fix the conversion, suggest the FixIts. 11323 for (const FixItHint &HI : Cand->Fix.Hints) 11324 FDiag << HI; 11325 } 11326 11327 S.Diag(Fn->getLocation(), FDiag); 11328 11329 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11330 } 11331 11332 /// Additional arity mismatch diagnosis specific to a function overload 11333 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 11334 /// over a candidate in any candidate set. 11335 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 11336 unsigned NumArgs) { 11337 FunctionDecl *Fn = Cand->Function; 11338 unsigned MinParams = Fn->getMinRequiredArguments(); 11339 11340 // With invalid overloaded operators, it's possible that we think we 11341 // have an arity mismatch when in fact it looks like we have the 11342 // right number of arguments, because only overloaded operators have 11343 // the weird behavior of overloading member and non-member functions. 11344 // Just don't report anything. 11345 if (Fn->isInvalidDecl() && 11346 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 11347 return true; 11348 11349 if (NumArgs < MinParams) { 11350 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 11351 (Cand->FailureKind == ovl_fail_bad_deduction && 11352 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 11353 } else { 11354 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 11355 (Cand->FailureKind == ovl_fail_bad_deduction && 11356 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 11357 } 11358 11359 return false; 11360 } 11361 11362 /// General arity mismatch diagnosis over a candidate in a candidate set. 11363 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 11364 unsigned NumFormalArgs) { 11365 assert(isa<FunctionDecl>(D) && 11366 "The templated declaration should at least be a function" 11367 " when diagnosing bad template argument deduction due to too many" 11368 " or too few arguments"); 11369 11370 FunctionDecl *Fn = cast<FunctionDecl>(D); 11371 11372 // TODO: treat calls to a missing default constructor as a special case 11373 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 11374 unsigned MinParams = Fn->getMinRequiredExplicitArguments(); 11375 11376 // at least / at most / exactly 11377 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter(); 11378 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0); 11379 unsigned mode, modeCount; 11380 if (NumFormalArgs < MinParams) { 11381 if (MinParams != ParamCount || FnTy->isVariadic() || 11382 FnTy->isTemplateVariadic()) 11383 mode = 0; // "at least" 11384 else 11385 mode = 2; // "exactly" 11386 modeCount = MinParams; 11387 } else { 11388 if (MinParams != ParamCount) 11389 mode = 1; // "at most" 11390 else 11391 mode = 2; // "exactly" 11392 modeCount = ParamCount; 11393 } 11394 11395 std::string Description; 11396 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11397 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 11398 11399 if (modeCount == 1 && 11400 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName()) 11401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 11402 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11403 << Description << mode 11404 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs 11405 << HasExplicitObjectParam << Fn->getParametersSourceRange(); 11406 else 11407 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 11408 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11409 << Description << mode << modeCount << NumFormalArgs 11410 << HasExplicitObjectParam << Fn->getParametersSourceRange(); 11411 11412 MaybeEmitInheritedConstructorNote(S, Found); 11413 } 11414 11415 /// Arity mismatch diagnosis specific to a function overload candidate. 11416 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 11417 unsigned NumFormalArgs) { 11418 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 11419 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 11420 } 11421 11422 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 11423 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 11424 return TD; 11425 llvm_unreachable("Unsupported: Getting the described template declaration" 11426 " for bad deduction diagnosis"); 11427 } 11428 11429 /// Diagnose a failed template-argument deduction. 11430 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 11431 DeductionFailureInfo &DeductionFailure, 11432 unsigned NumArgs, 11433 bool TakingCandidateAddress) { 11434 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 11435 NamedDecl *ParamD; 11436 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 11437 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 11438 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 11439 switch (DeductionFailure.Result) { 11440 case Sema::TDK_Success: 11441 llvm_unreachable("TDK_success while diagnosing bad deduction"); 11442 11443 case Sema::TDK_Incomplete: { 11444 assert(ParamD && "no parameter found for incomplete deduction result"); 11445 S.Diag(Templated->getLocation(), 11446 diag::note_ovl_candidate_incomplete_deduction) 11447 << ParamD->getDeclName(); 11448 MaybeEmitInheritedConstructorNote(S, Found); 11449 return; 11450 } 11451 11452 case Sema::TDK_IncompletePack: { 11453 assert(ParamD && "no parameter found for incomplete deduction result"); 11454 S.Diag(Templated->getLocation(), 11455 diag::note_ovl_candidate_incomplete_deduction_pack) 11456 << ParamD->getDeclName() 11457 << (DeductionFailure.getFirstArg()->pack_size() + 1) 11458 << *DeductionFailure.getFirstArg(); 11459 MaybeEmitInheritedConstructorNote(S, Found); 11460 return; 11461 } 11462 11463 case Sema::TDK_Underqualified: { 11464 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 11465 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 11466 11467 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 11468 11469 // Param will have been canonicalized, but it should just be a 11470 // qualified version of ParamD, so move the qualifiers to that. 11471 QualifierCollector Qs; 11472 Qs.strip(Param); 11473 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 11474 assert(S.Context.hasSameType(Param, NonCanonParam)); 11475 11476 // Arg has also been canonicalized, but there's nothing we can do 11477 // about that. It also doesn't matter as much, because it won't 11478 // have any template parameters in it (because deduction isn't 11479 // done on dependent types). 11480 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 11481 11482 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 11483 << ParamD->getDeclName() << Arg << NonCanonParam; 11484 MaybeEmitInheritedConstructorNote(S, Found); 11485 return; 11486 } 11487 11488 case Sema::TDK_Inconsistent: { 11489 assert(ParamD && "no parameter found for inconsistent deduction result"); 11490 int which = 0; 11491 if (isa<TemplateTypeParmDecl>(ParamD)) 11492 which = 0; 11493 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 11494 // Deduction might have failed because we deduced arguments of two 11495 // different types for a non-type template parameter. 11496 // FIXME: Use a different TDK value for this. 11497 QualType T1 = 11498 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 11499 QualType T2 = 11500 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 11501 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 11502 S.Diag(Templated->getLocation(), 11503 diag::note_ovl_candidate_inconsistent_deduction_types) 11504 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 11505 << *DeductionFailure.getSecondArg() << T2; 11506 MaybeEmitInheritedConstructorNote(S, Found); 11507 return; 11508 } 11509 11510 which = 1; 11511 } else { 11512 which = 2; 11513 } 11514 11515 // Tweak the diagnostic if the problem is that we deduced packs of 11516 // different arities. We'll print the actual packs anyway in case that 11517 // includes additional useful information. 11518 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 11519 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 11520 DeductionFailure.getFirstArg()->pack_size() != 11521 DeductionFailure.getSecondArg()->pack_size()) { 11522 which = 3; 11523 } 11524 11525 S.Diag(Templated->getLocation(), 11526 diag::note_ovl_candidate_inconsistent_deduction) 11527 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 11528 << *DeductionFailure.getSecondArg(); 11529 MaybeEmitInheritedConstructorNote(S, Found); 11530 return; 11531 } 11532 11533 case Sema::TDK_InvalidExplicitArguments: 11534 assert(ParamD && "no parameter found for invalid explicit arguments"); 11535 if (ParamD->getDeclName()) 11536 S.Diag(Templated->getLocation(), 11537 diag::note_ovl_candidate_explicit_arg_mismatch_named) 11538 << ParamD->getDeclName(); 11539 else { 11540 int index = 0; 11541 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 11542 index = TTP->getIndex(); 11543 else if (NonTypeTemplateParmDecl *NTTP 11544 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 11545 index = NTTP->getIndex(); 11546 else 11547 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 11548 S.Diag(Templated->getLocation(), 11549 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 11550 << (index + 1); 11551 } 11552 MaybeEmitInheritedConstructorNote(S, Found); 11553 return; 11554 11555 case Sema::TDK_ConstraintsNotSatisfied: { 11556 // Format the template argument list into the argument string. 11557 SmallString<128> TemplateArgString; 11558 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 11559 TemplateArgString = " "; 11560 TemplateArgString += S.getTemplateArgumentBindingsText( 11561 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11562 if (TemplateArgString.size() == 1) 11563 TemplateArgString.clear(); 11564 S.Diag(Templated->getLocation(), 11565 diag::note_ovl_candidate_unsatisfied_constraints) 11566 << TemplateArgString; 11567 11568 S.DiagnoseUnsatisfiedConstraint( 11569 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 11570 return; 11571 } 11572 case Sema::TDK_TooManyArguments: 11573 case Sema::TDK_TooFewArguments: 11574 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 11575 return; 11576 11577 case Sema::TDK_InstantiationDepth: 11578 S.Diag(Templated->getLocation(), 11579 diag::note_ovl_candidate_instantiation_depth); 11580 MaybeEmitInheritedConstructorNote(S, Found); 11581 return; 11582 11583 case Sema::TDK_SubstitutionFailure: { 11584 // Format the template argument list into the argument string. 11585 SmallString<128> TemplateArgString; 11586 if (TemplateArgumentList *Args = 11587 DeductionFailure.getTemplateArgumentList()) { 11588 TemplateArgString = " "; 11589 TemplateArgString += S.getTemplateArgumentBindingsText( 11590 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11591 if (TemplateArgString.size() == 1) 11592 TemplateArgString.clear(); 11593 } 11594 11595 // If this candidate was disabled by enable_if, say so. 11596 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 11597 if (PDiag && PDiag->second.getDiagID() == 11598 diag::err_typename_nested_not_found_enable_if) { 11599 // FIXME: Use the source range of the condition, and the fully-qualified 11600 // name of the enable_if template. These are both present in PDiag. 11601 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 11602 << "'enable_if'" << TemplateArgString; 11603 return; 11604 } 11605 11606 // We found a specific requirement that disabled the enable_if. 11607 if (PDiag && PDiag->second.getDiagID() == 11608 diag::err_typename_nested_not_found_requirement) { 11609 S.Diag(Templated->getLocation(), 11610 diag::note_ovl_candidate_disabled_by_requirement) 11611 << PDiag->second.getStringArg(0) << TemplateArgString; 11612 return; 11613 } 11614 11615 // Format the SFINAE diagnostic into the argument string. 11616 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 11617 // formatted message in another diagnostic. 11618 SmallString<128> SFINAEArgString; 11619 SourceRange R; 11620 if (PDiag) { 11621 SFINAEArgString = ": "; 11622 R = SourceRange(PDiag->first, PDiag->first); 11623 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 11624 } 11625 11626 S.Diag(Templated->getLocation(), 11627 diag::note_ovl_candidate_substitution_failure) 11628 << TemplateArgString << SFINAEArgString << R; 11629 MaybeEmitInheritedConstructorNote(S, Found); 11630 return; 11631 } 11632 11633 case Sema::TDK_DeducedMismatch: 11634 case Sema::TDK_DeducedMismatchNested: { 11635 // Format the template argument list into the argument string. 11636 SmallString<128> TemplateArgString; 11637 if (TemplateArgumentList *Args = 11638 DeductionFailure.getTemplateArgumentList()) { 11639 TemplateArgString = " "; 11640 TemplateArgString += S.getTemplateArgumentBindingsText( 11641 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11642 if (TemplateArgString.size() == 1) 11643 TemplateArgString.clear(); 11644 } 11645 11646 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11647 << (*DeductionFailure.getCallArgIndex() + 1) 11648 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11649 << TemplateArgString 11650 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11651 break; 11652 } 11653 11654 case Sema::TDK_NonDeducedMismatch: { 11655 // FIXME: Provide a source location to indicate what we couldn't match. 11656 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11657 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11658 if (FirstTA.getKind() == TemplateArgument::Template && 11659 SecondTA.getKind() == TemplateArgument::Template) { 11660 TemplateName FirstTN = FirstTA.getAsTemplate(); 11661 TemplateName SecondTN = SecondTA.getAsTemplate(); 11662 if (FirstTN.getKind() == TemplateName::Template && 11663 SecondTN.getKind() == TemplateName::Template) { 11664 if (FirstTN.getAsTemplateDecl()->getName() == 11665 SecondTN.getAsTemplateDecl()->getName()) { 11666 // FIXME: This fixes a bad diagnostic where both templates are named 11667 // the same. This particular case is a bit difficult since: 11668 // 1) It is passed as a string to the diagnostic printer. 11669 // 2) The diagnostic printer only attempts to find a better 11670 // name for types, not decls. 11671 // Ideally, this should folded into the diagnostic printer. 11672 S.Diag(Templated->getLocation(), 11673 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11674 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11675 return; 11676 } 11677 } 11678 } 11679 11680 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11681 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11682 return; 11683 11684 // FIXME: For generic lambda parameters, check if the function is a lambda 11685 // call operator, and if so, emit a prettier and more informative 11686 // diagnostic that mentions 'auto' and lambda in addition to 11687 // (or instead of?) the canonical template type parameters. 11688 S.Diag(Templated->getLocation(), 11689 diag::note_ovl_candidate_non_deduced_mismatch) 11690 << FirstTA << SecondTA; 11691 return; 11692 } 11693 // TODO: diagnose these individually, then kill off 11694 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11695 case Sema::TDK_MiscellaneousDeductionFailure: 11696 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11697 MaybeEmitInheritedConstructorNote(S, Found); 11698 return; 11699 case Sema::TDK_CUDATargetMismatch: 11700 S.Diag(Templated->getLocation(), 11701 diag::note_cuda_ovl_candidate_target_mismatch); 11702 return; 11703 } 11704 } 11705 11706 /// Diagnose a failed template-argument deduction, for function calls. 11707 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11708 unsigned NumArgs, 11709 bool TakingCandidateAddress) { 11710 unsigned TDK = Cand->DeductionFailure.Result; 11711 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11712 if (CheckArityMismatch(S, Cand, NumArgs)) 11713 return; 11714 } 11715 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11716 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11717 } 11718 11719 /// CUDA: diagnose an invalid call across targets. 11720 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11721 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 11722 FunctionDecl *Callee = Cand->Function; 11723 11724 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11725 CalleeTarget = S.IdentifyCUDATarget(Callee); 11726 11727 std::string FnDesc; 11728 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11729 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11730 Cand->getRewriteKind(), FnDesc); 11731 11732 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11733 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11734 << FnDesc /* Ignored */ 11735 << CalleeTarget << CallerTarget; 11736 11737 // This could be an implicit constructor for which we could not infer the 11738 // target due to a collsion. Diagnose that case. 11739 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11740 if (Meth != nullptr && Meth->isImplicit()) { 11741 CXXRecordDecl *ParentClass = Meth->getParent(); 11742 Sema::CXXSpecialMember CSM; 11743 11744 switch (FnKindPair.first) { 11745 default: 11746 return; 11747 case oc_implicit_default_constructor: 11748 CSM = Sema::CXXDefaultConstructor; 11749 break; 11750 case oc_implicit_copy_constructor: 11751 CSM = Sema::CXXCopyConstructor; 11752 break; 11753 case oc_implicit_move_constructor: 11754 CSM = Sema::CXXMoveConstructor; 11755 break; 11756 case oc_implicit_copy_assignment: 11757 CSM = Sema::CXXCopyAssignment; 11758 break; 11759 case oc_implicit_move_assignment: 11760 CSM = Sema::CXXMoveAssignment; 11761 break; 11762 }; 11763 11764 bool ConstRHS = false; 11765 if (Meth->getNumParams()) { 11766 if (const ReferenceType *RT = 11767 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11768 ConstRHS = RT->getPointeeType().isConstQualified(); 11769 } 11770 } 11771 11772 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11773 /* ConstRHS */ ConstRHS, 11774 /* Diagnose */ true); 11775 } 11776 } 11777 11778 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11779 FunctionDecl *Callee = Cand->Function; 11780 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11781 11782 S.Diag(Callee->getLocation(), 11783 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11784 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11785 } 11786 11787 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11788 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11789 assert(ES.isExplicit() && "not an explicit candidate"); 11790 11791 unsigned Kind; 11792 switch (Cand->Function->getDeclKind()) { 11793 case Decl::Kind::CXXConstructor: 11794 Kind = 0; 11795 break; 11796 case Decl::Kind::CXXConversion: 11797 Kind = 1; 11798 break; 11799 case Decl::Kind::CXXDeductionGuide: 11800 Kind = Cand->Function->isImplicit() ? 0 : 2; 11801 break; 11802 default: 11803 llvm_unreachable("invalid Decl"); 11804 } 11805 11806 // Note the location of the first (in-class) declaration; a redeclaration 11807 // (particularly an out-of-class definition) will typically lack the 11808 // 'explicit' specifier. 11809 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11810 FunctionDecl *First = Cand->Function->getFirstDecl(); 11811 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11812 First = Pattern->getFirstDecl(); 11813 11814 S.Diag(First->getLocation(), 11815 diag::note_ovl_candidate_explicit) 11816 << Kind << (ES.getExpr() ? 1 : 0) 11817 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11818 } 11819 11820 /// Generates a 'note' diagnostic for an overload candidate. We've 11821 /// already generated a primary error at the call site. 11822 /// 11823 /// It really does need to be a single diagnostic with its caret 11824 /// pointed at the candidate declaration. Yes, this creates some 11825 /// major challenges of technical writing. Yes, this makes pointing 11826 /// out problems with specific arguments quite awkward. It's still 11827 /// better than generating twenty screens of text for every failed 11828 /// overload. 11829 /// 11830 /// It would be great to be able to express per-candidate problems 11831 /// more richly for those diagnostic clients that cared, but we'd 11832 /// still have to be just as careful with the default diagnostics. 11833 /// \param CtorDestAS Addr space of object being constructed (for ctor 11834 /// candidates only). 11835 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11836 unsigned NumArgs, 11837 bool TakingCandidateAddress, 11838 LangAS CtorDestAS = LangAS::Default) { 11839 FunctionDecl *Fn = Cand->Function; 11840 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11841 return; 11842 11843 // There is no physical candidate declaration to point to for OpenCL builtins. 11844 // Except for failed conversions, the notes are identical for each candidate, 11845 // so do not generate such notes. 11846 if (S.getLangOpts().OpenCL && Fn->isImplicit() && 11847 Cand->FailureKind != ovl_fail_bad_conversion) 11848 return; 11849 11850 // Note deleted candidates, but only if they're viable. 11851 if (Cand->Viable) { 11852 if (Fn->isDeleted()) { 11853 std::string FnDesc; 11854 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11855 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11856 Cand->getRewriteKind(), FnDesc); 11857 11858 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11859 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11860 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11861 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11862 return; 11863 } 11864 11865 // We don't really have anything else to say about viable candidates. 11866 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11867 return; 11868 } 11869 11870 switch (Cand->FailureKind) { 11871 case ovl_fail_too_many_arguments: 11872 case ovl_fail_too_few_arguments: 11873 return DiagnoseArityMismatch(S, Cand, NumArgs); 11874 11875 case ovl_fail_bad_deduction: 11876 return DiagnoseBadDeduction(S, Cand, NumArgs, 11877 TakingCandidateAddress); 11878 11879 case ovl_fail_illegal_constructor: { 11880 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11881 << (Fn->getPrimaryTemplate() ? 1 : 0); 11882 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11883 return; 11884 } 11885 11886 case ovl_fail_object_addrspace_mismatch: { 11887 Qualifiers QualsForPrinting; 11888 QualsForPrinting.setAddressSpace(CtorDestAS); 11889 S.Diag(Fn->getLocation(), 11890 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11891 << QualsForPrinting; 11892 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11893 return; 11894 } 11895 11896 case ovl_fail_trivial_conversion: 11897 case ovl_fail_bad_final_conversion: 11898 case ovl_fail_final_conversion_not_exact: 11899 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11900 11901 case ovl_fail_bad_conversion: { 11902 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11903 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11904 if (Cand->Conversions[I].isBad()) 11905 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11906 11907 // FIXME: this currently happens when we're called from SemaInit 11908 // when user-conversion overload fails. Figure out how to handle 11909 // those conditions and diagnose them well. 11910 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11911 } 11912 11913 case ovl_fail_bad_target: 11914 return DiagnoseBadTarget(S, Cand); 11915 11916 case ovl_fail_enable_if: 11917 return DiagnoseFailedEnableIfAttr(S, Cand); 11918 11919 case ovl_fail_explicit: 11920 return DiagnoseFailedExplicitSpec(S, Cand); 11921 11922 case ovl_fail_inhctor_slice: 11923 // It's generally not interesting to note copy/move constructors here. 11924 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11925 return; 11926 S.Diag(Fn->getLocation(), 11927 diag::note_ovl_candidate_inherited_constructor_slice) 11928 << (Fn->getPrimaryTemplate() ? 1 : 0) 11929 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11930 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11931 return; 11932 11933 case ovl_fail_addr_not_available: { 11934 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11935 (void)Available; 11936 assert(!Available); 11937 break; 11938 } 11939 case ovl_non_default_multiversion_function: 11940 // Do nothing, these should simply be ignored. 11941 break; 11942 11943 case ovl_fail_constraints_not_satisfied: { 11944 std::string FnDesc; 11945 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11946 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11947 Cand->getRewriteKind(), FnDesc); 11948 11949 S.Diag(Fn->getLocation(), 11950 diag::note_ovl_candidate_constraints_not_satisfied) 11951 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11952 << FnDesc /* Ignored */; 11953 ConstraintSatisfaction Satisfaction; 11954 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11955 break; 11956 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11957 } 11958 } 11959 } 11960 11961 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11962 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11963 return; 11964 11965 // Desugar the type of the surrogate down to a function type, 11966 // retaining as many typedefs as possible while still showing 11967 // the function type (and, therefore, its parameter types). 11968 QualType FnType = Cand->Surrogate->getConversionType(); 11969 bool isLValueReference = false; 11970 bool isRValueReference = false; 11971 bool isPointer = false; 11972 if (const LValueReferenceType *FnTypeRef = 11973 FnType->getAs<LValueReferenceType>()) { 11974 FnType = FnTypeRef->getPointeeType(); 11975 isLValueReference = true; 11976 } else if (const RValueReferenceType *FnTypeRef = 11977 FnType->getAs<RValueReferenceType>()) { 11978 FnType = FnTypeRef->getPointeeType(); 11979 isRValueReference = true; 11980 } 11981 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11982 FnType = FnTypePtr->getPointeeType(); 11983 isPointer = true; 11984 } 11985 // Desugar down to a function type. 11986 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11987 // Reconstruct the pointer/reference as appropriate. 11988 if (isPointer) FnType = S.Context.getPointerType(FnType); 11989 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11990 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11991 11992 if (!Cand->Viable && 11993 Cand->FailureKind == ovl_fail_constraints_not_satisfied) { 11994 S.Diag(Cand->Surrogate->getLocation(), 11995 diag::note_ovl_surrogate_constraints_not_satisfied) 11996 << Cand->Surrogate; 11997 ConstraintSatisfaction Satisfaction; 11998 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction)) 11999 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 12000 } else { 12001 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 12002 << FnType; 12003 } 12004 } 12005 12006 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 12007 SourceLocation OpLoc, 12008 OverloadCandidate *Cand) { 12009 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 12010 std::string TypeStr("operator"); 12011 TypeStr += Opc; 12012 TypeStr += "("; 12013 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 12014 if (Cand->Conversions.size() == 1) { 12015 TypeStr += ")"; 12016 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 12017 } else { 12018 TypeStr += ", "; 12019 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 12020 TypeStr += ")"; 12021 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 12022 } 12023 } 12024 12025 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 12026 OverloadCandidate *Cand) { 12027 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 12028 if (ICS.isBad()) break; // all meaningless after first invalid 12029 if (!ICS.isAmbiguous()) continue; 12030 12031 ICS.DiagnoseAmbiguousConversion( 12032 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 12033 } 12034 } 12035 12036 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 12037 if (Cand->Function) 12038 return Cand->Function->getLocation(); 12039 if (Cand->IsSurrogate) 12040 return Cand->Surrogate->getLocation(); 12041 return SourceLocation(); 12042 } 12043 12044 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 12045 switch ((Sema::TemplateDeductionResult)DFI.Result) { 12046 case Sema::TDK_Success: 12047 case Sema::TDK_NonDependentConversionFailure: 12048 case Sema::TDK_AlreadyDiagnosed: 12049 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 12050 12051 case Sema::TDK_Invalid: 12052 case Sema::TDK_Incomplete: 12053 case Sema::TDK_IncompletePack: 12054 return 1; 12055 12056 case Sema::TDK_Underqualified: 12057 case Sema::TDK_Inconsistent: 12058 return 2; 12059 12060 case Sema::TDK_SubstitutionFailure: 12061 case Sema::TDK_DeducedMismatch: 12062 case Sema::TDK_ConstraintsNotSatisfied: 12063 case Sema::TDK_DeducedMismatchNested: 12064 case Sema::TDK_NonDeducedMismatch: 12065 case Sema::TDK_MiscellaneousDeductionFailure: 12066 case Sema::TDK_CUDATargetMismatch: 12067 return 3; 12068 12069 case Sema::TDK_InstantiationDepth: 12070 return 4; 12071 12072 case Sema::TDK_InvalidExplicitArguments: 12073 return 5; 12074 12075 case Sema::TDK_TooManyArguments: 12076 case Sema::TDK_TooFewArguments: 12077 return 6; 12078 } 12079 llvm_unreachable("Unhandled deduction result"); 12080 } 12081 12082 namespace { 12083 12084 struct CompareOverloadCandidatesForDisplay { 12085 Sema &S; 12086 SourceLocation Loc; 12087 size_t NumArgs; 12088 OverloadCandidateSet::CandidateSetKind CSK; 12089 12090 CompareOverloadCandidatesForDisplay( 12091 Sema &S, SourceLocation Loc, size_t NArgs, 12092 OverloadCandidateSet::CandidateSetKind CSK) 12093 : S(S), NumArgs(NArgs), CSK(CSK) {} 12094 12095 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 12096 // If there are too many or too few arguments, that's the high-order bit we 12097 // want to sort by, even if the immediate failure kind was something else. 12098 if (C->FailureKind == ovl_fail_too_many_arguments || 12099 C->FailureKind == ovl_fail_too_few_arguments) 12100 return static_cast<OverloadFailureKind>(C->FailureKind); 12101 12102 if (C->Function) { 12103 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 12104 return ovl_fail_too_many_arguments; 12105 if (NumArgs < C->Function->getMinRequiredArguments()) 12106 return ovl_fail_too_few_arguments; 12107 } 12108 12109 return static_cast<OverloadFailureKind>(C->FailureKind); 12110 } 12111 12112 bool operator()(const OverloadCandidate *L, 12113 const OverloadCandidate *R) { 12114 // Fast-path this check. 12115 if (L == R) return false; 12116 12117 // Order first by viability. 12118 if (L->Viable) { 12119 if (!R->Viable) return true; 12120 12121 if (int Ord = CompareConversions(*L, *R)) 12122 return Ord < 0; 12123 // Use other tie breakers. 12124 } else if (R->Viable) 12125 return false; 12126 12127 assert(L->Viable == R->Viable); 12128 12129 // Criteria by which we can sort non-viable candidates: 12130 if (!L->Viable) { 12131 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 12132 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 12133 12134 // 1. Arity mismatches come after other candidates. 12135 if (LFailureKind == ovl_fail_too_many_arguments || 12136 LFailureKind == ovl_fail_too_few_arguments) { 12137 if (RFailureKind == ovl_fail_too_many_arguments || 12138 RFailureKind == ovl_fail_too_few_arguments) { 12139 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 12140 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 12141 if (LDist == RDist) { 12142 if (LFailureKind == RFailureKind) 12143 // Sort non-surrogates before surrogates. 12144 return !L->IsSurrogate && R->IsSurrogate; 12145 // Sort candidates requiring fewer parameters than there were 12146 // arguments given after candidates requiring more parameters 12147 // than there were arguments given. 12148 return LFailureKind == ovl_fail_too_many_arguments; 12149 } 12150 return LDist < RDist; 12151 } 12152 return false; 12153 } 12154 if (RFailureKind == ovl_fail_too_many_arguments || 12155 RFailureKind == ovl_fail_too_few_arguments) 12156 return true; 12157 12158 // 2. Bad conversions come first and are ordered by the number 12159 // of bad conversions and quality of good conversions. 12160 if (LFailureKind == ovl_fail_bad_conversion) { 12161 if (RFailureKind != ovl_fail_bad_conversion) 12162 return true; 12163 12164 // The conversion that can be fixed with a smaller number of changes, 12165 // comes first. 12166 unsigned numLFixes = L->Fix.NumConversionsFixed; 12167 unsigned numRFixes = R->Fix.NumConversionsFixed; 12168 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 12169 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 12170 if (numLFixes != numRFixes) { 12171 return numLFixes < numRFixes; 12172 } 12173 12174 // If there's any ordering between the defined conversions... 12175 if (int Ord = CompareConversions(*L, *R)) 12176 return Ord < 0; 12177 } else if (RFailureKind == ovl_fail_bad_conversion) 12178 return false; 12179 12180 if (LFailureKind == ovl_fail_bad_deduction) { 12181 if (RFailureKind != ovl_fail_bad_deduction) 12182 return true; 12183 12184 if (L->DeductionFailure.Result != R->DeductionFailure.Result) { 12185 unsigned LRank = RankDeductionFailure(L->DeductionFailure); 12186 unsigned RRank = RankDeductionFailure(R->DeductionFailure); 12187 if (LRank != RRank) 12188 return LRank < RRank; 12189 } 12190 } else if (RFailureKind == ovl_fail_bad_deduction) 12191 return false; 12192 12193 // TODO: others? 12194 } 12195 12196 // Sort everything else by location. 12197 SourceLocation LLoc = GetLocationForCandidate(L); 12198 SourceLocation RLoc = GetLocationForCandidate(R); 12199 12200 // Put candidates without locations (e.g. builtins) at the end. 12201 if (LLoc.isValid() && RLoc.isValid()) 12202 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 12203 if (LLoc.isValid() && !RLoc.isValid()) 12204 return true; 12205 if (RLoc.isValid() && !LLoc.isValid()) 12206 return false; 12207 assert(!LLoc.isValid() && !RLoc.isValid()); 12208 // For builtins and other functions without locations, fallback to the order 12209 // in which they were added into the candidate set. 12210 return L < R; 12211 } 12212 12213 private: 12214 struct ConversionSignals { 12215 unsigned KindRank = 0; 12216 ImplicitConversionRank Rank = ICR_Exact_Match; 12217 12218 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) { 12219 ConversionSignals Sig; 12220 Sig.KindRank = Seq.getKindRank(); 12221 if (Seq.isStandard()) 12222 Sig.Rank = Seq.Standard.getRank(); 12223 else if (Seq.isUserDefined()) 12224 Sig.Rank = Seq.UserDefined.After.getRank(); 12225 // We intend StaticObjectArgumentConversion to compare the same as 12226 // StandardConversion with ICR_ExactMatch rank. 12227 return Sig; 12228 } 12229 12230 static ConversionSignals ForObjectArgument() { 12231 // We intend StaticObjectArgumentConversion to compare the same as 12232 // StandardConversion with ICR_ExactMatch rank. Default give us that. 12233 return {}; 12234 } 12235 }; 12236 12237 // Returns -1 if conversions in L are considered better. 12238 // 0 if they are considered indistinguishable. 12239 // 1 if conversions in R are better. 12240 int CompareConversions(const OverloadCandidate &L, 12241 const OverloadCandidate &R) { 12242 // We cannot use `isBetterOverloadCandidate` because it is defined 12243 // according to the C++ standard and provides a partial order, but we need 12244 // a total order as this function is used in sort. 12245 assert(L.Conversions.size() == R.Conversions.size()); 12246 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) { 12247 auto LS = L.IgnoreObjectArgument && I == 0 12248 ? ConversionSignals::ForObjectArgument() 12249 : ConversionSignals::ForSequence(L.Conversions[I]); 12250 auto RS = R.IgnoreObjectArgument 12251 ? ConversionSignals::ForObjectArgument() 12252 : ConversionSignals::ForSequence(R.Conversions[I]); 12253 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank)) 12254 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank) 12255 ? -1 12256 : 1; 12257 } 12258 // FIXME: find a way to compare templates for being more or less 12259 // specialized that provides a strict weak ordering. 12260 return 0; 12261 } 12262 }; 12263 } 12264 12265 /// CompleteNonViableCandidate - Normally, overload resolution only 12266 /// computes up to the first bad conversion. Produces the FixIt set if 12267 /// possible. 12268 static void 12269 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 12270 ArrayRef<Expr *> Args, 12271 OverloadCandidateSet::CandidateSetKind CSK) { 12272 assert(!Cand->Viable); 12273 12274 // Don't do anything on failures other than bad conversion. 12275 if (Cand->FailureKind != ovl_fail_bad_conversion) 12276 return; 12277 12278 // We only want the FixIts if all the arguments can be corrected. 12279 bool Unfixable = false; 12280 // Use a implicit copy initialization to check conversion fixes. 12281 Cand->Fix.setConversionChecker(TryCopyInitialization); 12282 12283 // Attempt to fix the bad conversion. 12284 unsigned ConvCount = Cand->Conversions.size(); 12285 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 12286 ++ConvIdx) { 12287 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 12288 if (Cand->Conversions[ConvIdx].isInitialized() && 12289 Cand->Conversions[ConvIdx].isBad()) { 12290 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 12291 break; 12292 } 12293 } 12294 12295 // FIXME: this should probably be preserved from the overload 12296 // operation somehow. 12297 bool SuppressUserConversions = false; 12298 12299 unsigned ConvIdx = 0; 12300 unsigned ArgIdx = 0; 12301 ArrayRef<QualType> ParamTypes; 12302 bool Reversed = Cand->isReversed(); 12303 12304 if (Cand->IsSurrogate) { 12305 QualType ConvType 12306 = Cand->Surrogate->getConversionType().getNonReferenceType(); 12307 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12308 ConvType = ConvPtrType->getPointeeType(); 12309 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 12310 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 12311 ConvIdx = 1; 12312 } else if (Cand->Function) { 12313 ParamTypes = 12314 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 12315 if (isa<CXXMethodDecl>(Cand->Function) && 12316 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 12317 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 12318 ConvIdx = 1; 12319 if (CSK == OverloadCandidateSet::CSK_Operator && 12320 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 12321 Cand->Function->getDeclName().getCXXOverloadedOperator() != 12322 OO_Subscript) 12323 // Argument 0 is 'this', which doesn't have a corresponding parameter. 12324 ArgIdx = 1; 12325 } 12326 } else { 12327 // Builtin operator. 12328 assert(ConvCount <= 3); 12329 ParamTypes = Cand->BuiltinParamTypes; 12330 } 12331 12332 // Fill in the rest of the conversions. 12333 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 12334 ConvIdx != ConvCount; 12335 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 12336 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 12337 if (Cand->Conversions[ConvIdx].isInitialized()) { 12338 // We've already checked this conversion. 12339 } else if (ParamIdx < ParamTypes.size()) { 12340 if (ParamTypes[ParamIdx]->isDependentType()) 12341 Cand->Conversions[ConvIdx].setAsIdentityConversion( 12342 Args[ArgIdx]->getType()); 12343 else { 12344 Cand->Conversions[ConvIdx] = 12345 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 12346 SuppressUserConversions, 12347 /*InOverloadResolution=*/true, 12348 /*AllowObjCWritebackConversion=*/ 12349 S.getLangOpts().ObjCAutoRefCount); 12350 // Store the FixIt in the candidate if it exists. 12351 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 12352 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 12353 } 12354 } else 12355 Cand->Conversions[ConvIdx].setEllipsis(); 12356 } 12357 } 12358 12359 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 12360 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 12361 SourceLocation OpLoc, 12362 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 12363 // Sort the candidates by viability and position. Sorting directly would 12364 // be prohibitive, so we make a set of pointers and sort those. 12365 SmallVector<OverloadCandidate*, 32> Cands; 12366 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 12367 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12368 if (!Filter(*Cand)) 12369 continue; 12370 switch (OCD) { 12371 case OCD_AllCandidates: 12372 if (!Cand->Viable) { 12373 if (!Cand->Function && !Cand->IsSurrogate) { 12374 // This a non-viable builtin candidate. We do not, in general, 12375 // want to list every possible builtin candidate. 12376 continue; 12377 } 12378 CompleteNonViableCandidate(S, Cand, Args, Kind); 12379 } 12380 break; 12381 12382 case OCD_ViableCandidates: 12383 if (!Cand->Viable) 12384 continue; 12385 break; 12386 12387 case OCD_AmbiguousCandidates: 12388 if (!Cand->Best) 12389 continue; 12390 break; 12391 } 12392 12393 Cands.push_back(Cand); 12394 } 12395 12396 llvm::stable_sort( 12397 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 12398 12399 return Cands; 12400 } 12401 12402 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 12403 SourceLocation OpLoc) { 12404 bool DeferHint = false; 12405 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 12406 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 12407 // host device candidates. 12408 auto WrongSidedCands = 12409 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 12410 return (Cand.Viable == false && 12411 Cand.FailureKind == ovl_fail_bad_target) || 12412 (Cand.Function && 12413 Cand.Function->template hasAttr<CUDAHostAttr>() && 12414 Cand.Function->template hasAttr<CUDADeviceAttr>()); 12415 }); 12416 DeferHint = !WrongSidedCands.empty(); 12417 } 12418 return DeferHint; 12419 } 12420 12421 /// When overload resolution fails, prints diagnostic messages containing the 12422 /// candidates in the candidate set. 12423 void OverloadCandidateSet::NoteCandidates( 12424 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 12425 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 12426 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 12427 12428 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 12429 12430 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 12431 12432 // In WebAssembly we don't want to emit further diagnostics if a table is 12433 // passed as an argument to a function. 12434 bool NoteCands = true; 12435 for (const Expr *Arg : Args) { 12436 if (Arg->getType()->isWebAssemblyTableType()) 12437 NoteCands = false; 12438 } 12439 12440 if (NoteCands) 12441 NoteCandidates(S, Args, Cands, Opc, OpLoc); 12442 12443 if (OCD == OCD_AmbiguousCandidates) 12444 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 12445 } 12446 12447 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 12448 ArrayRef<OverloadCandidate *> Cands, 12449 StringRef Opc, SourceLocation OpLoc) { 12450 bool ReportedAmbiguousConversions = false; 12451 12452 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12453 unsigned CandsShown = 0; 12454 auto I = Cands.begin(), E = Cands.end(); 12455 for (; I != E; ++I) { 12456 OverloadCandidate *Cand = *I; 12457 12458 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 12459 ShowOverloads == Ovl_Best) { 12460 break; 12461 } 12462 ++CandsShown; 12463 12464 if (Cand->Function) 12465 NoteFunctionCandidate(S, Cand, Args.size(), 12466 /*TakingCandidateAddress=*/false, DestAS); 12467 else if (Cand->IsSurrogate) 12468 NoteSurrogateCandidate(S, Cand); 12469 else { 12470 assert(Cand->Viable && 12471 "Non-viable built-in candidates are not added to Cands."); 12472 // Generally we only see ambiguities including viable builtin 12473 // operators if overload resolution got screwed up by an 12474 // ambiguous user-defined conversion. 12475 // 12476 // FIXME: It's quite possible for different conversions to see 12477 // different ambiguities, though. 12478 if (!ReportedAmbiguousConversions) { 12479 NoteAmbiguousUserConversions(S, OpLoc, Cand); 12480 ReportedAmbiguousConversions = true; 12481 } 12482 12483 // If this is a viable builtin, print it. 12484 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 12485 } 12486 } 12487 12488 // Inform S.Diags that we've shown an overload set with N elements. This may 12489 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 12490 S.Diags.overloadCandidatesShown(CandsShown); 12491 12492 if (I != E) 12493 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 12494 shouldDeferDiags(S, Args, OpLoc)) 12495 << int(E - I); 12496 } 12497 12498 static SourceLocation 12499 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 12500 return Cand->Specialization ? Cand->Specialization->getLocation() 12501 : SourceLocation(); 12502 } 12503 12504 namespace { 12505 struct CompareTemplateSpecCandidatesForDisplay { 12506 Sema &S; 12507 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 12508 12509 bool operator()(const TemplateSpecCandidate *L, 12510 const TemplateSpecCandidate *R) { 12511 // Fast-path this check. 12512 if (L == R) 12513 return false; 12514 12515 // Assuming that both candidates are not matches... 12516 12517 // Sort by the ranking of deduction failures. 12518 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 12519 return RankDeductionFailure(L->DeductionFailure) < 12520 RankDeductionFailure(R->DeductionFailure); 12521 12522 // Sort everything else by location. 12523 SourceLocation LLoc = GetLocationForCandidate(L); 12524 SourceLocation RLoc = GetLocationForCandidate(R); 12525 12526 // Put candidates without locations (e.g. builtins) at the end. 12527 if (LLoc.isInvalid()) 12528 return false; 12529 if (RLoc.isInvalid()) 12530 return true; 12531 12532 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 12533 } 12534 }; 12535 } 12536 12537 /// Diagnose a template argument deduction failure. 12538 /// We are treating these failures as overload failures due to bad 12539 /// deductions. 12540 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 12541 bool ForTakingAddress) { 12542 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 12543 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 12544 } 12545 12546 void TemplateSpecCandidateSet::destroyCandidates() { 12547 for (iterator i = begin(), e = end(); i != e; ++i) { 12548 i->DeductionFailure.Destroy(); 12549 } 12550 } 12551 12552 void TemplateSpecCandidateSet::clear() { 12553 destroyCandidates(); 12554 Candidates.clear(); 12555 } 12556 12557 /// NoteCandidates - When no template specialization match is found, prints 12558 /// diagnostic messages containing the non-matching specializations that form 12559 /// the candidate set. 12560 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 12561 /// OCD == OCD_AllCandidates and Cand->Viable == false. 12562 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 12563 // Sort the candidates by position (assuming no candidate is a match). 12564 // Sorting directly would be prohibitive, so we make a set of pointers 12565 // and sort those. 12566 SmallVector<TemplateSpecCandidate *, 32> Cands; 12567 Cands.reserve(size()); 12568 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12569 if (Cand->Specialization) 12570 Cands.push_back(Cand); 12571 // Otherwise, this is a non-matching builtin candidate. We do not, 12572 // in general, want to list every possible builtin candidate. 12573 } 12574 12575 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 12576 12577 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 12578 // for generalization purposes (?). 12579 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12580 12581 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 12582 unsigned CandsShown = 0; 12583 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 12584 TemplateSpecCandidate *Cand = *I; 12585 12586 // Set an arbitrary limit on the number of candidates we'll spam 12587 // the user with. FIXME: This limit should depend on details of the 12588 // candidate list. 12589 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 12590 break; 12591 ++CandsShown; 12592 12593 assert(Cand->Specialization && 12594 "Non-matching built-in candidates are not added to Cands."); 12595 Cand->NoteDeductionFailure(S, ForTakingAddress); 12596 } 12597 12598 if (I != E) 12599 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 12600 } 12601 12602 // [PossiblyAFunctionType] --> [Return] 12603 // NonFunctionType --> NonFunctionType 12604 // R (A) --> R(A) 12605 // R (*)(A) --> R (A) 12606 // R (&)(A) --> R (A) 12607 // R (S::*)(A) --> R (A) 12608 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 12609 QualType Ret = PossiblyAFunctionType; 12610 if (const PointerType *ToTypePtr = 12611 PossiblyAFunctionType->getAs<PointerType>()) 12612 Ret = ToTypePtr->getPointeeType(); 12613 else if (const ReferenceType *ToTypeRef = 12614 PossiblyAFunctionType->getAs<ReferenceType>()) 12615 Ret = ToTypeRef->getPointeeType(); 12616 else if (const MemberPointerType *MemTypePtr = 12617 PossiblyAFunctionType->getAs<MemberPointerType>()) 12618 Ret = MemTypePtr->getPointeeType(); 12619 Ret = 12620 Context.getCanonicalType(Ret).getUnqualifiedType(); 12621 return Ret; 12622 } 12623 12624 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 12625 bool Complain = true) { 12626 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 12627 S.DeduceReturnType(FD, Loc, Complain)) 12628 return true; 12629 12630 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 12631 if (S.getLangOpts().CPlusPlus17 && 12632 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 12633 !S.ResolveExceptionSpec(Loc, FPT)) 12634 return true; 12635 12636 return false; 12637 } 12638 12639 namespace { 12640 // A helper class to help with address of function resolution 12641 // - allows us to avoid passing around all those ugly parameters 12642 class AddressOfFunctionResolver { 12643 Sema& S; 12644 Expr* SourceExpr; 12645 const QualType& TargetType; 12646 QualType TargetFunctionType; // Extracted function type from target type 12647 12648 bool Complain; 12649 //DeclAccessPair& ResultFunctionAccessPair; 12650 ASTContext& Context; 12651 12652 bool TargetTypeIsNonStaticMemberFunction; 12653 bool FoundNonTemplateFunction; 12654 bool StaticMemberFunctionFromBoundPointer; 12655 bool HasComplained; 12656 12657 OverloadExpr::FindResult OvlExprInfo; 12658 OverloadExpr *OvlExpr; 12659 TemplateArgumentListInfo OvlExplicitTemplateArgs; 12660 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 12661 TemplateSpecCandidateSet FailedCandidates; 12662 12663 public: 12664 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 12665 const QualType &TargetType, bool Complain) 12666 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 12667 Complain(Complain), Context(S.getASTContext()), 12668 TargetTypeIsNonStaticMemberFunction( 12669 !!TargetType->getAs<MemberPointerType>()), 12670 FoundNonTemplateFunction(false), 12671 StaticMemberFunctionFromBoundPointer(false), 12672 HasComplained(false), 12673 OvlExprInfo(OverloadExpr::find(SourceExpr)), 12674 OvlExpr(OvlExprInfo.Expression), 12675 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 12676 ExtractUnqualifiedFunctionTypeFromTargetType(); 12677 12678 if (TargetFunctionType->isFunctionType()) { 12679 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 12680 if (!UME->isImplicitAccess() && 12681 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 12682 StaticMemberFunctionFromBoundPointer = true; 12683 } else if (OvlExpr->hasExplicitTemplateArgs()) { 12684 DeclAccessPair dap; 12685 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 12686 OvlExpr, false, &dap)) { 12687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 12688 if (!Method->isStatic()) { 12689 // If the target type is a non-function type and the function found 12690 // is a non-static member function, pretend as if that was the 12691 // target, it's the only possible type to end up with. 12692 TargetTypeIsNonStaticMemberFunction = true; 12693 12694 // And skip adding the function if its not in the proper form. 12695 // We'll diagnose this due to an empty set of functions. 12696 if (!OvlExprInfo.HasFormOfMemberPointer) 12697 return; 12698 } 12699 12700 Matches.push_back(std::make_pair(dap, Fn)); 12701 } 12702 return; 12703 } 12704 12705 if (OvlExpr->hasExplicitTemplateArgs()) 12706 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 12707 12708 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 12709 // C++ [over.over]p4: 12710 // If more than one function is selected, [...] 12711 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12712 if (FoundNonTemplateFunction) 12713 EliminateAllTemplateMatches(); 12714 else 12715 EliminateAllExceptMostSpecializedTemplate(); 12716 } 12717 } 12718 12719 if (S.getLangOpts().CUDA && Matches.size() > 1) 12720 EliminateSuboptimalCudaMatches(); 12721 } 12722 12723 bool hasComplained() const { return HasComplained; } 12724 12725 private: 12726 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12727 QualType Discard; 12728 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12729 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12730 } 12731 12732 /// \return true if A is considered a better overload candidate for the 12733 /// desired type than B. 12734 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12735 // If A doesn't have exactly the correct type, we don't want to classify it 12736 // as "better" than anything else. This way, the user is required to 12737 // disambiguate for us if there are multiple candidates and no exact match. 12738 return candidateHasExactlyCorrectType(A) && 12739 (!candidateHasExactlyCorrectType(B) || 12740 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12741 } 12742 12743 /// \return true if we were able to eliminate all but one overload candidate, 12744 /// false otherwise. 12745 bool eliminiateSuboptimalOverloadCandidates() { 12746 // Same algorithm as overload resolution -- one pass to pick the "best", 12747 // another pass to be sure that nothing is better than the best. 12748 auto Best = Matches.begin(); 12749 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12750 if (isBetterCandidate(I->second, Best->second)) 12751 Best = I; 12752 12753 const FunctionDecl *BestFn = Best->second; 12754 auto IsBestOrInferiorToBest = [this, BestFn]( 12755 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12756 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12757 }; 12758 12759 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12760 // option, so we can potentially give the user a better error 12761 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12762 return false; 12763 Matches[0] = *Best; 12764 Matches.resize(1); 12765 return true; 12766 } 12767 12768 bool isTargetTypeAFunction() const { 12769 return TargetFunctionType->isFunctionType(); 12770 } 12771 12772 // [ToType] [Return] 12773 12774 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12775 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12776 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12777 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12778 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12779 } 12780 12781 // return true if any matching specializations were found 12782 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12783 const DeclAccessPair& CurAccessFunPair) { 12784 if (CXXMethodDecl *Method 12785 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12786 // Skip non-static function templates when converting to pointer, and 12787 // static when converting to member pointer. 12788 bool CanConvertToFunctionPointer = 12789 Method->isStatic() || Method->isExplicitObjectMemberFunction(); 12790 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) 12791 return false; 12792 } 12793 else if (TargetTypeIsNonStaticMemberFunction) 12794 return false; 12795 12796 // C++ [over.over]p2: 12797 // If the name is a function template, template argument deduction is 12798 // done (14.8.2.2), and if the argument deduction succeeds, the 12799 // resulting template argument list is used to generate a single 12800 // function template specialization, which is added to the set of 12801 // overloaded functions considered. 12802 FunctionDecl *Specialization = nullptr; 12803 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12804 if (Sema::TemplateDeductionResult Result 12805 = S.DeduceTemplateArguments(FunctionTemplate, 12806 &OvlExplicitTemplateArgs, 12807 TargetFunctionType, Specialization, 12808 Info, /*IsAddressOfFunction*/true)) { 12809 // Make a note of the failed deduction for diagnostics. 12810 FailedCandidates.addCandidate() 12811 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12812 MakeDeductionFailureInfo(Context, Result, Info)); 12813 return false; 12814 } 12815 12816 // Template argument deduction ensures that we have an exact match or 12817 // compatible pointer-to-function arguments that would be adjusted by ICS. 12818 // This function template specicalization works. 12819 assert(S.isSameOrCompatibleFunctionType( 12820 Context.getCanonicalType(Specialization->getType()), 12821 Context.getCanonicalType(TargetFunctionType))); 12822 12823 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12824 return false; 12825 12826 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12827 return true; 12828 } 12829 12830 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12831 const DeclAccessPair& CurAccessFunPair) { 12832 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12833 // Skip non-static functions when converting to pointer, and static 12834 // when converting to member pointer. 12835 bool CanConvertToFunctionPointer = 12836 Method->isStatic() || Method->isExplicitObjectMemberFunction(); 12837 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) 12838 return false; 12839 } 12840 else if (TargetTypeIsNonStaticMemberFunction) 12841 return false; 12842 12843 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12844 if (S.getLangOpts().CUDA) { 12845 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 12846 if (!(Caller && Caller->isImplicit()) && 12847 !S.IsAllowedCUDACall(Caller, FunDecl)) 12848 return false; 12849 } 12850 if (FunDecl->isMultiVersion()) { 12851 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12852 if (TA && !TA->isDefaultVersion()) 12853 return false; 12854 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>(); 12855 if (TVA && !TVA->isDefaultVersion()) 12856 return false; 12857 } 12858 12859 // If any candidate has a placeholder return type, trigger its deduction 12860 // now. 12861 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12862 Complain)) { 12863 HasComplained |= Complain; 12864 return false; 12865 } 12866 12867 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12868 return false; 12869 12870 // If we're in C, we need to support types that aren't exactly identical. 12871 if (!S.getLangOpts().CPlusPlus || 12872 candidateHasExactlyCorrectType(FunDecl)) { 12873 Matches.push_back(std::make_pair( 12874 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12875 FoundNonTemplateFunction = true; 12876 return true; 12877 } 12878 } 12879 12880 return false; 12881 } 12882 12883 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12884 bool Ret = false; 12885 12886 // If the overload expression doesn't have the form of a pointer to 12887 // member, don't try to convert it to a pointer-to-member type. 12888 if (IsInvalidFormOfPointerToMemberFunction()) 12889 return false; 12890 12891 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12892 E = OvlExpr->decls_end(); 12893 I != E; ++I) { 12894 // Look through any using declarations to find the underlying function. 12895 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12896 12897 // C++ [over.over]p3: 12898 // Non-member functions and static member functions match 12899 // targets of type "pointer-to-function" or "reference-to-function." 12900 // Nonstatic member functions match targets of 12901 // type "pointer-to-member-function." 12902 // Note that according to DR 247, the containing class does not matter. 12903 if (FunctionTemplateDecl *FunctionTemplate 12904 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12905 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12906 Ret = true; 12907 } 12908 // If we have explicit template arguments supplied, skip non-templates. 12909 else if (!OvlExpr->hasExplicitTemplateArgs() && 12910 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12911 Ret = true; 12912 } 12913 assert(Ret || Matches.empty()); 12914 return Ret; 12915 } 12916 12917 void EliminateAllExceptMostSpecializedTemplate() { 12918 // [...] and any given function template specialization F1 is 12919 // eliminated if the set contains a second function template 12920 // specialization whose function template is more specialized 12921 // than the function template of F1 according to the partial 12922 // ordering rules of 14.5.5.2. 12923 12924 // The algorithm specified above is quadratic. We instead use a 12925 // two-pass algorithm (similar to the one used to identify the 12926 // best viable function in an overload set) that identifies the 12927 // best function template (if it exists). 12928 12929 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12930 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12931 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12932 12933 // TODO: It looks like FailedCandidates does not serve much purpose 12934 // here, since the no_viable diagnostic has index 0. 12935 UnresolvedSetIterator Result = S.getMostSpecialized( 12936 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12937 SourceExpr->getBeginLoc(), S.PDiag(), 12938 S.PDiag(diag::err_addr_ovl_ambiguous) 12939 << Matches[0].second->getDeclName(), 12940 S.PDiag(diag::note_ovl_candidate) 12941 << (unsigned)oc_function << (unsigned)ocs_described_template, 12942 Complain, TargetFunctionType); 12943 12944 if (Result != MatchesCopy.end()) { 12945 // Make it the first and only element 12946 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12947 Matches[0].second = cast<FunctionDecl>(*Result); 12948 Matches.resize(1); 12949 } else 12950 HasComplained |= Complain; 12951 } 12952 12953 void EliminateAllTemplateMatches() { 12954 // [...] any function template specializations in the set are 12955 // eliminated if the set also contains a non-template function, [...] 12956 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12957 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12958 ++I; 12959 else { 12960 Matches[I] = Matches[--N]; 12961 Matches.resize(N); 12962 } 12963 } 12964 } 12965 12966 void EliminateSuboptimalCudaMatches() { 12967 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), 12968 Matches); 12969 } 12970 12971 public: 12972 void ComplainNoMatchesFound() const { 12973 assert(Matches.empty()); 12974 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12975 << OvlExpr->getName() << TargetFunctionType 12976 << OvlExpr->getSourceRange(); 12977 if (FailedCandidates.empty()) 12978 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12979 /*TakingAddress=*/true); 12980 else { 12981 // We have some deduction failure messages. Use them to diagnose 12982 // the function templates, and diagnose the non-template candidates 12983 // normally. 12984 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12985 IEnd = OvlExpr->decls_end(); 12986 I != IEnd; ++I) 12987 if (FunctionDecl *Fun = 12988 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12989 if (!functionHasPassObjectSizeParams(Fun)) 12990 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12991 /*TakingAddress=*/true); 12992 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12993 } 12994 } 12995 12996 bool IsInvalidFormOfPointerToMemberFunction() const { 12997 return TargetTypeIsNonStaticMemberFunction && 12998 !OvlExprInfo.HasFormOfMemberPointer; 12999 } 13000 13001 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 13002 // TODO: Should we condition this on whether any functions might 13003 // have matched, or is it more appropriate to do that in callers? 13004 // TODO: a fixit wouldn't hurt. 13005 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 13006 << TargetType << OvlExpr->getSourceRange(); 13007 } 13008 13009 bool IsStaticMemberFunctionFromBoundPointer() const { 13010 return StaticMemberFunctionFromBoundPointer; 13011 } 13012 13013 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 13014 S.Diag(OvlExpr->getBeginLoc(), 13015 diag::err_invalid_form_pointer_member_function) 13016 << OvlExpr->getSourceRange(); 13017 } 13018 13019 void ComplainOfInvalidConversion() const { 13020 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 13021 << OvlExpr->getName() << TargetType; 13022 } 13023 13024 void ComplainMultipleMatchesFound() const { 13025 assert(Matches.size() > 1); 13026 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 13027 << OvlExpr->getName() << OvlExpr->getSourceRange(); 13028 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 13029 /*TakingAddress=*/true); 13030 } 13031 13032 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 13033 13034 int getNumMatches() const { return Matches.size(); } 13035 13036 FunctionDecl* getMatchingFunctionDecl() const { 13037 if (Matches.size() != 1) return nullptr; 13038 return Matches[0].second; 13039 } 13040 13041 const DeclAccessPair* getMatchingFunctionAccessPair() const { 13042 if (Matches.size() != 1) return nullptr; 13043 return &Matches[0].first; 13044 } 13045 }; 13046 } 13047 13048 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 13049 /// an overloaded function (C++ [over.over]), where @p From is an 13050 /// expression with overloaded function type and @p ToType is the type 13051 /// we're trying to resolve to. For example: 13052 /// 13053 /// @code 13054 /// int f(double); 13055 /// int f(int); 13056 /// 13057 /// int (*pfd)(double) = f; // selects f(double) 13058 /// @endcode 13059 /// 13060 /// This routine returns the resulting FunctionDecl if it could be 13061 /// resolved, and NULL otherwise. When @p Complain is true, this 13062 /// routine will emit diagnostics if there is an error. 13063 FunctionDecl * 13064 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 13065 QualType TargetType, 13066 bool Complain, 13067 DeclAccessPair &FoundResult, 13068 bool *pHadMultipleCandidates) { 13069 assert(AddressOfExpr->getType() == Context.OverloadTy); 13070 13071 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 13072 Complain); 13073 int NumMatches = Resolver.getNumMatches(); 13074 FunctionDecl *Fn = nullptr; 13075 bool ShouldComplain = Complain && !Resolver.hasComplained(); 13076 if (NumMatches == 0 && ShouldComplain) { 13077 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 13078 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 13079 else 13080 Resolver.ComplainNoMatchesFound(); 13081 } 13082 else if (NumMatches > 1 && ShouldComplain) 13083 Resolver.ComplainMultipleMatchesFound(); 13084 else if (NumMatches == 1) { 13085 Fn = Resolver.getMatchingFunctionDecl(); 13086 assert(Fn); 13087 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13088 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 13089 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 13090 if (Complain) { 13091 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 13092 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 13093 else 13094 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 13095 } 13096 } 13097 13098 if (pHadMultipleCandidates) 13099 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 13100 return Fn; 13101 } 13102 13103 /// Given an expression that refers to an overloaded function, try to 13104 /// resolve that function to a single function that can have its address taken. 13105 /// This will modify `Pair` iff it returns non-null. 13106 /// 13107 /// This routine can only succeed if from all of the candidates in the overload 13108 /// set for SrcExpr that can have their addresses taken, there is one candidate 13109 /// that is more constrained than the rest. 13110 FunctionDecl * 13111 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 13112 OverloadExpr::FindResult R = OverloadExpr::find(E); 13113 OverloadExpr *Ovl = R.Expression; 13114 bool IsResultAmbiguous = false; 13115 FunctionDecl *Result = nullptr; 13116 DeclAccessPair DAP; 13117 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 13118 13119 // Return positive for better, negative for worse, 0 for equal preference. 13120 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) { 13121 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 13122 return static_cast<int>(IdentifyCUDAPreference(Caller, FD1)) - 13123 static_cast<int>(IdentifyCUDAPreference(Caller, FD2)); 13124 }; 13125 13126 auto CheckMoreConstrained = [&](FunctionDecl *FD1, 13127 FunctionDecl *FD2) -> std::optional<bool> { 13128 if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction()) 13129 FD1 = MF; 13130 if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction()) 13131 FD2 = MF; 13132 SmallVector<const Expr *, 1> AC1, AC2; 13133 FD1->getAssociatedConstraints(AC1); 13134 FD2->getAssociatedConstraints(AC2); 13135 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 13136 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 13137 return std::nullopt; 13138 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 13139 return std::nullopt; 13140 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 13141 return std::nullopt; 13142 return AtLeastAsConstrained1; 13143 }; 13144 13145 // Don't use the AddressOfResolver because we're specifically looking for 13146 // cases where we have one overload candidate that lacks 13147 // enable_if/pass_object_size/... 13148 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 13149 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 13150 if (!FD) 13151 return nullptr; 13152 13153 if (!checkAddressOfFunctionIsAvailable(FD)) 13154 continue; 13155 13156 // If we found a better result, update Result. 13157 auto FoundBetter = [&]() { 13158 IsResultAmbiguous = false; 13159 DAP = I.getPair(); 13160 Result = FD; 13161 }; 13162 13163 // We have more than one result - see if it is more constrained than the 13164 // previous one. 13165 if (Result) { 13166 // Check CUDA preference first. If the candidates have differennt CUDA 13167 // preference, choose the one with higher CUDA preference. Otherwise, 13168 // choose the one with more constraints. 13169 if (getLangOpts().CUDA) { 13170 int PreferenceByCUDA = CheckCUDAPreference(FD, Result); 13171 // FD has different preference than Result. 13172 if (PreferenceByCUDA != 0) { 13173 // FD is more preferable than Result. 13174 if (PreferenceByCUDA > 0) 13175 FoundBetter(); 13176 continue; 13177 } 13178 } 13179 // FD has the same CUDA prefernece than Result. Continue check 13180 // constraints. 13181 std::optional<bool> MoreConstrainedThanPrevious = 13182 CheckMoreConstrained(FD, Result); 13183 if (!MoreConstrainedThanPrevious) { 13184 IsResultAmbiguous = true; 13185 AmbiguousDecls.push_back(FD); 13186 continue; 13187 } 13188 if (!*MoreConstrainedThanPrevious) 13189 continue; 13190 // FD is more constrained - replace Result with it. 13191 } 13192 FoundBetter(); 13193 } 13194 13195 if (IsResultAmbiguous) 13196 return nullptr; 13197 13198 if (Result) { 13199 SmallVector<const Expr *, 1> ResultAC; 13200 // We skipped over some ambiguous declarations which might be ambiguous with 13201 // the selected result. 13202 for (FunctionDecl *Skipped : AmbiguousDecls) { 13203 // If skipped candidate has different CUDA preference than the result, 13204 // there is no ambiguity. Otherwise check whether they have different 13205 // constraints. 13206 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0) 13207 continue; 13208 if (!CheckMoreConstrained(Skipped, Result)) 13209 return nullptr; 13210 } 13211 Pair = DAP; 13212 } 13213 return Result; 13214 } 13215 13216 /// Given an overloaded function, tries to turn it into a non-overloaded 13217 /// function reference using resolveAddressOfSingleOverloadCandidate. This 13218 /// will perform access checks, diagnose the use of the resultant decl, and, if 13219 /// requested, potentially perform a function-to-pointer decay. 13220 /// 13221 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 13222 /// Otherwise, returns true. This may emit diagnostics and return true. 13223 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 13224 ExprResult &SrcExpr, bool DoFunctionPointerConversion) { 13225 Expr *E = SrcExpr.get(); 13226 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 13227 13228 DeclAccessPair DAP; 13229 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 13230 if (!Found || Found->isCPUDispatchMultiVersion() || 13231 Found->isCPUSpecificMultiVersion()) 13232 return false; 13233 13234 // Emitting multiple diagnostics for a function that is both inaccessible and 13235 // unavailable is consistent with our behavior elsewhere. So, always check 13236 // for both. 13237 DiagnoseUseOfDecl(Found, E->getExprLoc()); 13238 CheckAddressOfMemberAccess(E, DAP); 13239 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found); 13240 if (Res.isInvalid()) 13241 return false; 13242 Expr *Fixed = Res.get(); 13243 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType()) 13244 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 13245 else 13246 SrcExpr = Fixed; 13247 return true; 13248 } 13249 13250 /// Given an expression that refers to an overloaded function, try to 13251 /// resolve that overloaded function expression down to a single function. 13252 /// 13253 /// This routine can only resolve template-ids that refer to a single function 13254 /// template, where that template-id refers to a single template whose template 13255 /// arguments are either provided by the template-id or have defaults, 13256 /// as described in C++0x [temp.arg.explicit]p3. 13257 /// 13258 /// If no template-ids are found, no diagnostics are emitted and NULL is 13259 /// returned. 13260 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization( 13261 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult, 13262 TemplateSpecCandidateSet *FailedTSC) { 13263 // C++ [over.over]p1: 13264 // [...] [Note: any redundant set of parentheses surrounding the 13265 // overloaded function name is ignored (5.1). ] 13266 // C++ [over.over]p1: 13267 // [...] The overloaded function name can be preceded by the & 13268 // operator. 13269 13270 // If we didn't actually find any template-ids, we're done. 13271 if (!ovl->hasExplicitTemplateArgs()) 13272 return nullptr; 13273 13274 TemplateArgumentListInfo ExplicitTemplateArgs; 13275 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 13276 13277 // Look through all of the overloaded functions, searching for one 13278 // whose type matches exactly. 13279 FunctionDecl *Matched = nullptr; 13280 for (UnresolvedSetIterator I = ovl->decls_begin(), 13281 E = ovl->decls_end(); I != E; ++I) { 13282 // C++0x [temp.arg.explicit]p3: 13283 // [...] In contexts where deduction is done and fails, or in contexts 13284 // where deduction is not done, if a template argument list is 13285 // specified and it, along with any default template arguments, 13286 // identifies a single function template specialization, then the 13287 // template-id is an lvalue for the function template specialization. 13288 FunctionTemplateDecl *FunctionTemplate 13289 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 13290 13291 // C++ [over.over]p2: 13292 // If the name is a function template, template argument deduction is 13293 // done (14.8.2.2), and if the argument deduction succeeds, the 13294 // resulting template argument list is used to generate a single 13295 // function template specialization, which is added to the set of 13296 // overloaded functions considered. 13297 FunctionDecl *Specialization = nullptr; 13298 TemplateDeductionInfo Info(ovl->getNameLoc()); 13299 if (TemplateDeductionResult Result 13300 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 13301 Specialization, Info, 13302 /*IsAddressOfFunction*/true)) { 13303 // Make a note of the failed deduction for diagnostics. 13304 if (FailedTSC) 13305 FailedTSC->addCandidate().set( 13306 I.getPair(), FunctionTemplate->getTemplatedDecl(), 13307 MakeDeductionFailureInfo(Context, Result, Info)); 13308 continue; 13309 } 13310 13311 assert(Specialization && "no specialization and no error?"); 13312 13313 // Multiple matches; we can't resolve to a single declaration. 13314 if (Matched) { 13315 if (Complain) { 13316 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 13317 << ovl->getName(); 13318 NoteAllOverloadCandidates(ovl); 13319 } 13320 return nullptr; 13321 } 13322 13323 Matched = Specialization; 13324 if (FoundResult) *FoundResult = I.getPair(); 13325 } 13326 13327 if (Matched && 13328 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 13329 return nullptr; 13330 13331 return Matched; 13332 } 13333 13334 // Resolve and fix an overloaded expression that can be resolved 13335 // because it identifies a single function template specialization. 13336 // 13337 // Last three arguments should only be supplied if Complain = true 13338 // 13339 // Return true if it was logically possible to so resolve the 13340 // expression, regardless of whether or not it succeeded. Always 13341 // returns true if 'complain' is set. 13342 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 13343 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain, 13344 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining, 13345 unsigned DiagIDForComplaining) { 13346 assert(SrcExpr.get()->getType() == Context.OverloadTy); 13347 13348 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 13349 13350 DeclAccessPair found; 13351 ExprResult SingleFunctionExpression; 13352 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 13353 ovl.Expression, /*complain*/ false, &found)) { 13354 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 13355 SrcExpr = ExprError(); 13356 return true; 13357 } 13358 13359 // It is only correct to resolve to an instance method if we're 13360 // resolving a form that's permitted to be a pointer to member. 13361 // Otherwise we'll end up making a bound member expression, which 13362 // is illegal in all the contexts we resolve like this. 13363 if (!ovl.HasFormOfMemberPointer && 13364 isa<CXXMethodDecl>(fn) && 13365 cast<CXXMethodDecl>(fn)->isInstance()) { 13366 if (!complain) return false; 13367 13368 Diag(ovl.Expression->getExprLoc(), 13369 diag::err_bound_member_function) 13370 << 0 << ovl.Expression->getSourceRange(); 13371 13372 // TODO: I believe we only end up here if there's a mix of 13373 // static and non-static candidates (otherwise the expression 13374 // would have 'bound member' type, not 'overload' type). 13375 // Ideally we would note which candidate was chosen and why 13376 // the static candidates were rejected. 13377 SrcExpr = ExprError(); 13378 return true; 13379 } 13380 13381 // Fix the expression to refer to 'fn'. 13382 SingleFunctionExpression = 13383 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 13384 13385 // If desired, do function-to-pointer decay. 13386 if (doFunctionPointerConversion) { 13387 SingleFunctionExpression = 13388 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 13389 if (SingleFunctionExpression.isInvalid()) { 13390 SrcExpr = ExprError(); 13391 return true; 13392 } 13393 } 13394 } 13395 13396 if (!SingleFunctionExpression.isUsable()) { 13397 if (complain) { 13398 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 13399 << ovl.Expression->getName() 13400 << DestTypeForComplaining 13401 << OpRangeForComplaining 13402 << ovl.Expression->getQualifierLoc().getSourceRange(); 13403 NoteAllOverloadCandidates(SrcExpr.get()); 13404 13405 SrcExpr = ExprError(); 13406 return true; 13407 } 13408 13409 return false; 13410 } 13411 13412 SrcExpr = SingleFunctionExpression; 13413 return true; 13414 } 13415 13416 /// Add a single candidate to the overload set. 13417 static void AddOverloadedCallCandidate(Sema &S, 13418 DeclAccessPair FoundDecl, 13419 TemplateArgumentListInfo *ExplicitTemplateArgs, 13420 ArrayRef<Expr *> Args, 13421 OverloadCandidateSet &CandidateSet, 13422 bool PartialOverloading, 13423 bool KnownValid) { 13424 NamedDecl *Callee = FoundDecl.getDecl(); 13425 if (isa<UsingShadowDecl>(Callee)) 13426 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 13427 13428 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 13429 if (ExplicitTemplateArgs) { 13430 assert(!KnownValid && "Explicit template arguments?"); 13431 return; 13432 } 13433 // Prevent ill-formed function decls to be added as overload candidates. 13434 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 13435 return; 13436 13437 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 13438 /*SuppressUserConversions=*/false, 13439 PartialOverloading); 13440 return; 13441 } 13442 13443 if (FunctionTemplateDecl *FuncTemplate 13444 = dyn_cast<FunctionTemplateDecl>(Callee)) { 13445 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 13446 ExplicitTemplateArgs, Args, CandidateSet, 13447 /*SuppressUserConversions=*/false, 13448 PartialOverloading); 13449 return; 13450 } 13451 13452 assert(!KnownValid && "unhandled case in overloaded call candidate"); 13453 } 13454 13455 /// Add the overload candidates named by callee and/or found by argument 13456 /// dependent lookup to the given overload set. 13457 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 13458 ArrayRef<Expr *> Args, 13459 OverloadCandidateSet &CandidateSet, 13460 bool PartialOverloading) { 13461 13462 #ifndef NDEBUG 13463 // Verify that ArgumentDependentLookup is consistent with the rules 13464 // in C++0x [basic.lookup.argdep]p3: 13465 // 13466 // Let X be the lookup set produced by unqualified lookup (3.4.1) 13467 // and let Y be the lookup set produced by argument dependent 13468 // lookup (defined as follows). If X contains 13469 // 13470 // -- a declaration of a class member, or 13471 // 13472 // -- a block-scope function declaration that is not a 13473 // using-declaration, or 13474 // 13475 // -- a declaration that is neither a function or a function 13476 // template 13477 // 13478 // then Y is empty. 13479 13480 if (ULE->requiresADL()) { 13481 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 13482 E = ULE->decls_end(); I != E; ++I) { 13483 assert(!(*I)->getDeclContext()->isRecord()); 13484 assert(isa<UsingShadowDecl>(*I) || 13485 !(*I)->getDeclContext()->isFunctionOrMethod()); 13486 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 13487 } 13488 } 13489 #endif 13490 13491 // It would be nice to avoid this copy. 13492 TemplateArgumentListInfo TABuffer; 13493 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13494 if (ULE->hasExplicitTemplateArgs()) { 13495 ULE->copyTemplateArgumentsInto(TABuffer); 13496 ExplicitTemplateArgs = &TABuffer; 13497 } 13498 13499 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 13500 E = ULE->decls_end(); I != E; ++I) 13501 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 13502 CandidateSet, PartialOverloading, 13503 /*KnownValid*/ true); 13504 13505 if (ULE->requiresADL()) 13506 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 13507 Args, ExplicitTemplateArgs, 13508 CandidateSet, PartialOverloading); 13509 } 13510 13511 /// Add the call candidates from the given set of lookup results to the given 13512 /// overload set. Non-function lookup results are ignored. 13513 void Sema::AddOverloadedCallCandidates( 13514 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 13515 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 13516 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 13517 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 13518 CandidateSet, false, /*KnownValid*/ false); 13519 } 13520 13521 /// Determine whether a declaration with the specified name could be moved into 13522 /// a different namespace. 13523 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 13524 switch (Name.getCXXOverloadedOperator()) { 13525 case OO_New: case OO_Array_New: 13526 case OO_Delete: case OO_Array_Delete: 13527 return false; 13528 13529 default: 13530 return true; 13531 } 13532 } 13533 13534 /// Attempt to recover from an ill-formed use of a non-dependent name in a 13535 /// template, where the non-dependent name was declared after the template 13536 /// was defined. This is common in code written for a compilers which do not 13537 /// correctly implement two-stage name lookup. 13538 /// 13539 /// Returns true if a viable candidate was found and a diagnostic was issued. 13540 static bool DiagnoseTwoPhaseLookup( 13541 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 13542 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 13543 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 13544 CXXRecordDecl **FoundInClass = nullptr) { 13545 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 13546 return false; 13547 13548 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 13549 if (DC->isTransparentContext()) 13550 continue; 13551 13552 SemaRef.LookupQualifiedName(R, DC); 13553 13554 if (!R.empty()) { 13555 R.suppressDiagnostics(); 13556 13557 OverloadCandidateSet Candidates(FnLoc, CSK); 13558 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 13559 Candidates); 13560 13561 OverloadCandidateSet::iterator Best; 13562 OverloadingResult OR = 13563 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 13564 13565 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 13566 // We either found non-function declarations or a best viable function 13567 // at class scope. A class-scope lookup result disables ADL. Don't 13568 // look past this, but let the caller know that we found something that 13569 // either is, or might be, usable in this class. 13570 if (FoundInClass) { 13571 *FoundInClass = RD; 13572 if (OR == OR_Success) { 13573 R.clear(); 13574 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 13575 R.resolveKind(); 13576 } 13577 } 13578 return false; 13579 } 13580 13581 if (OR != OR_Success) { 13582 // There wasn't a unique best function or function template. 13583 return false; 13584 } 13585 13586 // Find the namespaces where ADL would have looked, and suggest 13587 // declaring the function there instead. 13588 Sema::AssociatedNamespaceSet AssociatedNamespaces; 13589 Sema::AssociatedClassSet AssociatedClasses; 13590 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 13591 AssociatedNamespaces, 13592 AssociatedClasses); 13593 Sema::AssociatedNamespaceSet SuggestedNamespaces; 13594 if (canBeDeclaredInNamespace(R.getLookupName())) { 13595 DeclContext *Std = SemaRef.getStdNamespace(); 13596 for (Sema::AssociatedNamespaceSet::iterator 13597 it = AssociatedNamespaces.begin(), 13598 end = AssociatedNamespaces.end(); it != end; ++it) { 13599 // Never suggest declaring a function within namespace 'std'. 13600 if (Std && Std->Encloses(*it)) 13601 continue; 13602 13603 // Never suggest declaring a function within a namespace with a 13604 // reserved name, like __gnu_cxx. 13605 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 13606 if (NS && 13607 NS->getQualifiedNameAsString().find("__") != std::string::npos) 13608 continue; 13609 13610 SuggestedNamespaces.insert(*it); 13611 } 13612 } 13613 13614 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 13615 << R.getLookupName(); 13616 if (SuggestedNamespaces.empty()) { 13617 SemaRef.Diag(Best->Function->getLocation(), 13618 diag::note_not_found_by_two_phase_lookup) 13619 << R.getLookupName() << 0; 13620 } else if (SuggestedNamespaces.size() == 1) { 13621 SemaRef.Diag(Best->Function->getLocation(), 13622 diag::note_not_found_by_two_phase_lookup) 13623 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 13624 } else { 13625 // FIXME: It would be useful to list the associated namespaces here, 13626 // but the diagnostics infrastructure doesn't provide a way to produce 13627 // a localized representation of a list of items. 13628 SemaRef.Diag(Best->Function->getLocation(), 13629 diag::note_not_found_by_two_phase_lookup) 13630 << R.getLookupName() << 2; 13631 } 13632 13633 // Try to recover by calling this function. 13634 return true; 13635 } 13636 13637 R.clear(); 13638 } 13639 13640 return false; 13641 } 13642 13643 /// Attempt to recover from ill-formed use of a non-dependent operator in a 13644 /// template, where the non-dependent operator was declared after the template 13645 /// was defined. 13646 /// 13647 /// Returns true if a viable candidate was found and a diagnostic was issued. 13648 static bool 13649 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 13650 SourceLocation OpLoc, 13651 ArrayRef<Expr *> Args) { 13652 DeclarationName OpName = 13653 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 13654 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 13655 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 13656 OverloadCandidateSet::CSK_Operator, 13657 /*ExplicitTemplateArgs=*/nullptr, Args); 13658 } 13659 13660 namespace { 13661 class BuildRecoveryCallExprRAII { 13662 Sema &SemaRef; 13663 Sema::SatisfactionStackResetRAII SatStack; 13664 13665 public: 13666 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) { 13667 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 13668 SemaRef.IsBuildingRecoveryCallExpr = true; 13669 } 13670 13671 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; } 13672 }; 13673 } 13674 13675 /// Attempts to recover from a call where no functions were found. 13676 /// 13677 /// This function will do one of three things: 13678 /// * Diagnose, recover, and return a recovery expression. 13679 /// * Diagnose, fail to recover, and return ExprError(). 13680 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 13681 /// expected to diagnose as appropriate. 13682 static ExprResult 13683 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13684 UnresolvedLookupExpr *ULE, 13685 SourceLocation LParenLoc, 13686 MutableArrayRef<Expr *> Args, 13687 SourceLocation RParenLoc, 13688 bool EmptyLookup, bool AllowTypoCorrection) { 13689 // Do not try to recover if it is already building a recovery call. 13690 // This stops infinite loops for template instantiations like 13691 // 13692 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 13693 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 13694 if (SemaRef.IsBuildingRecoveryCallExpr) 13695 return ExprResult(); 13696 BuildRecoveryCallExprRAII RCE(SemaRef); 13697 13698 CXXScopeSpec SS; 13699 SS.Adopt(ULE->getQualifierLoc()); 13700 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 13701 13702 TemplateArgumentListInfo TABuffer; 13703 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13704 if (ULE->hasExplicitTemplateArgs()) { 13705 ULE->copyTemplateArgumentsInto(TABuffer); 13706 ExplicitTemplateArgs = &TABuffer; 13707 } 13708 13709 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 13710 Sema::LookupOrdinaryName); 13711 CXXRecordDecl *FoundInClass = nullptr; 13712 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 13713 OverloadCandidateSet::CSK_Normal, 13714 ExplicitTemplateArgs, Args, &FoundInClass)) { 13715 // OK, diagnosed a two-phase lookup issue. 13716 } else if (EmptyLookup) { 13717 // Try to recover from an empty lookup with typo correction. 13718 R.clear(); 13719 NoTypoCorrectionCCC NoTypoValidator{}; 13720 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 13721 ExplicitTemplateArgs != nullptr, 13722 dyn_cast<MemberExpr>(Fn)); 13723 CorrectionCandidateCallback &Validator = 13724 AllowTypoCorrection 13725 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 13726 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 13727 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 13728 Args)) 13729 return ExprError(); 13730 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 13731 // We found a usable declaration of the name in a dependent base of some 13732 // enclosing class. 13733 // FIXME: We should also explain why the candidates found by name lookup 13734 // were not viable. 13735 if (SemaRef.DiagnoseDependentMemberLookup(R)) 13736 return ExprError(); 13737 } else { 13738 // We had viable candidates and couldn't recover; let the caller diagnose 13739 // this. 13740 return ExprResult(); 13741 } 13742 13743 // If we get here, we should have issued a diagnostic and formed a recovery 13744 // lookup result. 13745 assert(!R.empty() && "lookup results empty despite recovery"); 13746 13747 // If recovery created an ambiguity, just bail out. 13748 if (R.isAmbiguous()) { 13749 R.suppressDiagnostics(); 13750 return ExprError(); 13751 } 13752 13753 // Build an implicit member call if appropriate. Just drop the 13754 // casts and such from the call, we don't really care. 13755 ExprResult NewFn = ExprError(); 13756 if ((*R.begin())->isCXXClassMember()) 13757 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13758 ExplicitTemplateArgs, S); 13759 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13760 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13761 ExplicitTemplateArgs); 13762 else 13763 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13764 13765 if (NewFn.isInvalid()) 13766 return ExprError(); 13767 13768 // This shouldn't cause an infinite loop because we're giving it 13769 // an expression with viable lookup results, which should never 13770 // end up here. 13771 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13772 MultiExprArg(Args.data(), Args.size()), 13773 RParenLoc); 13774 } 13775 13776 /// Constructs and populates an OverloadedCandidateSet from 13777 /// the given function. 13778 /// \returns true when an the ExprResult output parameter has been set. 13779 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13780 UnresolvedLookupExpr *ULE, 13781 MultiExprArg Args, 13782 SourceLocation RParenLoc, 13783 OverloadCandidateSet *CandidateSet, 13784 ExprResult *Result) { 13785 #ifndef NDEBUG 13786 if (ULE->requiresADL()) { 13787 // To do ADL, we must have found an unqualified name. 13788 assert(!ULE->getQualifier() && "qualified name with ADL"); 13789 13790 // We don't perform ADL for implicit declarations of builtins. 13791 // Verify that this was correctly set up. 13792 FunctionDecl *F; 13793 if (ULE->decls_begin() != ULE->decls_end() && 13794 ULE->decls_begin() + 1 == ULE->decls_end() && 13795 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13796 F->getBuiltinID() && F->isImplicit()) 13797 llvm_unreachable("performing ADL for builtin"); 13798 13799 // We don't perform ADL in C. 13800 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13801 } 13802 #endif 13803 13804 UnbridgedCastsSet UnbridgedCasts; 13805 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13806 *Result = ExprError(); 13807 return true; 13808 } 13809 13810 // Add the functions denoted by the callee to the set of candidate 13811 // functions, including those from argument-dependent lookup. 13812 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13813 13814 if (getLangOpts().MSVCCompat && 13815 CurContext->isDependentContext() && !isSFINAEContext() && 13816 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13817 13818 OverloadCandidateSet::iterator Best; 13819 if (CandidateSet->empty() || 13820 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13821 OR_No_Viable_Function) { 13822 // In Microsoft mode, if we are inside a template class member function 13823 // then create a type dependent CallExpr. The goal is to postpone name 13824 // lookup to instantiation time to be able to search into type dependent 13825 // base classes. 13826 CallExpr *CE = 13827 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13828 RParenLoc, CurFPFeatureOverrides()); 13829 CE->markDependentForPostponedNameLookup(); 13830 *Result = CE; 13831 return true; 13832 } 13833 } 13834 13835 if (CandidateSet->empty()) 13836 return false; 13837 13838 UnbridgedCasts.restore(); 13839 return false; 13840 } 13841 13842 // Guess at what the return type for an unresolvable overload should be. 13843 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13844 OverloadCandidateSet::iterator *Best) { 13845 std::optional<QualType> Result; 13846 // Adjust Type after seeing a candidate. 13847 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13848 if (!Candidate.Function) 13849 return; 13850 if (Candidate.Function->isInvalidDecl()) 13851 return; 13852 QualType T = Candidate.Function->getReturnType(); 13853 if (T.isNull()) 13854 return; 13855 if (!Result) 13856 Result = T; 13857 else if (Result != T) 13858 Result = QualType(); 13859 }; 13860 13861 // Look for an unambiguous type from a progressively larger subset. 13862 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13863 // 13864 // First, consider only the best candidate. 13865 if (Best && *Best != CS.end()) 13866 ConsiderCandidate(**Best); 13867 // Next, consider only viable candidates. 13868 if (!Result) 13869 for (const auto &C : CS) 13870 if (C.Viable) 13871 ConsiderCandidate(C); 13872 // Finally, consider all candidates. 13873 if (!Result) 13874 for (const auto &C : CS) 13875 ConsiderCandidate(C); 13876 13877 if (!Result) 13878 return QualType(); 13879 auto Value = *Result; 13880 if (Value.isNull() || Value->isUndeducedType()) 13881 return QualType(); 13882 return Value; 13883 } 13884 13885 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13886 /// the completed call expression. If overload resolution fails, emits 13887 /// diagnostics and returns ExprError() 13888 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13889 UnresolvedLookupExpr *ULE, 13890 SourceLocation LParenLoc, 13891 MultiExprArg Args, 13892 SourceLocation RParenLoc, 13893 Expr *ExecConfig, 13894 OverloadCandidateSet *CandidateSet, 13895 OverloadCandidateSet::iterator *Best, 13896 OverloadingResult OverloadResult, 13897 bool AllowTypoCorrection) { 13898 switch (OverloadResult) { 13899 case OR_Success: { 13900 FunctionDecl *FDecl = (*Best)->Function; 13901 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13902 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13903 return ExprError(); 13904 ExprResult Res = 13905 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13906 if (Res.isInvalid()) 13907 return ExprError(); 13908 return SemaRef.BuildResolvedCallExpr( 13909 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, 13910 /*IsExecConfig=*/false, (*Best)->IsADLCandidate); 13911 } 13912 13913 case OR_No_Viable_Function: { 13914 // Try to recover by looking for viable functions which the user might 13915 // have meant to call. 13916 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13917 Args, RParenLoc, 13918 CandidateSet->empty(), 13919 AllowTypoCorrection); 13920 if (Recovery.isInvalid() || Recovery.isUsable()) 13921 return Recovery; 13922 13923 // If the user passes in a function that we can't take the address of, we 13924 // generally end up emitting really bad error messages. Here, we attempt to 13925 // emit better ones. 13926 for (const Expr *Arg : Args) { 13927 if (!Arg->getType()->isFunctionType()) 13928 continue; 13929 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13930 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13931 if (FD && 13932 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13933 Arg->getExprLoc())) 13934 return ExprError(); 13935 } 13936 } 13937 13938 CandidateSet->NoteCandidates( 13939 PartialDiagnosticAt( 13940 Fn->getBeginLoc(), 13941 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13942 << ULE->getName() << Fn->getSourceRange()), 13943 SemaRef, OCD_AllCandidates, Args); 13944 break; 13945 } 13946 13947 case OR_Ambiguous: 13948 CandidateSet->NoteCandidates( 13949 PartialDiagnosticAt(Fn->getBeginLoc(), 13950 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13951 << ULE->getName() << Fn->getSourceRange()), 13952 SemaRef, OCD_AmbiguousCandidates, Args); 13953 break; 13954 13955 case OR_Deleted: { 13956 CandidateSet->NoteCandidates( 13957 PartialDiagnosticAt(Fn->getBeginLoc(), 13958 SemaRef.PDiag(diag::err_ovl_deleted_call) 13959 << ULE->getName() << Fn->getSourceRange()), 13960 SemaRef, OCD_AllCandidates, Args); 13961 13962 // We emitted an error for the unavailable/deleted function call but keep 13963 // the call in the AST. 13964 FunctionDecl *FDecl = (*Best)->Function; 13965 ExprResult Res = 13966 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13967 if (Res.isInvalid()) 13968 return ExprError(); 13969 return SemaRef.BuildResolvedCallExpr( 13970 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, 13971 /*IsExecConfig=*/false, (*Best)->IsADLCandidate); 13972 } 13973 } 13974 13975 // Overload resolution failed, try to recover. 13976 SmallVector<Expr *, 8> SubExprs = {Fn}; 13977 SubExprs.append(Args.begin(), Args.end()); 13978 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13979 chooseRecoveryType(*CandidateSet, Best)); 13980 } 13981 13982 static void markUnaddressableCandidatesUnviable(Sema &S, 13983 OverloadCandidateSet &CS) { 13984 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13985 if (I->Viable && 13986 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13987 I->Viable = false; 13988 I->FailureKind = ovl_fail_addr_not_available; 13989 } 13990 } 13991 } 13992 13993 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13994 /// (which eventually refers to the declaration Func) and the call 13995 /// arguments Args/NumArgs, attempt to resolve the function call down 13996 /// to a specific function. If overload resolution succeeds, returns 13997 /// the call expression produced by overload resolution. 13998 /// Otherwise, emits diagnostics and returns ExprError. 13999 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 14000 UnresolvedLookupExpr *ULE, 14001 SourceLocation LParenLoc, 14002 MultiExprArg Args, 14003 SourceLocation RParenLoc, 14004 Expr *ExecConfig, 14005 bool AllowTypoCorrection, 14006 bool CalleesAddressIsTaken) { 14007 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 14008 OverloadCandidateSet::CSK_Normal); 14009 ExprResult result; 14010 14011 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 14012 &result)) 14013 return result; 14014 14015 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 14016 // functions that aren't addressible are considered unviable. 14017 if (CalleesAddressIsTaken) 14018 markUnaddressableCandidatesUnviable(*this, CandidateSet); 14019 14020 OverloadCandidateSet::iterator Best; 14021 OverloadingResult OverloadResult = 14022 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 14023 14024 // Model the case with a call to a templated function whose definition 14025 // encloses the call and whose return type contains a placeholder type as if 14026 // the UnresolvedLookupExpr was type-dependent. 14027 if (OverloadResult == OR_Success) { 14028 const FunctionDecl *FDecl = Best->Function; 14029 if (FDecl && FDecl->isTemplateInstantiation() && 14030 FDecl->getReturnType()->isUndeducedType()) { 14031 if (const auto *TP = 14032 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false); 14033 TP && TP->willHaveBody()) { 14034 return CallExpr::Create(Context, Fn, Args, Context.DependentTy, 14035 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 14036 } 14037 } 14038 } 14039 14040 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 14041 ExecConfig, &CandidateSet, &Best, 14042 OverloadResult, AllowTypoCorrection); 14043 } 14044 14045 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 14046 return Functions.size() > 1 || 14047 (Functions.size() == 1 && 14048 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 14049 } 14050 14051 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 14052 NestedNameSpecifierLoc NNSLoc, 14053 DeclarationNameInfo DNI, 14054 const UnresolvedSetImpl &Fns, 14055 bool PerformADL) { 14056 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 14057 PerformADL, IsOverloaded(Fns), 14058 Fns.begin(), Fns.end()); 14059 } 14060 14061 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 14062 CXXConversionDecl *Method, 14063 bool HadMultipleCandidates) { 14064 // Convert the expression to match the conversion function's implicit object 14065 // parameter. 14066 ExprResult Exp; 14067 if (Method->isExplicitObjectMemberFunction()) 14068 Exp = InitializeExplicitObjectArgument(*this, E, Method); 14069 else 14070 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 14071 FoundDecl, Method); 14072 if (Exp.isInvalid()) 14073 return true; 14074 14075 if (Method->getParent()->isLambda() && 14076 Method->getConversionType()->isBlockPointerType()) { 14077 // This is a lambda conversion to block pointer; check if the argument 14078 // was a LambdaExpr. 14079 Expr *SubE = E; 14080 auto *CE = dyn_cast<CastExpr>(SubE); 14081 if (CE && CE->getCastKind() == CK_NoOp) 14082 SubE = CE->getSubExpr(); 14083 SubE = SubE->IgnoreParens(); 14084 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 14085 SubE = BE->getSubExpr(); 14086 if (isa<LambdaExpr>(SubE)) { 14087 // For the conversion to block pointer on a lambda expression, we 14088 // construct a special BlockLiteral instead; this doesn't really make 14089 // a difference in ARC, but outside of ARC the resulting block literal 14090 // follows the normal lifetime rules for block literals instead of being 14091 // autoreleased. 14092 PushExpressionEvaluationContext( 14093 ExpressionEvaluationContext::PotentiallyEvaluated); 14094 ExprResult BlockExp = BuildBlockForLambdaConversion( 14095 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 14096 PopExpressionEvaluationContext(); 14097 14098 // FIXME: This note should be produced by a CodeSynthesisContext. 14099 if (BlockExp.isInvalid()) 14100 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 14101 return BlockExp; 14102 } 14103 } 14104 CallExpr *CE; 14105 QualType ResultType = Method->getReturnType(); 14106 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14107 ResultType = ResultType.getNonLValueExprType(Context); 14108 if (Method->isExplicitObjectMemberFunction()) { 14109 ExprResult FnExpr = 14110 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(), 14111 HadMultipleCandidates, E->getBeginLoc()); 14112 if (FnExpr.isInvalid()) 14113 return ExprError(); 14114 Expr *ObjectParam = Exp.get(); 14115 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1), 14116 ResultType, VK, Exp.get()->getEndLoc(), 14117 CurFPFeatureOverrides()); 14118 } else { 14119 MemberExpr *ME = 14120 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 14121 NestedNameSpecifierLoc(), SourceLocation(), Method, 14122 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 14123 HadMultipleCandidates, DeclarationNameInfo(), 14124 Context.BoundMemberTy, VK_PRValue, OK_Ordinary); 14125 14126 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK, 14127 Exp.get()->getEndLoc(), 14128 CurFPFeatureOverrides()); 14129 } 14130 14131 if (CheckFunctionCall(Method, CE, 14132 Method->getType()->castAs<FunctionProtoType>())) 14133 return ExprError(); 14134 14135 return CheckForImmediateInvocation(CE, CE->getDirectCallee()); 14136 } 14137 14138 /// Create a unary operation that may resolve to an overloaded 14139 /// operator. 14140 /// 14141 /// \param OpLoc The location of the operator itself (e.g., '*'). 14142 /// 14143 /// \param Opc The UnaryOperatorKind that describes this operator. 14144 /// 14145 /// \param Fns The set of non-member functions that will be 14146 /// considered by overload resolution. The caller needs to build this 14147 /// set based on the context using, e.g., 14148 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 14149 /// set should not contain any member functions; those will be added 14150 /// by CreateOverloadedUnaryOp(). 14151 /// 14152 /// \param Input The input argument. 14153 ExprResult 14154 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 14155 const UnresolvedSetImpl &Fns, 14156 Expr *Input, bool PerformADL) { 14157 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 14158 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 14159 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14160 // TODO: provide better source location info. 14161 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 14162 14163 if (checkPlaceholderForOverload(*this, Input)) 14164 return ExprError(); 14165 14166 Expr *Args[2] = { Input, nullptr }; 14167 unsigned NumArgs = 1; 14168 14169 // For post-increment and post-decrement, add the implicit '0' as 14170 // the second argument, so that we know this is a post-increment or 14171 // post-decrement. 14172 if (Opc == UO_PostInc || Opc == UO_PostDec) { 14173 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 14174 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 14175 SourceLocation()); 14176 NumArgs = 2; 14177 } 14178 14179 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 14180 14181 if (Input->isTypeDependent()) { 14182 if (Fns.empty()) 14183 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 14184 VK_PRValue, OK_Ordinary, OpLoc, false, 14185 CurFPFeatureOverrides()); 14186 14187 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14188 ExprResult Fn = CreateUnresolvedLookupExpr( 14189 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 14190 if (Fn.isInvalid()) 14191 return ExprError(); 14192 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 14193 Context.DependentTy, VK_PRValue, OpLoc, 14194 CurFPFeatureOverrides()); 14195 } 14196 14197 // Build an empty overload set. 14198 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 14199 14200 // Add the candidates from the given function set. 14201 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 14202 14203 // Add operator candidates that are member functions. 14204 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 14205 14206 // Add candidates from ADL. 14207 if (PerformADL) { 14208 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 14209 /*ExplicitTemplateArgs*/nullptr, 14210 CandidateSet); 14211 } 14212 14213 // Add builtin operator candidates. 14214 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 14215 14216 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14217 14218 // Perform overload resolution. 14219 OverloadCandidateSet::iterator Best; 14220 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14221 case OR_Success: { 14222 // We found a built-in operator or an overloaded operator. 14223 FunctionDecl *FnDecl = Best->Function; 14224 14225 if (FnDecl) { 14226 Expr *Base = nullptr; 14227 // We matched an overloaded operator. Build a call to that 14228 // operator. 14229 14230 // Convert the arguments. 14231 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 14232 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl); 14233 14234 ExprResult InputInit; 14235 if (Method->isExplicitObjectMemberFunction()) 14236 InputInit = InitializeExplicitObjectArgument(*this, Input, Method); 14237 else 14238 InputInit = PerformImplicitObjectArgumentInitialization( 14239 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14240 if (InputInit.isInvalid()) 14241 return ExprError(); 14242 Base = Input = InputInit.get(); 14243 } else { 14244 // Convert the arguments. 14245 ExprResult InputInit 14246 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14247 Context, 14248 FnDecl->getParamDecl(0)), 14249 SourceLocation(), 14250 Input); 14251 if (InputInit.isInvalid()) 14252 return ExprError(); 14253 Input = InputInit.get(); 14254 } 14255 14256 // Build the actual expression node. 14257 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 14258 Base, HadMultipleCandidates, 14259 OpLoc); 14260 if (FnExpr.isInvalid()) 14261 return ExprError(); 14262 14263 // Determine the result type. 14264 QualType ResultTy = FnDecl->getReturnType(); 14265 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14266 ResultTy = ResultTy.getNonLValueExprType(Context); 14267 14268 Args[0] = Input; 14269 CallExpr *TheCall = CXXOperatorCallExpr::Create( 14270 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 14271 CurFPFeatureOverrides(), Best->IsADLCandidate); 14272 14273 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 14274 return ExprError(); 14275 14276 if (CheckFunctionCall(FnDecl, TheCall, 14277 FnDecl->getType()->castAs<FunctionProtoType>())) 14278 return ExprError(); 14279 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 14280 } else { 14281 // We matched a built-in operator. Convert the arguments, then 14282 // break out so that we will build the appropriate built-in 14283 // operator node. 14284 ExprResult InputRes = PerformImplicitConversion( 14285 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 14286 CCK_ForBuiltinOverloadedOp); 14287 if (InputRes.isInvalid()) 14288 return ExprError(); 14289 Input = InputRes.get(); 14290 break; 14291 } 14292 } 14293 14294 case OR_No_Viable_Function: 14295 // This is an erroneous use of an operator which can be overloaded by 14296 // a non-member function. Check for non-member operators which were 14297 // defined too late to be candidates. 14298 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 14299 // FIXME: Recover by calling the found function. 14300 return ExprError(); 14301 14302 // No viable function; fall through to handling this as a 14303 // built-in operator, which will produce an error message for us. 14304 break; 14305 14306 case OR_Ambiguous: 14307 CandidateSet.NoteCandidates( 14308 PartialDiagnosticAt(OpLoc, 14309 PDiag(diag::err_ovl_ambiguous_oper_unary) 14310 << UnaryOperator::getOpcodeStr(Opc) 14311 << Input->getType() << Input->getSourceRange()), 14312 *this, OCD_AmbiguousCandidates, ArgsArray, 14313 UnaryOperator::getOpcodeStr(Opc), OpLoc); 14314 return ExprError(); 14315 14316 case OR_Deleted: 14317 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the 14318 // object whose method was called. Later in NoteCandidates size of ArgsArray 14319 // is passed further and it eventually ends up compared to number of 14320 // function candidate parameters which never includes the object parameter, 14321 // so slice ArgsArray to make sure apples are compared to apples. 14322 CandidateSet.NoteCandidates( 14323 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14324 << UnaryOperator::getOpcodeStr(Opc) 14325 << Input->getSourceRange()), 14326 *this, OCD_AllCandidates, ArgsArray.drop_front(), 14327 UnaryOperator::getOpcodeStr(Opc), OpLoc); 14328 return ExprError(); 14329 } 14330 14331 // Either we found no viable overloaded operator or we matched a 14332 // built-in operator. In either case, fall through to trying to 14333 // build a built-in operation. 14334 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14335 } 14336 14337 /// Perform lookup for an overloaded binary operator. 14338 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 14339 OverloadedOperatorKind Op, 14340 const UnresolvedSetImpl &Fns, 14341 ArrayRef<Expr *> Args, bool PerformADL) { 14342 SourceLocation OpLoc = CandidateSet.getLocation(); 14343 14344 OverloadedOperatorKind ExtraOp = 14345 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 14346 ? getRewrittenOverloadedOperator(Op) 14347 : OO_None; 14348 14349 // Add the candidates from the given function set. This also adds the 14350 // rewritten candidates using these functions if necessary. 14351 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 14352 14353 // Add operator candidates that are member functions. 14354 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 14355 if (CandidateSet.getRewriteInfo().allowsReversed(Op)) 14356 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 14357 OverloadCandidateParamOrder::Reversed); 14358 14359 // In C++20, also add any rewritten member candidates. 14360 if (ExtraOp) { 14361 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 14362 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp)) 14363 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 14364 CandidateSet, 14365 OverloadCandidateParamOrder::Reversed); 14366 } 14367 14368 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 14369 // performed for an assignment operator (nor for operator[] nor operator->, 14370 // which don't get here). 14371 if (Op != OO_Equal && PerformADL) { 14372 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14373 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 14374 /*ExplicitTemplateArgs*/ nullptr, 14375 CandidateSet); 14376 if (ExtraOp) { 14377 DeclarationName ExtraOpName = 14378 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 14379 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 14380 /*ExplicitTemplateArgs*/ nullptr, 14381 CandidateSet); 14382 } 14383 } 14384 14385 // Add builtin operator candidates. 14386 // 14387 // FIXME: We don't add any rewritten candidates here. This is strictly 14388 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 14389 // resulting in our selecting a rewritten builtin candidate. For example: 14390 // 14391 // enum class E { e }; 14392 // bool operator!=(E, E) requires false; 14393 // bool k = E::e != E::e; 14394 // 14395 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 14396 // it seems unreasonable to consider rewritten builtin candidates. A core 14397 // issue has been filed proposing to removed this requirement. 14398 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 14399 } 14400 14401 /// Create a binary operation that may resolve to an overloaded 14402 /// operator. 14403 /// 14404 /// \param OpLoc The location of the operator itself (e.g., '+'). 14405 /// 14406 /// \param Opc The BinaryOperatorKind that describes this operator. 14407 /// 14408 /// \param Fns The set of non-member functions that will be 14409 /// considered by overload resolution. The caller needs to build this 14410 /// set based on the context using, e.g., 14411 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 14412 /// set should not contain any member functions; those will be added 14413 /// by CreateOverloadedBinOp(). 14414 /// 14415 /// \param LHS Left-hand argument. 14416 /// \param RHS Right-hand argument. 14417 /// \param PerformADL Whether to consider operator candidates found by ADL. 14418 /// \param AllowRewrittenCandidates Whether to consider candidates found by 14419 /// C++20 operator rewrites. 14420 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 14421 /// the function in question. Such a function is never a candidate in 14422 /// our overload resolution. This also enables synthesizing a three-way 14423 /// comparison from < and == as described in C++20 [class.spaceship]p1. 14424 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 14425 BinaryOperatorKind Opc, 14426 const UnresolvedSetImpl &Fns, Expr *LHS, 14427 Expr *RHS, bool PerformADL, 14428 bool AllowRewrittenCandidates, 14429 FunctionDecl *DefaultedFn) { 14430 Expr *Args[2] = { LHS, RHS }; 14431 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 14432 14433 if (!getLangOpts().CPlusPlus20) 14434 AllowRewrittenCandidates = false; 14435 14436 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 14437 14438 // If either side is type-dependent, create an appropriate dependent 14439 // expression. 14440 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 14441 if (Fns.empty()) { 14442 // If there are no functions to store, just build a dependent 14443 // BinaryOperator or CompoundAssignment. 14444 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14445 return CompoundAssignOperator::Create( 14446 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 14447 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 14448 Context.DependentTy); 14449 return BinaryOperator::Create( 14450 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 14451 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 14452 } 14453 14454 // FIXME: save results of ADL from here? 14455 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14456 // TODO: provide better source location info in DNLoc component. 14457 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14458 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 14459 ExprResult Fn = CreateUnresolvedLookupExpr( 14460 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 14461 if (Fn.isInvalid()) 14462 return ExprError(); 14463 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 14464 Context.DependentTy, VK_PRValue, OpLoc, 14465 CurFPFeatureOverrides()); 14466 } 14467 14468 // Always do placeholder-like conversions on the RHS. 14469 if (checkPlaceholderForOverload(*this, Args[1])) 14470 return ExprError(); 14471 14472 // Do placeholder-like conversion on the LHS; note that we should 14473 // not get here with a PseudoObject LHS. 14474 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 14475 if (checkPlaceholderForOverload(*this, Args[0])) 14476 return ExprError(); 14477 14478 // If this is the assignment operator, we only perform overload resolution 14479 // if the left-hand side is a class or enumeration type. This is actually 14480 // a hack. The standard requires that we do overload resolution between the 14481 // various built-in candidates, but as DR507 points out, this can lead to 14482 // problems. So we do it this way, which pretty much follows what GCC does. 14483 // Note that we go the traditional code path for compound assignment forms. 14484 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 14485 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14486 14487 // If this is the .* operator, which is not overloadable, just 14488 // create a built-in binary operator. 14489 if (Opc == BO_PtrMemD) 14490 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14491 14492 // Build the overload set. 14493 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator, 14494 OverloadCandidateSet::OperatorRewriteInfo( 14495 Op, OpLoc, AllowRewrittenCandidates)); 14496 if (DefaultedFn) 14497 CandidateSet.exclude(DefaultedFn); 14498 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 14499 14500 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14501 14502 // Perform overload resolution. 14503 OverloadCandidateSet::iterator Best; 14504 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14505 case OR_Success: { 14506 // We found a built-in operator or an overloaded operator. 14507 FunctionDecl *FnDecl = Best->Function; 14508 14509 bool IsReversed = Best->isReversed(); 14510 if (IsReversed) 14511 std::swap(Args[0], Args[1]); 14512 14513 if (FnDecl) { 14514 14515 if (FnDecl->isInvalidDecl()) 14516 return ExprError(); 14517 14518 Expr *Base = nullptr; 14519 // We matched an overloaded operator. Build a call to that 14520 // operator. 14521 14522 OverloadedOperatorKind ChosenOp = 14523 FnDecl->getDeclName().getCXXOverloadedOperator(); 14524 14525 // C++2a [over.match.oper]p9: 14526 // If a rewritten operator== candidate is selected by overload 14527 // resolution for an operator@, its return type shall be cv bool 14528 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 14529 !FnDecl->getReturnType()->isBooleanType()) { 14530 bool IsExtension = 14531 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 14532 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 14533 : diag::err_ovl_rewrite_equalequal_not_bool) 14534 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 14535 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14536 Diag(FnDecl->getLocation(), diag::note_declared_at); 14537 if (!IsExtension) 14538 return ExprError(); 14539 } 14540 14541 if (AllowRewrittenCandidates && !IsReversed && 14542 CandidateSet.getRewriteInfo().isReversible()) { 14543 // We could have reversed this operator, but didn't. Check if some 14544 // reversed form was a viable candidate, and if so, if it had a 14545 // better conversion for either parameter. If so, this call is 14546 // formally ambiguous, and allowing it is an extension. 14547 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 14548 for (OverloadCandidate &Cand : CandidateSet) { 14549 if (Cand.Viable && Cand.Function && Cand.isReversed() && 14550 allowAmbiguity(Context, Cand.Function, FnDecl)) { 14551 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 14552 if (CompareImplicitConversionSequences( 14553 *this, OpLoc, Cand.Conversions[ArgIdx], 14554 Best->Conversions[ArgIdx]) == 14555 ImplicitConversionSequence::Better) { 14556 AmbiguousWith.push_back(Cand.Function); 14557 break; 14558 } 14559 } 14560 } 14561 } 14562 14563 if (!AmbiguousWith.empty()) { 14564 bool AmbiguousWithSelf = 14565 AmbiguousWith.size() == 1 && 14566 declaresSameEntity(AmbiguousWith.front(), FnDecl); 14567 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 14568 << BinaryOperator::getOpcodeStr(Opc) 14569 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 14570 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14571 if (AmbiguousWithSelf) { 14572 Diag(FnDecl->getLocation(), 14573 diag::note_ovl_ambiguous_oper_binary_reversed_self); 14574 // Mark member== const or provide matching != to disallow reversed 14575 // args. Eg. 14576 // struct S { bool operator==(const S&); }; 14577 // S()==S(); 14578 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl)) 14579 if (Op == OverloadedOperatorKind::OO_EqualEqual && 14580 !MD->isConst() && 14581 !MD->hasCXXExplicitFunctionObjectParameter() && 14582 Context.hasSameUnqualifiedType( 14583 MD->getFunctionObjectParameterType(), 14584 MD->getParamDecl(0)->getType().getNonReferenceType()) && 14585 Context.hasSameUnqualifiedType( 14586 MD->getFunctionObjectParameterType(), 14587 Args[0]->getType()) && 14588 Context.hasSameUnqualifiedType( 14589 MD->getFunctionObjectParameterType(), 14590 Args[1]->getType())) 14591 Diag(FnDecl->getLocation(), 14592 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const); 14593 } else { 14594 Diag(FnDecl->getLocation(), 14595 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 14596 for (auto *F : AmbiguousWith) 14597 Diag(F->getLocation(), 14598 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 14599 } 14600 } 14601 } 14602 14603 // Convert the arguments. 14604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 14605 // Best->Access is only meaningful for class members. 14606 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 14607 14608 ExprResult Arg0, Arg1; 14609 unsigned ParamIdx = 0; 14610 if (Method->isExplicitObjectMemberFunction()) { 14611 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl); 14612 ParamIdx = 1; 14613 } else { 14614 Arg0 = PerformImplicitObjectArgumentInitialization( 14615 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14616 } 14617 Arg1 = PerformCopyInitialization( 14618 InitializedEntity::InitializeParameter( 14619 Context, FnDecl->getParamDecl(ParamIdx)), 14620 SourceLocation(), Args[1]); 14621 if (Arg0.isInvalid() || Arg1.isInvalid()) 14622 return ExprError(); 14623 14624 Base = Args[0] = Arg0.getAs<Expr>(); 14625 Args[1] = RHS = Arg1.getAs<Expr>(); 14626 } else { 14627 // Convert the arguments. 14628 ExprResult Arg0 = PerformCopyInitialization( 14629 InitializedEntity::InitializeParameter(Context, 14630 FnDecl->getParamDecl(0)), 14631 SourceLocation(), Args[0]); 14632 if (Arg0.isInvalid()) 14633 return ExprError(); 14634 14635 ExprResult Arg1 = 14636 PerformCopyInitialization( 14637 InitializedEntity::InitializeParameter(Context, 14638 FnDecl->getParamDecl(1)), 14639 SourceLocation(), Args[1]); 14640 if (Arg1.isInvalid()) 14641 return ExprError(); 14642 Args[0] = LHS = Arg0.getAs<Expr>(); 14643 Args[1] = RHS = Arg1.getAs<Expr>(); 14644 } 14645 14646 // Build the actual expression node. 14647 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14648 Best->FoundDecl, Base, 14649 HadMultipleCandidates, OpLoc); 14650 if (FnExpr.isInvalid()) 14651 return ExprError(); 14652 14653 // Determine the result type. 14654 QualType ResultTy = FnDecl->getReturnType(); 14655 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14656 ResultTy = ResultTy.getNonLValueExprType(Context); 14657 14658 CallExpr *TheCall; 14659 ArrayRef<const Expr *> ArgsArray(Args, 2); 14660 const Expr *ImplicitThis = nullptr; 14661 14662 // We always create a CXXOperatorCallExpr, even for explicit object 14663 // members; CodeGen should take care not to emit the this pointer. 14664 TheCall = CXXOperatorCallExpr::Create( 14665 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 14666 CurFPFeatureOverrides(), Best->IsADLCandidate); 14667 14668 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl); 14669 Method && Method->isImplicitObjectMemberFunction()) { 14670 // Cut off the implicit 'this'. 14671 ImplicitThis = ArgsArray[0]; 14672 ArgsArray = ArgsArray.slice(1); 14673 } 14674 14675 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 14676 FnDecl)) 14677 return ExprError(); 14678 14679 // Check for a self move. 14680 if (Op == OO_Equal) 14681 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 14682 14683 if (ImplicitThis) { 14684 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 14685 QualType ThisTypeFromDecl = Context.getPointerType( 14686 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType()); 14687 14688 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 14689 ThisTypeFromDecl); 14690 } 14691 14692 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 14693 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 14694 VariadicDoesNotApply); 14695 14696 ExprResult R = MaybeBindToTemporary(TheCall); 14697 if (R.isInvalid()) 14698 return ExprError(); 14699 14700 R = CheckForImmediateInvocation(R, FnDecl); 14701 if (R.isInvalid()) 14702 return ExprError(); 14703 14704 // For a rewritten candidate, we've already reversed the arguments 14705 // if needed. Perform the rest of the rewrite now. 14706 if ((Best->RewriteKind & CRK_DifferentOperator) || 14707 (Op == OO_Spaceship && IsReversed)) { 14708 if (Op == OO_ExclaimEqual) { 14709 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 14710 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 14711 } else { 14712 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 14713 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 14714 Expr *ZeroLiteral = 14715 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 14716 14717 Sema::CodeSynthesisContext Ctx; 14718 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 14719 Ctx.Entity = FnDecl; 14720 pushCodeSynthesisContext(Ctx); 14721 14722 R = CreateOverloadedBinOp( 14723 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 14724 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true, 14725 /*AllowRewrittenCandidates=*/false); 14726 14727 popCodeSynthesisContext(); 14728 } 14729 if (R.isInvalid()) 14730 return ExprError(); 14731 } else { 14732 assert(ChosenOp == Op && "unexpected operator name"); 14733 } 14734 14735 // Make a note in the AST if we did any rewriting. 14736 if (Best->RewriteKind != CRK_None) 14737 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 14738 14739 return R; 14740 } else { 14741 // We matched a built-in operator. Convert the arguments, then 14742 // break out so that we will build the appropriate built-in 14743 // operator node. 14744 ExprResult ArgsRes0 = PerformImplicitConversion( 14745 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14746 AA_Passing, CCK_ForBuiltinOverloadedOp); 14747 if (ArgsRes0.isInvalid()) 14748 return ExprError(); 14749 Args[0] = ArgsRes0.get(); 14750 14751 ExprResult ArgsRes1 = PerformImplicitConversion( 14752 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14753 AA_Passing, CCK_ForBuiltinOverloadedOp); 14754 if (ArgsRes1.isInvalid()) 14755 return ExprError(); 14756 Args[1] = ArgsRes1.get(); 14757 break; 14758 } 14759 } 14760 14761 case OR_No_Viable_Function: { 14762 // C++ [over.match.oper]p9: 14763 // If the operator is the operator , [...] and there are no 14764 // viable functions, then the operator is assumed to be the 14765 // built-in operator and interpreted according to clause 5. 14766 if (Opc == BO_Comma) 14767 break; 14768 14769 // When defaulting an 'operator<=>', we can try to synthesize a three-way 14770 // compare result using '==' and '<'. 14771 if (DefaultedFn && Opc == BO_Cmp) { 14772 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 14773 Args[1], DefaultedFn); 14774 if (E.isInvalid() || E.isUsable()) 14775 return E; 14776 } 14777 14778 // For class as left operand for assignment or compound assignment 14779 // operator do not fall through to handling in built-in, but report that 14780 // no overloaded assignment operator found 14781 ExprResult Result = ExprError(); 14782 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 14783 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 14784 Args, OpLoc); 14785 DeferDiagsRAII DDR(*this, 14786 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 14787 if (Args[0]->getType()->isRecordType() && 14788 Opc >= BO_Assign && Opc <= BO_OrAssign) { 14789 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14790 << BinaryOperator::getOpcodeStr(Opc) 14791 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14792 if (Args[0]->getType()->isIncompleteType()) { 14793 Diag(OpLoc, diag::note_assign_lhs_incomplete) 14794 << Args[0]->getType() 14795 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14796 } 14797 } else { 14798 // This is an erroneous use of an operator which can be overloaded by 14799 // a non-member function. Check for non-member operators which were 14800 // defined too late to be candidates. 14801 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 14802 // FIXME: Recover by calling the found function. 14803 return ExprError(); 14804 14805 // No viable function; try to create a built-in operation, which will 14806 // produce an error. Then, show the non-viable candidates. 14807 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14808 } 14809 assert(Result.isInvalid() && 14810 "C++ binary operator overloading is missing candidates!"); 14811 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 14812 return Result; 14813 } 14814 14815 case OR_Ambiguous: 14816 CandidateSet.NoteCandidates( 14817 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14818 << BinaryOperator::getOpcodeStr(Opc) 14819 << Args[0]->getType() 14820 << Args[1]->getType() 14821 << Args[0]->getSourceRange() 14822 << Args[1]->getSourceRange()), 14823 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14824 OpLoc); 14825 return ExprError(); 14826 14827 case OR_Deleted: 14828 if (isImplicitlyDeleted(Best->Function)) { 14829 FunctionDecl *DeletedFD = Best->Function; 14830 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 14831 if (DFK.isSpecialMember()) { 14832 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 14833 << Args[0]->getType() << DFK.asSpecialMember(); 14834 } else { 14835 assert(DFK.isComparison()); 14836 Diag(OpLoc, diag::err_ovl_deleted_comparison) 14837 << Args[0]->getType() << DeletedFD; 14838 } 14839 14840 // The user probably meant to call this special member. Just 14841 // explain why it's deleted. 14842 NoteDeletedFunction(DeletedFD); 14843 return ExprError(); 14844 } 14845 CandidateSet.NoteCandidates( 14846 PartialDiagnosticAt( 14847 OpLoc, PDiag(diag::err_ovl_deleted_oper) 14848 << getOperatorSpelling(Best->Function->getDeclName() 14849 .getCXXOverloadedOperator()) 14850 << Args[0]->getSourceRange() 14851 << Args[1]->getSourceRange()), 14852 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14853 OpLoc); 14854 return ExprError(); 14855 } 14856 14857 // We matched a built-in operator; build it. 14858 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14859 } 14860 14861 ExprResult Sema::BuildSynthesizedThreeWayComparison( 14862 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 14863 FunctionDecl *DefaultedFn) { 14864 const ComparisonCategoryInfo *Info = 14865 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 14866 // If we're not producing a known comparison category type, we can't 14867 // synthesize a three-way comparison. Let the caller diagnose this. 14868 if (!Info) 14869 return ExprResult((Expr*)nullptr); 14870 14871 // If we ever want to perform this synthesis more generally, we will need to 14872 // apply the temporary materialization conversion to the operands. 14873 assert(LHS->isGLValue() && RHS->isGLValue() && 14874 "cannot use prvalue expressions more than once"); 14875 Expr *OrigLHS = LHS; 14876 Expr *OrigRHS = RHS; 14877 14878 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 14879 // each of them multiple times below. 14880 LHS = new (Context) 14881 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 14882 LHS->getObjectKind(), LHS); 14883 RHS = new (Context) 14884 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 14885 RHS->getObjectKind(), RHS); 14886 14887 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 14888 DefaultedFn); 14889 if (Eq.isInvalid()) 14890 return ExprError(); 14891 14892 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 14893 true, DefaultedFn); 14894 if (Less.isInvalid()) 14895 return ExprError(); 14896 14897 ExprResult Greater; 14898 if (Info->isPartial()) { 14899 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14900 DefaultedFn); 14901 if (Greater.isInvalid()) 14902 return ExprError(); 14903 } 14904 14905 // Form the list of comparisons we're going to perform. 14906 struct Comparison { 14907 ExprResult Cmp; 14908 ComparisonCategoryResult Result; 14909 } Comparisons[4] = 14910 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14911 : ComparisonCategoryResult::Equivalent}, 14912 {Less, ComparisonCategoryResult::Less}, 14913 {Greater, ComparisonCategoryResult::Greater}, 14914 {ExprResult(), ComparisonCategoryResult::Unordered}, 14915 }; 14916 14917 int I = Info->isPartial() ? 3 : 2; 14918 14919 // Combine the comparisons with suitable conditional expressions. 14920 ExprResult Result; 14921 for (; I >= 0; --I) { 14922 // Build a reference to the comparison category constant. 14923 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14924 // FIXME: Missing a constant for a comparison category. Diagnose this? 14925 if (!VI) 14926 return ExprResult((Expr*)nullptr); 14927 ExprResult ThisResult = 14928 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14929 if (ThisResult.isInvalid()) 14930 return ExprError(); 14931 14932 // Build a conditional unless this is the final case. 14933 if (Result.get()) { 14934 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14935 ThisResult.get(), Result.get()); 14936 if (Result.isInvalid()) 14937 return ExprError(); 14938 } else { 14939 Result = ThisResult; 14940 } 14941 } 14942 14943 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14944 // bind the OpaqueValueExprs before they're (repeatedly) used. 14945 Expr *SyntacticForm = BinaryOperator::Create( 14946 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14947 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14948 CurFPFeatureOverrides()); 14949 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14950 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14951 } 14952 14953 static bool PrepareArgumentsForCallToObjectOfClassType( 14954 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 14955 MultiExprArg Args, SourceLocation LParenLoc) { 14956 14957 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14958 unsigned NumParams = Proto->getNumParams(); 14959 unsigned NumArgsSlots = 14960 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 14961 // Build the full argument list for the method call (the implicit object 14962 // parameter is placed at the beginning of the list). 14963 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 14964 bool IsError = false; 14965 // Initialize the implicit object parameter. 14966 // Check the argument types. 14967 for (unsigned i = 0; i != NumParams; i++) { 14968 Expr *Arg; 14969 if (i < Args.size()) { 14970 Arg = Args[i]; 14971 ExprResult InputInit = 14972 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 14973 S.Context, Method->getParamDecl(i)), 14974 SourceLocation(), Arg); 14975 IsError |= InputInit.isInvalid(); 14976 Arg = InputInit.getAs<Expr>(); 14977 } else { 14978 ExprResult DefArg = 14979 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14980 if (DefArg.isInvalid()) { 14981 IsError = true; 14982 break; 14983 } 14984 Arg = DefArg.getAs<Expr>(); 14985 } 14986 14987 MethodArgs.push_back(Arg); 14988 } 14989 return IsError; 14990 } 14991 14992 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14993 SourceLocation RLoc, 14994 Expr *Base, 14995 MultiExprArg ArgExpr) { 14996 SmallVector<Expr *, 2> Args; 14997 Args.push_back(Base); 14998 for (auto *e : ArgExpr) { 14999 Args.push_back(e); 15000 } 15001 DeclarationName OpName = 15002 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 15003 15004 SourceRange Range = ArgExpr.empty() 15005 ? SourceRange{} 15006 : SourceRange(ArgExpr.front()->getBeginLoc(), 15007 ArgExpr.back()->getEndLoc()); 15008 15009 // If either side is type-dependent, create an appropriate dependent 15010 // expression. 15011 if (Expr::hasAnyTypeDependentArguments(Args)) { 15012 15013 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 15014 // CHECKME: no 'operator' keyword? 15015 DeclarationNameInfo OpNameInfo(OpName, LLoc); 15016 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 15017 ExprResult Fn = CreateUnresolvedLookupExpr( 15018 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 15019 if (Fn.isInvalid()) 15020 return ExprError(); 15021 // Can't add any actual overloads yet 15022 15023 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 15024 Context.DependentTy, VK_PRValue, RLoc, 15025 CurFPFeatureOverrides()); 15026 } 15027 15028 // Handle placeholders 15029 UnbridgedCastsSet UnbridgedCasts; 15030 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 15031 return ExprError(); 15032 } 15033 // Build an empty overload set. 15034 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 15035 15036 // Subscript can only be overloaded as a member function. 15037 15038 // Add operator candidates that are member functions. 15039 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 15040 15041 // Add builtin operator candidates. 15042 if (Args.size() == 2) 15043 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 15044 15045 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15046 15047 // Perform overload resolution. 15048 OverloadCandidateSet::iterator Best; 15049 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 15050 case OR_Success: { 15051 // We found a built-in operator or an overloaded operator. 15052 FunctionDecl *FnDecl = Best->Function; 15053 15054 if (FnDecl) { 15055 // We matched an overloaded operator. Build a call to that 15056 // operator. 15057 15058 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 15059 15060 // Convert the arguments. 15061 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 15062 SmallVector<Expr *, 2> MethodArgs; 15063 15064 // Handle 'this' parameter if the selected function is not static. 15065 if (Method->isExplicitObjectMemberFunction()) { 15066 ExprResult Res = 15067 InitializeExplicitObjectArgument(*this, Args[0], Method); 15068 if (Res.isInvalid()) 15069 return ExprError(); 15070 Args[0] = Res.get(); 15071 ArgExpr = Args; 15072 } else if (Method->isInstance()) { 15073 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization( 15074 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15075 if (Arg0.isInvalid()) 15076 return ExprError(); 15077 15078 MethodArgs.push_back(Arg0.get()); 15079 } 15080 15081 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 15082 *this, MethodArgs, Method, ArgExpr, LLoc); 15083 if (IsError) 15084 return ExprError(); 15085 15086 // Build the actual expression node. 15087 DeclarationNameInfo OpLocInfo(OpName, LLoc); 15088 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 15089 ExprResult FnExpr = CreateFunctionRefExpr( 15090 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 15091 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 15092 if (FnExpr.isInvalid()) 15093 return ExprError(); 15094 15095 // Determine the result type 15096 QualType ResultTy = FnDecl->getReturnType(); 15097 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15098 ResultTy = ResultTy.getNonLValueExprType(Context); 15099 15100 CallExpr *TheCall; 15101 if (Method->isInstance()) 15102 TheCall = CXXOperatorCallExpr::Create( 15103 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, 15104 RLoc, CurFPFeatureOverrides()); 15105 else 15106 TheCall = 15107 CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK, 15108 RLoc, CurFPFeatureOverrides()); 15109 15110 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 15111 return ExprError(); 15112 15113 if (CheckFunctionCall(Method, TheCall, 15114 Method->getType()->castAs<FunctionProtoType>())) 15115 return ExprError(); 15116 15117 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 15118 FnDecl); 15119 } else { 15120 // We matched a built-in operator. Convert the arguments, then 15121 // break out so that we will build the appropriate built-in 15122 // operator node. 15123 ExprResult ArgsRes0 = PerformImplicitConversion( 15124 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 15125 AA_Passing, CCK_ForBuiltinOverloadedOp); 15126 if (ArgsRes0.isInvalid()) 15127 return ExprError(); 15128 Args[0] = ArgsRes0.get(); 15129 15130 ExprResult ArgsRes1 = PerformImplicitConversion( 15131 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 15132 AA_Passing, CCK_ForBuiltinOverloadedOp); 15133 if (ArgsRes1.isInvalid()) 15134 return ExprError(); 15135 Args[1] = ArgsRes1.get(); 15136 15137 break; 15138 } 15139 } 15140 15141 case OR_No_Viable_Function: { 15142 PartialDiagnostic PD = 15143 CandidateSet.empty() 15144 ? (PDiag(diag::err_ovl_no_oper) 15145 << Args[0]->getType() << /*subscript*/ 0 15146 << Args[0]->getSourceRange() << Range) 15147 : (PDiag(diag::err_ovl_no_viable_subscript) 15148 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 15149 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 15150 OCD_AllCandidates, ArgExpr, "[]", LLoc); 15151 return ExprError(); 15152 } 15153 15154 case OR_Ambiguous: 15155 if (Args.size() == 2) { 15156 CandidateSet.NoteCandidates( 15157 PartialDiagnosticAt( 15158 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 15159 << "[]" << Args[0]->getType() << Args[1]->getType() 15160 << Args[0]->getSourceRange() << Range), 15161 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 15162 } else { 15163 CandidateSet.NoteCandidates( 15164 PartialDiagnosticAt(LLoc, 15165 PDiag(diag::err_ovl_ambiguous_subscript_call) 15166 << Args[0]->getType() 15167 << Args[0]->getSourceRange() << Range), 15168 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 15169 } 15170 return ExprError(); 15171 15172 case OR_Deleted: 15173 CandidateSet.NoteCandidates( 15174 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 15175 << "[]" << Args[0]->getSourceRange() 15176 << Range), 15177 *this, OCD_AllCandidates, Args, "[]", LLoc); 15178 return ExprError(); 15179 } 15180 15181 // We matched a built-in operator; build it. 15182 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 15183 } 15184 15185 /// BuildCallToMemberFunction - Build a call to a member 15186 /// function. MemExpr is the expression that refers to the member 15187 /// function (and includes the object parameter), Args/NumArgs are the 15188 /// arguments to the function call (not including the object 15189 /// parameter). The caller needs to validate that the member 15190 /// expression refers to a non-static member function or an overloaded 15191 /// member function. 15192 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 15193 SourceLocation LParenLoc, 15194 MultiExprArg Args, 15195 SourceLocation RParenLoc, 15196 Expr *ExecConfig, bool IsExecConfig, 15197 bool AllowRecovery) { 15198 assert(MemExprE->getType() == Context.BoundMemberTy || 15199 MemExprE->getType() == Context.OverloadTy); 15200 15201 // Dig out the member expression. This holds both the object 15202 // argument and the member function we're referring to. 15203 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 15204 15205 // Determine whether this is a call to a pointer-to-member function. 15206 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 15207 assert(op->getType() == Context.BoundMemberTy); 15208 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 15209 15210 QualType fnType = 15211 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 15212 15213 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 15214 QualType resultType = proto->getCallResultType(Context); 15215 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 15216 15217 // Check that the object type isn't more qualified than the 15218 // member function we're calling. 15219 Qualifiers funcQuals = proto->getMethodQuals(); 15220 15221 QualType objectType = op->getLHS()->getType(); 15222 if (op->getOpcode() == BO_PtrMemI) 15223 objectType = objectType->castAs<PointerType>()->getPointeeType(); 15224 Qualifiers objectQuals = objectType.getQualifiers(); 15225 15226 Qualifiers difference = objectQuals - funcQuals; 15227 difference.removeObjCGCAttr(); 15228 difference.removeAddressSpace(); 15229 if (difference) { 15230 std::string qualsString = difference.getAsString(); 15231 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 15232 << fnType.getUnqualifiedType() 15233 << qualsString 15234 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 15235 } 15236 15237 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 15238 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 15239 CurFPFeatureOverrides(), proto->getNumParams()); 15240 15241 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 15242 call, nullptr)) 15243 return ExprError(); 15244 15245 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 15246 return ExprError(); 15247 15248 if (CheckOtherCall(call, proto)) 15249 return ExprError(); 15250 15251 return MaybeBindToTemporary(call); 15252 } 15253 15254 // We only try to build a recovery expr at this level if we can preserve 15255 // the return type, otherwise we return ExprError() and let the caller 15256 // recover. 15257 auto BuildRecoveryExpr = [&](QualType Type) { 15258 if (!AllowRecovery) 15259 return ExprError(); 15260 std::vector<Expr *> SubExprs = {MemExprE}; 15261 llvm::append_range(SubExprs, Args); 15262 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 15263 Type); 15264 }; 15265 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 15266 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 15267 RParenLoc, CurFPFeatureOverrides()); 15268 15269 UnbridgedCastsSet UnbridgedCasts; 15270 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 15271 return ExprError(); 15272 15273 MemberExpr *MemExpr; 15274 CXXMethodDecl *Method = nullptr; 15275 bool HadMultipleCandidates = false; 15276 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 15277 NestedNameSpecifier *Qualifier = nullptr; 15278 if (isa<MemberExpr>(NakedMemExpr)) { 15279 MemExpr = cast<MemberExpr>(NakedMemExpr); 15280 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 15281 FoundDecl = MemExpr->getFoundDecl(); 15282 Qualifier = MemExpr->getQualifier(); 15283 UnbridgedCasts.restore(); 15284 } else { 15285 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 15286 Qualifier = UnresExpr->getQualifier(); 15287 15288 QualType ObjectType = UnresExpr->getBaseType(); 15289 Expr::Classification ObjectClassification 15290 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 15291 : UnresExpr->getBase()->Classify(Context); 15292 15293 // Add overload candidates 15294 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 15295 OverloadCandidateSet::CSK_Normal); 15296 15297 // FIXME: avoid copy. 15298 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15299 if (UnresExpr->hasExplicitTemplateArgs()) { 15300 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15301 TemplateArgs = &TemplateArgsBuffer; 15302 } 15303 15304 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 15305 E = UnresExpr->decls_end(); I != E; ++I) { 15306 15307 QualType ExplicitObjectType = ObjectType; 15308 15309 NamedDecl *Func = *I; 15310 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 15311 if (isa<UsingShadowDecl>(Func)) 15312 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 15313 15314 bool HasExplicitParameter = false; 15315 if (const auto *M = dyn_cast<FunctionDecl>(Func); 15316 M && M->hasCXXExplicitFunctionObjectParameter()) 15317 HasExplicitParameter = true; 15318 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func); 15319 M && 15320 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter()) 15321 HasExplicitParameter = true; 15322 15323 if (HasExplicitParameter) 15324 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr); 15325 15326 // Microsoft supports direct constructor calls. 15327 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 15328 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 15329 CandidateSet, 15330 /*SuppressUserConversions*/ false); 15331 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 15332 // If explicit template arguments were provided, we can't call a 15333 // non-template member function. 15334 if (TemplateArgs) 15335 continue; 15336 15337 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType, 15338 ObjectClassification, Args, CandidateSet, 15339 /*SuppressUserConversions=*/false); 15340 } else { 15341 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 15342 I.getPair(), ActingDC, TemplateArgs, 15343 ExplicitObjectType, ObjectClassification, 15344 Args, CandidateSet, 15345 /*SuppressUserConversions=*/false); 15346 } 15347 } 15348 15349 HadMultipleCandidates = (CandidateSet.size() > 1); 15350 15351 DeclarationName DeclName = UnresExpr->getMemberName(); 15352 15353 UnbridgedCasts.restore(); 15354 15355 OverloadCandidateSet::iterator Best; 15356 bool Succeeded = false; 15357 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 15358 Best)) { 15359 case OR_Success: 15360 Method = cast<CXXMethodDecl>(Best->Function); 15361 FoundDecl = Best->FoundDecl; 15362 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 15363 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 15364 break; 15365 // If FoundDecl is different from Method (such as if one is a template 15366 // and the other a specialization), make sure DiagnoseUseOfDecl is 15367 // called on both. 15368 // FIXME: This would be more comprehensively addressed by modifying 15369 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 15370 // being used. 15371 if (Method != FoundDecl.getDecl() && 15372 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc())) 15373 break; 15374 Succeeded = true; 15375 break; 15376 15377 case OR_No_Viable_Function: 15378 CandidateSet.NoteCandidates( 15379 PartialDiagnosticAt( 15380 UnresExpr->getMemberLoc(), 15381 PDiag(diag::err_ovl_no_viable_member_function_in_call) 15382 << DeclName << MemExprE->getSourceRange()), 15383 *this, OCD_AllCandidates, Args); 15384 break; 15385 case OR_Ambiguous: 15386 CandidateSet.NoteCandidates( 15387 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 15388 PDiag(diag::err_ovl_ambiguous_member_call) 15389 << DeclName << MemExprE->getSourceRange()), 15390 *this, OCD_AmbiguousCandidates, Args); 15391 break; 15392 case OR_Deleted: 15393 CandidateSet.NoteCandidates( 15394 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 15395 PDiag(diag::err_ovl_deleted_member_call) 15396 << DeclName << MemExprE->getSourceRange()), 15397 *this, OCD_AllCandidates, Args); 15398 break; 15399 } 15400 // Overload resolution fails, try to recover. 15401 if (!Succeeded) 15402 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 15403 15404 ExprResult Res = 15405 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 15406 if (Res.isInvalid()) 15407 return ExprError(); 15408 MemExprE = Res.get(); 15409 15410 // If overload resolution picked a static member 15411 // build a non-member call based on that function. 15412 if (Method->isStatic()) { 15413 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 15414 ExecConfig, IsExecConfig); 15415 } 15416 15417 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 15418 } 15419 15420 QualType ResultType = Method->getReturnType(); 15421 ExprValueKind VK = Expr::getValueKindForType(ResultType); 15422 ResultType = ResultType.getNonLValueExprType(Context); 15423 15424 assert(Method && "Member call to something that isn't a method?"); 15425 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15426 15427 CallExpr *TheCall = nullptr; 15428 llvm::SmallVector<Expr *, 8> NewArgs; 15429 if (Method->isExplicitObjectMemberFunction()) { 15430 PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args, 15431 NewArgs); 15432 // Build the actual expression node. 15433 ExprResult FnExpr = 15434 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr, 15435 HadMultipleCandidates, MemExpr->getExprLoc()); 15436 if (FnExpr.isInvalid()) 15437 return ExprError(); 15438 15439 TheCall = 15440 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc, 15441 CurFPFeatureOverrides(), Proto->getNumParams()); 15442 } else { 15443 // Convert the object argument (for a non-static member function call). 15444 // We only need to do this if there was actually an overload; otherwise 15445 // it was done at lookup. 15446 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization( 15447 MemExpr->getBase(), Qualifier, FoundDecl, Method); 15448 if (ObjectArg.isInvalid()) 15449 return ExprError(); 15450 MemExpr->setBase(ObjectArg.get()); 15451 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 15452 RParenLoc, CurFPFeatureOverrides(), 15453 Proto->getNumParams()); 15454 } 15455 15456 // Check for a valid return type. 15457 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 15458 TheCall, Method)) 15459 return BuildRecoveryExpr(ResultType); 15460 15461 // Convert the rest of the arguments 15462 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 15463 RParenLoc)) 15464 return BuildRecoveryExpr(ResultType); 15465 15466 DiagnoseSentinelCalls(Method, LParenLoc, Args); 15467 15468 if (CheckFunctionCall(Method, TheCall, Proto)) 15469 return ExprError(); 15470 15471 // In the case the method to call was not selected by the overloading 15472 // resolution process, we still need to handle the enable_if attribute. Do 15473 // that here, so it will not hide previous -- and more relevant -- errors. 15474 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 15475 if (const EnableIfAttr *Attr = 15476 CheckEnableIf(Method, LParenLoc, Args, true)) { 15477 Diag(MemE->getMemberLoc(), 15478 diag::err_ovl_no_viable_member_function_in_call) 15479 << Method << Method->getSourceRange(); 15480 Diag(Method->getLocation(), 15481 diag::note_ovl_candidate_disabled_by_function_cond_attr) 15482 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 15483 return ExprError(); 15484 } 15485 } 15486 15487 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) && 15488 TheCall->getDirectCallee()->isPureVirtual()) { 15489 const FunctionDecl *MD = TheCall->getDirectCallee(); 15490 15491 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 15492 MemExpr->performsVirtualDispatch(getLangOpts())) { 15493 Diag(MemExpr->getBeginLoc(), 15494 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 15495 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 15496 << MD->getParent(); 15497 15498 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 15499 if (getLangOpts().AppleKext) 15500 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 15501 << MD->getParent() << MD->getDeclName(); 15502 } 15503 } 15504 15505 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) { 15506 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 15507 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 15508 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 15509 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 15510 MemExpr->getMemberLoc()); 15511 } 15512 15513 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 15514 TheCall->getDirectCallee()); 15515 } 15516 15517 /// BuildCallToObjectOfClassType - Build a call to an object of class 15518 /// type (C++ [over.call.object]), which can end up invoking an 15519 /// overloaded function call operator (@c operator()) or performing a 15520 /// user-defined conversion on the object argument. 15521 ExprResult 15522 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 15523 SourceLocation LParenLoc, 15524 MultiExprArg Args, 15525 SourceLocation RParenLoc) { 15526 if (checkPlaceholderForOverload(*this, Obj)) 15527 return ExprError(); 15528 ExprResult Object = Obj; 15529 15530 UnbridgedCastsSet UnbridgedCasts; 15531 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 15532 return ExprError(); 15533 15534 assert(Object.get()->getType()->isRecordType() && 15535 "Requires object type argument"); 15536 15537 // C++ [over.call.object]p1: 15538 // If the primary-expression E in the function call syntax 15539 // evaluates to a class object of type "cv T", then the set of 15540 // candidate functions includes at least the function call 15541 // operators of T. The function call operators of T are obtained by 15542 // ordinary lookup of the name operator() in the context of 15543 // (E).operator(). 15544 OverloadCandidateSet CandidateSet(LParenLoc, 15545 OverloadCandidateSet::CSK_Operator); 15546 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 15547 15548 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 15549 diag::err_incomplete_object_call, Object.get())) 15550 return true; 15551 15552 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 15553 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 15554 LookupQualifiedName(R, Record->getDecl()); 15555 R.suppressAccessDiagnostics(); 15556 15557 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 15558 Oper != OperEnd; ++Oper) { 15559 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 15560 Object.get()->Classify(Context), Args, CandidateSet, 15561 /*SuppressUserConversion=*/false); 15562 } 15563 15564 // When calling a lambda, both the call operator, and 15565 // the conversion operator to function pointer 15566 // are considered. But when constraint checking 15567 // on the call operator fails, it will also fail on the 15568 // conversion operator as the constraints are always the same. 15569 // As the user probably does not intend to perform a surrogate call, 15570 // we filter them out to produce better error diagnostics, ie to avoid 15571 // showing 2 failed overloads instead of one. 15572 bool IgnoreSurrogateFunctions = false; 15573 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) { 15574 const OverloadCandidate &Candidate = *CandidateSet.begin(); 15575 if (!Candidate.Viable && 15576 Candidate.FailureKind == ovl_fail_constraints_not_satisfied) 15577 IgnoreSurrogateFunctions = true; 15578 } 15579 15580 // C++ [over.call.object]p2: 15581 // In addition, for each (non-explicit in C++0x) conversion function 15582 // declared in T of the form 15583 // 15584 // operator conversion-type-id () cv-qualifier; 15585 // 15586 // where cv-qualifier is the same cv-qualification as, or a 15587 // greater cv-qualification than, cv, and where conversion-type-id 15588 // denotes the type "pointer to function of (P1,...,Pn) returning 15589 // R", or the type "reference to pointer to function of 15590 // (P1,...,Pn) returning R", or the type "reference to function 15591 // of (P1,...,Pn) returning R", a surrogate call function [...] 15592 // is also considered as a candidate function. Similarly, 15593 // surrogate call functions are added to the set of candidate 15594 // functions for each conversion function declared in an 15595 // accessible base class provided the function is not hidden 15596 // within T by another intervening declaration. 15597 const auto &Conversions = 15598 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 15599 for (auto I = Conversions.begin(), E = Conversions.end(); 15600 !IgnoreSurrogateFunctions && I != E; ++I) { 15601 NamedDecl *D = *I; 15602 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 15603 if (isa<UsingShadowDecl>(D)) 15604 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 15605 15606 // Skip over templated conversion functions; they aren't 15607 // surrogates. 15608 if (isa<FunctionTemplateDecl>(D)) 15609 continue; 15610 15611 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 15612 if (!Conv->isExplicit()) { 15613 // Strip the reference type (if any) and then the pointer type (if 15614 // any) to get down to what might be a function type. 15615 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 15616 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 15617 ConvType = ConvPtrType->getPointeeType(); 15618 15619 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 15620 { 15621 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 15622 Object.get(), Args, CandidateSet); 15623 } 15624 } 15625 } 15626 15627 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15628 15629 // Perform overload resolution. 15630 OverloadCandidateSet::iterator Best; 15631 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 15632 Best)) { 15633 case OR_Success: 15634 // Overload resolution succeeded; we'll build the appropriate call 15635 // below. 15636 break; 15637 15638 case OR_No_Viable_Function: { 15639 PartialDiagnostic PD = 15640 CandidateSet.empty() 15641 ? (PDiag(diag::err_ovl_no_oper) 15642 << Object.get()->getType() << /*call*/ 1 15643 << Object.get()->getSourceRange()) 15644 : (PDiag(diag::err_ovl_no_viable_object_call) 15645 << Object.get()->getType() << Object.get()->getSourceRange()); 15646 CandidateSet.NoteCandidates( 15647 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 15648 OCD_AllCandidates, Args); 15649 break; 15650 } 15651 case OR_Ambiguous: 15652 if (!R.isAmbiguous()) 15653 CandidateSet.NoteCandidates( 15654 PartialDiagnosticAt(Object.get()->getBeginLoc(), 15655 PDiag(diag::err_ovl_ambiguous_object_call) 15656 << Object.get()->getType() 15657 << Object.get()->getSourceRange()), 15658 *this, OCD_AmbiguousCandidates, Args); 15659 break; 15660 15661 case OR_Deleted: 15662 CandidateSet.NoteCandidates( 15663 PartialDiagnosticAt(Object.get()->getBeginLoc(), 15664 PDiag(diag::err_ovl_deleted_object_call) 15665 << Object.get()->getType() 15666 << Object.get()->getSourceRange()), 15667 *this, OCD_AllCandidates, Args); 15668 break; 15669 } 15670 15671 if (Best == CandidateSet.end()) 15672 return true; 15673 15674 UnbridgedCasts.restore(); 15675 15676 if (Best->Function == nullptr) { 15677 // Since there is no function declaration, this is one of the 15678 // surrogate candidates. Dig out the conversion function. 15679 CXXConversionDecl *Conv 15680 = cast<CXXConversionDecl>( 15681 Best->Conversions[0].UserDefined.ConversionFunction); 15682 15683 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 15684 Best->FoundDecl); 15685 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 15686 return ExprError(); 15687 assert(Conv == Best->FoundDecl.getDecl() && 15688 "Found Decl & conversion-to-functionptr should be same, right?!"); 15689 // We selected one of the surrogate functions that converts the 15690 // object parameter to a function pointer. Perform the conversion 15691 // on the object argument, then let BuildCallExpr finish the job. 15692 15693 // Create an implicit member expr to refer to the conversion operator. 15694 // and then call it. 15695 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 15696 Conv, HadMultipleCandidates); 15697 if (Call.isInvalid()) 15698 return ExprError(); 15699 // Record usage of conversion in an implicit cast. 15700 Call = ImplicitCastExpr::Create( 15701 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 15702 nullptr, VK_PRValue, CurFPFeatureOverrides()); 15703 15704 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 15705 } 15706 15707 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 15708 15709 // We found an overloaded operator(). Build a CXXOperatorCallExpr 15710 // that calls this method, using Object for the implicit object 15711 // parameter and passing along the remaining arguments. 15712 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15713 15714 // An error diagnostic has already been printed when parsing the declaration. 15715 if (Method->isInvalidDecl()) 15716 return ExprError(); 15717 15718 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15719 unsigned NumParams = Proto->getNumParams(); 15720 15721 DeclarationNameInfo OpLocInfo( 15722 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 15723 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 15724 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15725 Obj, HadMultipleCandidates, 15726 OpLocInfo.getLoc(), 15727 OpLocInfo.getInfo()); 15728 if (NewFn.isInvalid()) 15729 return true; 15730 15731 SmallVector<Expr *, 8> MethodArgs; 15732 MethodArgs.reserve(NumParams + 1); 15733 15734 bool IsError = false; 15735 15736 // Initialize the implicit object parameter if needed. 15737 // Since C++23, this could also be a call to a static call operator 15738 // which we emit as a regular CallExpr. 15739 llvm::SmallVector<Expr *, 8> NewArgs; 15740 if (Method->isExplicitObjectMemberFunction()) { 15741 // FIXME: we should do that during the definition of the lambda when we can. 15742 DiagnoseInvalidExplicitObjectParameterInLambda(Method); 15743 PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs); 15744 } else if (Method->isInstance()) { 15745 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization( 15746 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15747 if (ObjRes.isInvalid()) 15748 IsError = true; 15749 else 15750 Object = ObjRes; 15751 MethodArgs.push_back(Object.get()); 15752 } 15753 15754 IsError |= PrepareArgumentsForCallToObjectOfClassType( 15755 *this, MethodArgs, Method, Args, LParenLoc); 15756 15757 // If this is a variadic call, handle args passed through "...". 15758 if (Proto->isVariadic()) { 15759 // Promote the arguments (C99 6.5.2.2p7). 15760 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 15761 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 15762 nullptr); 15763 IsError |= Arg.isInvalid(); 15764 MethodArgs.push_back(Arg.get()); 15765 } 15766 } 15767 15768 if (IsError) 15769 return true; 15770 15771 DiagnoseSentinelCalls(Method, LParenLoc, Args); 15772 15773 // Once we've built TheCall, all of the expressions are properly owned. 15774 QualType ResultTy = Method->getReturnType(); 15775 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15776 ResultTy = ResultTy.getNonLValueExprType(Context); 15777 15778 CallExpr *TheCall; 15779 if (Method->isInstance()) 15780 TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), 15781 MethodArgs, ResultTy, VK, RParenLoc, 15782 CurFPFeatureOverrides()); 15783 else 15784 TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK, 15785 RParenLoc, CurFPFeatureOverrides()); 15786 15787 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 15788 return true; 15789 15790 if (CheckFunctionCall(Method, TheCall, Proto)) 15791 return true; 15792 15793 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15794 } 15795 15796 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 15797 /// (if one exists), where @c Base is an expression of class type and 15798 /// @c Member is the name of the member we're trying to find. 15799 ExprResult 15800 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 15801 bool *NoArrowOperatorFound) { 15802 assert(Base->getType()->isRecordType() && 15803 "left-hand side must have class type"); 15804 15805 if (checkPlaceholderForOverload(*this, Base)) 15806 return ExprError(); 15807 15808 SourceLocation Loc = Base->getExprLoc(); 15809 15810 // C++ [over.ref]p1: 15811 // 15812 // [...] An expression x->m is interpreted as (x.operator->())->m 15813 // for a class object x of type T if T::operator->() exists and if 15814 // the operator is selected as the best match function by the 15815 // overload resolution mechanism (13.3). 15816 DeclarationName OpName = 15817 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 15818 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 15819 15820 if (RequireCompleteType(Loc, Base->getType(), 15821 diag::err_typecheck_incomplete_tag, Base)) 15822 return ExprError(); 15823 15824 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 15825 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 15826 R.suppressAccessDiagnostics(); 15827 15828 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 15829 Oper != OperEnd; ++Oper) { 15830 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 15831 std::nullopt, CandidateSet, 15832 /*SuppressUserConversion=*/false); 15833 } 15834 15835 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15836 15837 // Perform overload resolution. 15838 OverloadCandidateSet::iterator Best; 15839 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 15840 case OR_Success: 15841 // Overload resolution succeeded; we'll build the call below. 15842 break; 15843 15844 case OR_No_Viable_Function: { 15845 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 15846 if (CandidateSet.empty()) { 15847 QualType BaseType = Base->getType(); 15848 if (NoArrowOperatorFound) { 15849 // Report this specific error to the caller instead of emitting a 15850 // diagnostic, as requested. 15851 *NoArrowOperatorFound = true; 15852 return ExprError(); 15853 } 15854 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 15855 << BaseType << Base->getSourceRange(); 15856 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 15857 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 15858 << FixItHint::CreateReplacement(OpLoc, "."); 15859 } 15860 } else 15861 Diag(OpLoc, diag::err_ovl_no_viable_oper) 15862 << "operator->" << Base->getSourceRange(); 15863 CandidateSet.NoteCandidates(*this, Base, Cands); 15864 return ExprError(); 15865 } 15866 case OR_Ambiguous: 15867 if (!R.isAmbiguous()) 15868 CandidateSet.NoteCandidates( 15869 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 15870 << "->" << Base->getType() 15871 << Base->getSourceRange()), 15872 *this, OCD_AmbiguousCandidates, Base); 15873 return ExprError(); 15874 15875 case OR_Deleted: 15876 CandidateSet.NoteCandidates( 15877 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 15878 << "->" << Base->getSourceRange()), 15879 *this, OCD_AllCandidates, Base); 15880 return ExprError(); 15881 } 15882 15883 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 15884 15885 // Convert the object parameter. 15886 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15887 15888 if (Method->isExplicitObjectMemberFunction()) { 15889 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method); 15890 if (R.isInvalid()) 15891 return ExprError(); 15892 Base = R.get(); 15893 } else { 15894 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization( 15895 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15896 if (BaseResult.isInvalid()) 15897 return ExprError(); 15898 Base = BaseResult.get(); 15899 } 15900 15901 // Build the operator call. 15902 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15903 Base, HadMultipleCandidates, OpLoc); 15904 if (FnExpr.isInvalid()) 15905 return ExprError(); 15906 15907 QualType ResultTy = Method->getReturnType(); 15908 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15909 ResultTy = ResultTy.getNonLValueExprType(Context); 15910 15911 CallExpr *TheCall = 15912 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 15913 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 15914 15915 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 15916 return ExprError(); 15917 15918 if (CheckFunctionCall(Method, TheCall, 15919 Method->getType()->castAs<FunctionProtoType>())) 15920 return ExprError(); 15921 15922 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15923 } 15924 15925 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 15926 /// a literal operator described by the provided lookup results. 15927 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 15928 DeclarationNameInfo &SuffixInfo, 15929 ArrayRef<Expr*> Args, 15930 SourceLocation LitEndLoc, 15931 TemplateArgumentListInfo *TemplateArgs) { 15932 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 15933 15934 OverloadCandidateSet CandidateSet(UDSuffixLoc, 15935 OverloadCandidateSet::CSK_Normal); 15936 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 15937 TemplateArgs); 15938 15939 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15940 15941 // Perform overload resolution. This will usually be trivial, but might need 15942 // to perform substitutions for a literal operator template. 15943 OverloadCandidateSet::iterator Best; 15944 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 15945 case OR_Success: 15946 case OR_Deleted: 15947 break; 15948 15949 case OR_No_Viable_Function: 15950 CandidateSet.NoteCandidates( 15951 PartialDiagnosticAt(UDSuffixLoc, 15952 PDiag(diag::err_ovl_no_viable_function_in_call) 15953 << R.getLookupName()), 15954 *this, OCD_AllCandidates, Args); 15955 return ExprError(); 15956 15957 case OR_Ambiguous: 15958 CandidateSet.NoteCandidates( 15959 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 15960 << R.getLookupName()), 15961 *this, OCD_AmbiguousCandidates, Args); 15962 return ExprError(); 15963 } 15964 15965 FunctionDecl *FD = Best->Function; 15966 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 15967 nullptr, HadMultipleCandidates, 15968 SuffixInfo.getLoc(), 15969 SuffixInfo.getInfo()); 15970 if (Fn.isInvalid()) 15971 return true; 15972 15973 // Check the argument types. This should almost always be a no-op, except 15974 // that array-to-pointer decay is applied to string literals. 15975 Expr *ConvArgs[2]; 15976 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 15977 ExprResult InputInit = PerformCopyInitialization( 15978 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 15979 SourceLocation(), Args[ArgIdx]); 15980 if (InputInit.isInvalid()) 15981 return true; 15982 ConvArgs[ArgIdx] = InputInit.get(); 15983 } 15984 15985 QualType ResultTy = FD->getReturnType(); 15986 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15987 ResultTy = ResultTy.getNonLValueExprType(Context); 15988 15989 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 15990 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK, 15991 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 15992 15993 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 15994 return ExprError(); 15995 15996 if (CheckFunctionCall(FD, UDL, nullptr)) 15997 return ExprError(); 15998 15999 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 16000 } 16001 16002 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 16003 /// given LookupResult is non-empty, it is assumed to describe a member which 16004 /// will be invoked. Otherwise, the function will be found via argument 16005 /// dependent lookup. 16006 /// CallExpr is set to a valid expression and FRS_Success returned on success, 16007 /// otherwise CallExpr is set to ExprError() and some non-success value 16008 /// is returned. 16009 Sema::ForRangeStatus 16010 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 16011 SourceLocation RangeLoc, 16012 const DeclarationNameInfo &NameInfo, 16013 LookupResult &MemberLookup, 16014 OverloadCandidateSet *CandidateSet, 16015 Expr *Range, ExprResult *CallExpr) { 16016 Scope *S = nullptr; 16017 16018 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 16019 if (!MemberLookup.empty()) { 16020 ExprResult MemberRef = 16021 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 16022 /*IsPtr=*/false, CXXScopeSpec(), 16023 /*TemplateKWLoc=*/SourceLocation(), 16024 /*FirstQualifierInScope=*/nullptr, 16025 MemberLookup, 16026 /*TemplateArgs=*/nullptr, S); 16027 if (MemberRef.isInvalid()) { 16028 *CallExpr = ExprError(); 16029 return FRS_DiagnosticIssued; 16030 } 16031 *CallExpr = 16032 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr); 16033 if (CallExpr->isInvalid()) { 16034 *CallExpr = ExprError(); 16035 return FRS_DiagnosticIssued; 16036 } 16037 } else { 16038 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 16039 NestedNameSpecifierLoc(), 16040 NameInfo, UnresolvedSet<0>()); 16041 if (FnR.isInvalid()) 16042 return FRS_DiagnosticIssued; 16043 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 16044 16045 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 16046 CandidateSet, CallExpr); 16047 if (CandidateSet->empty() || CandidateSetError) { 16048 *CallExpr = ExprError(); 16049 return FRS_NoViableFunction; 16050 } 16051 OverloadCandidateSet::iterator Best; 16052 OverloadingResult OverloadResult = 16053 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 16054 16055 if (OverloadResult == OR_No_Viable_Function) { 16056 *CallExpr = ExprError(); 16057 return FRS_NoViableFunction; 16058 } 16059 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 16060 Loc, nullptr, CandidateSet, &Best, 16061 OverloadResult, 16062 /*AllowTypoCorrection=*/false); 16063 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 16064 *CallExpr = ExprError(); 16065 return FRS_DiagnosticIssued; 16066 } 16067 } 16068 return FRS_Success; 16069 } 16070 16071 16072 /// FixOverloadedFunctionReference - E is an expression that refers to 16073 /// a C++ overloaded function (possibly with some parentheses and 16074 /// perhaps a '&' around it). We have resolved the overloaded function 16075 /// to the function declaration Fn, so patch up the expression E to 16076 /// refer (possibly indirectly) to Fn. Returns the new expr. 16077 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 16078 FunctionDecl *Fn) { 16079 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 16080 ExprResult SubExpr = 16081 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn); 16082 if (SubExpr.isInvalid()) 16083 return ExprError(); 16084 if (SubExpr.get() == PE->getSubExpr()) 16085 return PE; 16086 16087 return new (Context) 16088 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 16089 } 16090 16091 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 16092 ExprResult SubExpr = 16093 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn); 16094 if (SubExpr.isInvalid()) 16095 return ExprError(); 16096 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 16097 SubExpr.get()->getType()) && 16098 "Implicit cast type cannot be determined from overload"); 16099 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 16100 if (SubExpr.get() == ICE->getSubExpr()) 16101 return ICE; 16102 16103 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 16104 SubExpr.get(), nullptr, ICE->getValueKind(), 16105 CurFPFeatureOverrides()); 16106 } 16107 16108 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 16109 if (!GSE->isResultDependent()) { 16110 ExprResult SubExpr = 16111 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 16112 if (SubExpr.isInvalid()) 16113 return ExprError(); 16114 if (SubExpr.get() == GSE->getResultExpr()) 16115 return GSE; 16116 16117 // Replace the resulting type information before rebuilding the generic 16118 // selection expression. 16119 ArrayRef<Expr *> A = GSE->getAssocExprs(); 16120 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 16121 unsigned ResultIdx = GSE->getResultIndex(); 16122 AssocExprs[ResultIdx] = SubExpr.get(); 16123 16124 if (GSE->isExprPredicate()) 16125 return GenericSelectionExpr::Create( 16126 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 16127 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 16128 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 16129 ResultIdx); 16130 return GenericSelectionExpr::Create( 16131 Context, GSE->getGenericLoc(), GSE->getControllingType(), 16132 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 16133 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 16134 ResultIdx); 16135 } 16136 // Rather than fall through to the unreachable, return the original generic 16137 // selection expression. 16138 return GSE; 16139 } 16140 16141 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 16142 assert(UnOp->getOpcode() == UO_AddrOf && 16143 "Can only take the address of an overloaded function"); 16144 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 16145 if (Method->isStatic()) { 16146 // Do nothing: static member functions aren't any different 16147 // from non-member functions. 16148 } else { 16149 // Fix the subexpression, which really has to be an 16150 // UnresolvedLookupExpr holding an overloaded member function 16151 // or template. 16152 ExprResult SubExpr = 16153 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); 16154 if (SubExpr.isInvalid()) 16155 return ExprError(); 16156 if (SubExpr.get() == UnOp->getSubExpr()) 16157 return UnOp; 16158 16159 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(), 16160 SubExpr.get(), Method)) 16161 return ExprError(); 16162 16163 assert(isa<DeclRefExpr>(SubExpr.get()) && 16164 "fixed to something other than a decl ref"); 16165 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() && 16166 "fixed to a member ref with no nested name qualifier"); 16167 16168 // We have taken the address of a pointer to member 16169 // function. Perform the computation here so that we get the 16170 // appropriate pointer to member type. 16171 QualType ClassType 16172 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 16173 QualType MemPtrType 16174 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 16175 // Under the MS ABI, lock down the inheritance model now. 16176 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 16177 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 16178 16179 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf, 16180 MemPtrType, VK_PRValue, OK_Ordinary, 16181 UnOp->getOperatorLoc(), false, 16182 CurFPFeatureOverrides()); 16183 } 16184 } 16185 ExprResult SubExpr = 16186 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); 16187 if (SubExpr.isInvalid()) 16188 return ExprError(); 16189 if (SubExpr.get() == UnOp->getSubExpr()) 16190 return UnOp; 16191 16192 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, 16193 SubExpr.get()); 16194 } 16195 16196 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 16197 // FIXME: avoid copy. 16198 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 16199 if (ULE->hasExplicitTemplateArgs()) { 16200 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 16201 TemplateArgs = &TemplateArgsBuffer; 16202 } 16203 16204 QualType Type = Fn->getType(); 16205 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; 16206 16207 // FIXME: Duplicated from BuildDeclarationNameExpr. 16208 if (unsigned BID = Fn->getBuiltinID()) { 16209 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 16210 Type = Context.BuiltinFnTy; 16211 ValueKind = VK_PRValue; 16212 } 16213 } 16214 16215 DeclRefExpr *DRE = BuildDeclRefExpr( 16216 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), 16217 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); 16218 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 16219 return DRE; 16220 } 16221 16222 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 16223 // FIXME: avoid copy. 16224 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 16225 if (MemExpr->hasExplicitTemplateArgs()) { 16226 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 16227 TemplateArgs = &TemplateArgsBuffer; 16228 } 16229 16230 Expr *Base; 16231 16232 // If we're filling in a static method where we used to have an 16233 // implicit member access, rewrite to a simple decl ref. 16234 if (MemExpr->isImplicitAccess()) { 16235 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 16236 DeclRefExpr *DRE = BuildDeclRefExpr( 16237 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 16238 MemExpr->getQualifierLoc(), Found.getDecl(), 16239 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 16240 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 16241 return DRE; 16242 } else { 16243 SourceLocation Loc = MemExpr->getMemberLoc(); 16244 if (MemExpr->getQualifier()) 16245 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 16246 Base = 16247 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 16248 } 16249 } else 16250 Base = MemExpr->getBase(); 16251 16252 ExprValueKind valueKind; 16253 QualType type; 16254 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 16255 valueKind = VK_LValue; 16256 type = Fn->getType(); 16257 } else { 16258 valueKind = VK_PRValue; 16259 type = Context.BoundMemberTy; 16260 } 16261 16262 return BuildMemberExpr( 16263 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 16264 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 16265 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 16266 type, valueKind, OK_Ordinary, TemplateArgs); 16267 } 16268 16269 llvm_unreachable("Invalid reference to overloaded function"); 16270 } 16271 16272 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 16273 DeclAccessPair Found, 16274 FunctionDecl *Fn) { 16275 return FixOverloadedFunctionReference(E.get(), Found, Fn); 16276 } 16277 16278 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 16279 FunctionDecl *Function) { 16280 if (!PartialOverloading || !Function) 16281 return true; 16282 if (Function->isVariadic()) 16283 return false; 16284 if (const auto *Proto = 16285 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 16286 if (Proto->isTemplateVariadic()) 16287 return false; 16288 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 16289 if (const auto *Proto = 16290 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 16291 if (Proto->isTemplateVariadic()) 16292 return false; 16293 return true; 16294 } 16295