1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult CreateFunctionRefExpr( 53 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 54 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 55 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 56 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 57 return ExprError(); 58 // If FoundDecl is different from Fn (such as if one is a template 59 // and the other a specialization), make sure DiagnoseUseOfDecl is 60 // called on both. 61 // FIXME: This would be more comprehensively addressed by modifying 62 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 63 // being used. 64 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 65 return ExprError(); 66 DeclRefExpr *DRE = new (S.Context) 67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 73 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 74 S.ResolveExceptionSpec(Loc, FPT); 75 DRE->setType(Fn->getType()); 76 } 77 } 78 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 79 CK_FunctionToPointerDecay); 80 } 81 82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle, 86 bool AllowObjCWritebackConversion); 87 88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 89 QualType &ToType, 90 bool InOverloadResolution, 91 StandardConversionSequence &SCS, 92 bool CStyle); 93 static OverloadingResult 94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 95 UserDefinedConversionSequence& User, 96 OverloadCandidateSet& Conversions, 97 AllowedExplicit AllowExplicit, 98 bool AllowObjCConversionOnExplicit); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareQualificationConversions(Sema &S, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 static ImplicitConversionSequence::CompareKind 111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 112 const StandardConversionSequence& SCS1, 113 const StandardConversionSequence& SCS2); 114 115 /// GetConversionRank - Retrieve the implicit conversion rank 116 /// corresponding to the given implicit conversion kind. 117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 118 static const ImplicitConversionRank 119 Rank[(int)ICK_Num_Conversion_Kinds] = { 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Promotion, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_OCL_Scalar_Widening, 141 ICR_Complex_Real_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Writeback_Conversion, 145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 146 // it was omitted by the patch that added 147 // ICK_Zero_Event_Conversion 148 ICR_C_Conversion, 149 ICR_C_Conversion_Extension 150 }; 151 return Rank[(int)Kind]; 152 } 153 154 /// GetImplicitConversionName - Return the name of this kind of 155 /// implicit conversion. 156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 158 "No conversion", 159 "Lvalue-to-rvalue", 160 "Array-to-pointer", 161 "Function-to-pointer", 162 "Function pointer conversion", 163 "Qualification", 164 "Integral promotion", 165 "Floating point promotion", 166 "Complex promotion", 167 "Integral conversion", 168 "Floating conversion", 169 "Complex conversion", 170 "Floating-integral conversion", 171 "Pointer conversion", 172 "Pointer-to-member conversion", 173 "Boolean conversion", 174 "Compatible-types conversion", 175 "Derived-to-base conversion", 176 "Vector conversion", 177 "SVE Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion", 182 "Writeback conversion", 183 "OpenCL Zero Event Conversion", 184 "C specific type conversion", 185 "Incompatible pointer conversion" 186 }; 187 return Name[Kind]; 188 } 189 190 /// StandardConversionSequence - Set the standard conversion 191 /// sequence to the identity conversion. 192 void StandardConversionSequence::setAsIdentityConversion() { 193 First = ICK_Identity; 194 Second = ICK_Identity; 195 Third = ICK_Identity; 196 DeprecatedStringLiteralToCharPtr = false; 197 QualificationIncludesObjCLifetime = false; 198 ReferenceBinding = false; 199 DirectBinding = false; 200 IsLvalueReference = true; 201 BindsToFunctionLvalue = false; 202 BindsToRvalue = false; 203 BindsImplicitObjectArgumentWithoutRefQualifier = false; 204 ObjCLifetimeConversionBinding = false; 205 CopyConstructor = nullptr; 206 } 207 208 /// getRank - Retrieve the rank of this standard conversion sequence 209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 210 /// implicit conversions. 211 ImplicitConversionRank StandardConversionSequence::getRank() const { 212 ImplicitConversionRank Rank = ICR_Exact_Match; 213 if (GetConversionRank(First) > Rank) 214 Rank = GetConversionRank(First); 215 if (GetConversionRank(Second) > Rank) 216 Rank = GetConversionRank(Second); 217 if (GetConversionRank(Third) > Rank) 218 Rank = GetConversionRank(Third); 219 return Rank; 220 } 221 222 /// isPointerConversionToBool - Determines whether this conversion is 223 /// a conversion of a pointer or pointer-to-member to bool. This is 224 /// used as part of the ranking of standard conversion sequences 225 /// (C++ 13.3.3.2p4). 226 bool StandardConversionSequence::isPointerConversionToBool() const { 227 // Note that FromType has not necessarily been transformed by the 228 // array-to-pointer or function-to-pointer implicit conversions, so 229 // check for their presence as well as checking whether FromType is 230 // a pointer. 231 if (getToType(1)->isBooleanType() && 232 (getFromType()->isPointerType() || 233 getFromType()->isMemberPointerType() || 234 getFromType()->isObjCObjectPointerType() || 235 getFromType()->isBlockPointerType() || 236 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 237 return true; 238 239 return false; 240 } 241 242 /// isPointerConversionToVoidPointer - Determines whether this 243 /// conversion is a conversion of a pointer to a void pointer. This is 244 /// used as part of the ranking of standard conversion sequences (C++ 245 /// 13.3.3.2p4). 246 bool 247 StandardConversionSequence:: 248 isPointerConversionToVoidPointer(ASTContext& Context) const { 249 QualType FromType = getFromType(); 250 QualType ToType = getToType(1); 251 252 // Note that FromType has not necessarily been transformed by the 253 // array-to-pointer implicit conversion, so check for its presence 254 // and redo the conversion to get a pointer. 255 if (First == ICK_Array_To_Pointer) 256 FromType = Context.getArrayDecayedType(FromType); 257 258 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 259 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 260 return ToPtrType->getPointeeType()->isVoidType(); 261 262 return false; 263 } 264 265 /// Skip any implicit casts which could be either part of a narrowing conversion 266 /// or after one in an implicit conversion. 267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 268 const Expr *Converted) { 269 // We can have cleanups wrapping the converted expression; these need to be 270 // preserved so that destructors run if necessary. 271 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 272 Expr *Inner = 273 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 274 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 275 EWC->getObjects()); 276 } 277 278 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 279 switch (ICE->getCastKind()) { 280 case CK_NoOp: 281 case CK_IntegralCast: 282 case CK_IntegralToBoolean: 283 case CK_IntegralToFloating: 284 case CK_BooleanToSignedIntegral: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297 } 298 299 /// Check if this standard conversion sequence represents a narrowing 300 /// conversion, according to C++11 [dcl.init.list]p7. 301 /// 302 /// \param Ctx The AST context. 303 /// \param Converted The result of applying this standard conversion sequence. 304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305 /// value of the expression prior to the narrowing conversion. 306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307 /// type of the expression prior to the narrowing conversion. 308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 309 /// from floating point types to integral types should be ignored. 310 NarrowingKind StandardConversionSequence::getNarrowingKind( 311 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 312 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 320 // A conversion to an enumeration type is narrowing if the conversion to 321 // the underlying type is narrowing. This only arises for expressions of 322 // the form 'Enum{init}'. 323 if (auto *ET = ToType->getAs<EnumType>()) 324 ToType = ET->getDecl()->getIntegerType(); 325 326 switch (Second) { 327 // 'bool' is an integral type; dispatch to the right place to handle it. 328 case ICK_Boolean_Conversion: 329 if (FromType->isRealFloatingType()) 330 goto FloatingIntegralConversion; 331 if (FromType->isIntegralOrUnscopedEnumerationType()) 332 goto IntegralConversion; 333 // -- from a pointer type or pointer-to-member type to bool, or 334 return NK_Type_Narrowing; 335 336 // -- from a floating-point type to an integer type, or 337 // 338 // -- from an integer type or unscoped enumeration type to a floating-point 339 // type, except where the source is a constant expression and the actual 340 // value after conversion will fit into the target type and will produce 341 // the original value when converted back to the original type, or 342 case ICK_Floating_Integral: 343 FloatingIntegralConversion: 344 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 345 return NK_Type_Narrowing; 346 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 347 ToType->isRealFloatingType()) { 348 if (IgnoreFloatToIntegralConversion) 349 return NK_Not_Narrowing; 350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 351 assert(Initializer && "Unknown conversion expression"); 352 353 // If it's value-dependent, we can't tell whether it's narrowing. 354 if (Initializer->isValueDependent()) 355 return NK_Dependent_Narrowing; 356 357 if (Optional<llvm::APSInt> IntConstantValue = 358 Initializer->getIntegerConstantExpr(Ctx)) { 359 // Convert the integer to the floating type. 360 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 361 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 362 llvm::APFloat::rmNearestTiesToEven); 363 // And back. 364 llvm::APSInt ConvertedValue = *IntConstantValue; 365 bool ignored; 366 Result.convertToInteger(ConvertedValue, 367 llvm::APFloat::rmTowardZero, &ignored); 368 // If the resulting value is different, this was a narrowing conversion. 369 if (*IntConstantValue != ConvertedValue) { 370 ConstantValue = APValue(*IntConstantValue); 371 ConstantType = Initializer->getType(); 372 return NK_Constant_Narrowing; 373 } 374 } else { 375 // Variables are always narrowings. 376 return NK_Variable_Narrowing; 377 } 378 } 379 return NK_Not_Narrowing; 380 381 // -- from long double to double or float, or from double to float, except 382 // where the source is a constant expression and the actual value after 383 // conversion is within the range of values that can be represented (even 384 // if it cannot be represented exactly), or 385 case ICK_Floating_Conversion: 386 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 387 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 388 // FromType is larger than ToType. 389 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 390 391 // If it's value-dependent, we can't tell whether it's narrowing. 392 if (Initializer->isValueDependent()) 393 return NK_Dependent_Narrowing; 394 395 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 396 // Constant! 397 assert(ConstantValue.isFloat()); 398 llvm::APFloat FloatVal = ConstantValue.getFloat(); 399 // Convert the source value into the target type. 400 bool ignored; 401 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 402 Ctx.getFloatTypeSemantics(ToType), 403 llvm::APFloat::rmNearestTiesToEven, &ignored); 404 // If there was no overflow, the source value is within the range of 405 // values that can be represented. 406 if (ConvertStatus & llvm::APFloat::opOverflow) { 407 ConstantType = Initializer->getType(); 408 return NK_Constant_Narrowing; 409 } 410 } else { 411 return NK_Variable_Narrowing; 412 } 413 } 414 return NK_Not_Narrowing; 415 416 // -- from an integer type or unscoped enumeration type to an integer type 417 // that cannot represent all the values of the original type, except where 418 // the source is a constant expression and the actual value after 419 // conversion will fit into the target type and will produce the original 420 // value when converted back to the original type. 421 case ICK_Integral_Conversion: 422 IntegralConversion: { 423 assert(FromType->isIntegralOrUnscopedEnumerationType()); 424 assert(ToType->isIntegralOrUnscopedEnumerationType()); 425 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 426 const unsigned FromWidth = Ctx.getIntWidth(FromType); 427 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 428 const unsigned ToWidth = Ctx.getIntWidth(ToType); 429 430 if (FromWidth > ToWidth || 431 (FromWidth == ToWidth && FromSigned != ToSigned) || 432 (FromSigned && !ToSigned)) { 433 // Not all values of FromType can be represented in ToType. 434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 435 436 // If it's value-dependent, we can't tell whether it's narrowing. 437 if (Initializer->isValueDependent()) 438 return NK_Dependent_Narrowing; 439 440 Optional<llvm::APSInt> OptInitializerValue; 441 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 442 // Such conversions on variables are always narrowing. 443 return NK_Variable_Narrowing; 444 } 445 llvm::APSInt &InitializerValue = *OptInitializerValue; 446 bool Narrowing = false; 447 if (FromWidth < ToWidth) { 448 // Negative -> unsigned is narrowing. Otherwise, more bits is never 449 // narrowing. 450 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 451 Narrowing = true; 452 } else { 453 // Add a bit to the InitializerValue so we don't have to worry about 454 // signed vs. unsigned comparisons. 455 InitializerValue = InitializerValue.extend( 456 InitializerValue.getBitWidth() + 1); 457 // Convert the initializer to and from the target width and signed-ness. 458 llvm::APSInt ConvertedValue = InitializerValue; 459 ConvertedValue = ConvertedValue.trunc(ToWidth); 460 ConvertedValue.setIsSigned(ToSigned); 461 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 462 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 463 // If the result is different, this was a narrowing conversion. 464 if (ConvertedValue != InitializerValue) 465 Narrowing = true; 466 } 467 if (Narrowing) { 468 ConstantType = Initializer->getType(); 469 ConstantValue = APValue(InitializerValue); 470 return NK_Constant_Narrowing; 471 } 472 } 473 return NK_Not_Narrowing; 474 } 475 476 default: 477 // Other kinds of conversions are not narrowings. 478 return NK_Not_Narrowing; 479 } 480 } 481 482 /// dump - Print this standard conversion sequence to standard 483 /// error. Useful for debugging overloading issues. 484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 485 raw_ostream &OS = llvm::errs(); 486 bool PrintedSomething = false; 487 if (First != ICK_Identity) { 488 OS << GetImplicitConversionName(First); 489 PrintedSomething = true; 490 } 491 492 if (Second != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Second); 497 498 if (CopyConstructor) { 499 OS << " (by copy constructor)"; 500 } else if (DirectBinding) { 501 OS << " (direct reference binding)"; 502 } else if (ReferenceBinding) { 503 OS << " (reference binding)"; 504 } 505 PrintedSomething = true; 506 } 507 508 if (Third != ICK_Identity) { 509 if (PrintedSomething) { 510 OS << " -> "; 511 } 512 OS << GetImplicitConversionName(Third); 513 PrintedSomething = true; 514 } 515 516 if (!PrintedSomething) { 517 OS << "No conversions required"; 518 } 519 } 520 521 /// dump - Print this user-defined conversion sequence to standard 522 /// error. Useful for debugging overloading issues. 523 void UserDefinedConversionSequence::dump() const { 524 raw_ostream &OS = llvm::errs(); 525 if (Before.First || Before.Second || Before.Third) { 526 Before.dump(); 527 OS << " -> "; 528 } 529 if (ConversionFunction) 530 OS << '\'' << *ConversionFunction << '\''; 531 else 532 OS << "aggregate initialization"; 533 if (After.First || After.Second || After.Third) { 534 OS << " -> "; 535 After.dump(); 536 } 537 } 538 539 /// dump - Print this implicit conversion sequence to standard 540 /// error. Useful for debugging overloading issues. 541 void ImplicitConversionSequence::dump() const { 542 raw_ostream &OS = llvm::errs(); 543 if (hasInitializerListContainerType()) 544 OS << "Worst list element conversion: "; 545 switch (ConversionKind) { 546 case StandardConversion: 547 OS << "Standard conversion: "; 548 Standard.dump(); 549 break; 550 case UserDefinedConversion: 551 OS << "User-defined conversion: "; 552 UserDefined.dump(); 553 break; 554 case EllipsisConversion: 555 OS << "Ellipsis conversion"; 556 break; 557 case AmbiguousConversion: 558 OS << "Ambiguous conversion"; 559 break; 560 case BadConversion: 561 OS << "Bad conversion"; 562 break; 563 } 564 565 OS << "\n"; 566 } 567 568 void AmbiguousConversionSequence::construct() { 569 new (&conversions()) ConversionSet(); 570 } 571 572 void AmbiguousConversionSequence::destruct() { 573 conversions().~ConversionSet(); 574 } 575 576 void 577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 578 FromTypePtr = O.FromTypePtr; 579 ToTypePtr = O.ToTypePtr; 580 new (&conversions()) ConversionSet(O.conversions()); 581 } 582 583 namespace { 584 // Structure used by DeductionFailureInfo to store 585 // template argument information. 586 struct DFIArguments { 587 TemplateArgument FirstArg; 588 TemplateArgument SecondArg; 589 }; 590 // Structure used by DeductionFailureInfo to store 591 // template parameter and template argument information. 592 struct DFIParamWithArguments : DFIArguments { 593 TemplateParameter Param; 594 }; 595 // Structure used by DeductionFailureInfo to store template argument 596 // information and the index of the problematic call argument. 597 struct DFIDeducedMismatchArgs : DFIArguments { 598 TemplateArgumentList *TemplateArgs; 599 unsigned CallArgIndex; 600 }; 601 // Structure used by DeductionFailureInfo to store information about 602 // unsatisfied constraints. 603 struct CNSInfo { 604 TemplateArgumentList *TemplateArgs; 605 ConstraintSatisfaction Satisfaction; 606 }; 607 } 608 609 /// Convert from Sema's representation of template deduction information 610 /// to the form used in overload-candidate information. 611 DeductionFailureInfo 612 clang::MakeDeductionFailureInfo(ASTContext &Context, 613 Sema::TemplateDeductionResult TDK, 614 TemplateDeductionInfo &Info) { 615 DeductionFailureInfo Result; 616 Result.Result = static_cast<unsigned>(TDK); 617 Result.HasDiagnostic = false; 618 switch (TDK) { 619 case Sema::TDK_Invalid: 620 case Sema::TDK_InstantiationDepth: 621 case Sema::TDK_TooManyArguments: 622 case Sema::TDK_TooFewArguments: 623 case Sema::TDK_MiscellaneousDeductionFailure: 624 case Sema::TDK_CUDATargetMismatch: 625 Result.Data = nullptr; 626 break; 627 628 case Sema::TDK_Incomplete: 629 case Sema::TDK_InvalidExplicitArguments: 630 Result.Data = Info.Param.getOpaqueValue(); 631 break; 632 633 case Sema::TDK_DeducedMismatch: 634 case Sema::TDK_DeducedMismatchNested: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 auto *Saved = new (Context) DFIDeducedMismatchArgs; 637 Saved->FirstArg = Info.FirstArg; 638 Saved->SecondArg = Info.SecondArg; 639 Saved->TemplateArgs = Info.take(); 640 Saved->CallArgIndex = Info.CallArgIndex; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_NonDeducedMismatch: { 646 // FIXME: Should allocate from normal heap so that we can free this later. 647 DFIArguments *Saved = new (Context) DFIArguments; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_IncompletePack: 655 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 656 case Sema::TDK_Inconsistent: 657 case Sema::TDK_Underqualified: { 658 // FIXME: Should allocate from normal heap so that we can free this later. 659 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 660 Saved->Param = Info.Param; 661 Saved->FirstArg = Info.FirstArg; 662 Saved->SecondArg = Info.SecondArg; 663 Result.Data = Saved; 664 break; 665 } 666 667 case Sema::TDK_SubstitutionFailure: 668 Result.Data = Info.take(); 669 if (Info.hasSFINAEDiagnostic()) { 670 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 671 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 672 Info.takeSFINAEDiagnostic(*Diag); 673 Result.HasDiagnostic = true; 674 } 675 break; 676 677 case Sema::TDK_ConstraintsNotSatisfied: { 678 CNSInfo *Saved = new (Context) CNSInfo; 679 Saved->TemplateArgs = Info.take(); 680 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 681 Result.Data = Saved; 682 break; 683 } 684 685 case Sema::TDK_Success: 686 case Sema::TDK_NonDependentConversionFailure: 687 llvm_unreachable("not a deduction failure"); 688 } 689 690 return Result; 691 } 692 693 void DeductionFailureInfo::Destroy() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_CUDATargetMismatch: 703 case Sema::TDK_NonDependentConversionFailure: 704 break; 705 706 case Sema::TDK_IncompletePack: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_DeducedMismatch: 710 case Sema::TDK_DeducedMismatchNested: 711 case Sema::TDK_NonDeducedMismatch: 712 // FIXME: Destroy the data? 713 Data = nullptr; 714 break; 715 716 case Sema::TDK_SubstitutionFailure: 717 // FIXME: Destroy the template argument list? 718 Data = nullptr; 719 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 720 Diag->~PartialDiagnosticAt(); 721 HasDiagnostic = false; 722 } 723 break; 724 725 case Sema::TDK_ConstraintsNotSatisfied: 726 // FIXME: Destroy the template argument list? 727 Data = nullptr; 728 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 729 Diag->~PartialDiagnosticAt(); 730 HasDiagnostic = false; 731 } 732 break; 733 734 // Unhandled 735 case Sema::TDK_MiscellaneousDeductionFailure: 736 break; 737 } 738 } 739 740 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 741 if (HasDiagnostic) 742 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 743 return nullptr; 744 } 745 746 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 747 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 748 case Sema::TDK_Success: 749 case Sema::TDK_Invalid: 750 case Sema::TDK_InstantiationDepth: 751 case Sema::TDK_TooManyArguments: 752 case Sema::TDK_TooFewArguments: 753 case Sema::TDK_SubstitutionFailure: 754 case Sema::TDK_DeducedMismatch: 755 case Sema::TDK_DeducedMismatchNested: 756 case Sema::TDK_NonDeducedMismatch: 757 case Sema::TDK_CUDATargetMismatch: 758 case Sema::TDK_NonDependentConversionFailure: 759 case Sema::TDK_ConstraintsNotSatisfied: 760 return TemplateParameter(); 761 762 case Sema::TDK_Incomplete: 763 case Sema::TDK_InvalidExplicitArguments: 764 return TemplateParameter::getFromOpaqueValue(Data); 765 766 case Sema::TDK_IncompletePack: 767 case Sema::TDK_Inconsistent: 768 case Sema::TDK_Underqualified: 769 return static_cast<DFIParamWithArguments*>(Data)->Param; 770 771 // Unhandled 772 case Sema::TDK_MiscellaneousDeductionFailure: 773 break; 774 } 775 776 return TemplateParameter(); 777 } 778 779 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 780 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 781 case Sema::TDK_Success: 782 case Sema::TDK_Invalid: 783 case Sema::TDK_InstantiationDepth: 784 case Sema::TDK_TooManyArguments: 785 case Sema::TDK_TooFewArguments: 786 case Sema::TDK_Incomplete: 787 case Sema::TDK_IncompletePack: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_Inconsistent: 790 case Sema::TDK_Underqualified: 791 case Sema::TDK_NonDeducedMismatch: 792 case Sema::TDK_CUDATargetMismatch: 793 case Sema::TDK_NonDependentConversionFailure: 794 return nullptr; 795 796 case Sema::TDK_DeducedMismatch: 797 case Sema::TDK_DeducedMismatchNested: 798 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 799 800 case Sema::TDK_SubstitutionFailure: 801 return static_cast<TemplateArgumentList*>(Data); 802 803 case Sema::TDK_ConstraintsNotSatisfied: 804 return static_cast<CNSInfo*>(Data)->TemplateArgs; 805 806 // Unhandled 807 case Sema::TDK_MiscellaneousDeductionFailure: 808 break; 809 } 810 811 return nullptr; 812 } 813 814 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 815 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 816 case Sema::TDK_Success: 817 case Sema::TDK_Invalid: 818 case Sema::TDK_InstantiationDepth: 819 case Sema::TDK_Incomplete: 820 case Sema::TDK_TooManyArguments: 821 case Sema::TDK_TooFewArguments: 822 case Sema::TDK_InvalidExplicitArguments: 823 case Sema::TDK_SubstitutionFailure: 824 case Sema::TDK_CUDATargetMismatch: 825 case Sema::TDK_NonDependentConversionFailure: 826 case Sema::TDK_ConstraintsNotSatisfied: 827 return nullptr; 828 829 case Sema::TDK_IncompletePack: 830 case Sema::TDK_Inconsistent: 831 case Sema::TDK_Underqualified: 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 case Sema::TDK_NonDeducedMismatch: 835 return &static_cast<DFIArguments*>(Data)->FirstArg; 836 837 // Unhandled 838 case Sema::TDK_MiscellaneousDeductionFailure: 839 break; 840 } 841 842 return nullptr; 843 } 844 845 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 846 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 847 case Sema::TDK_Success: 848 case Sema::TDK_Invalid: 849 case Sema::TDK_InstantiationDepth: 850 case Sema::TDK_Incomplete: 851 case Sema::TDK_IncompletePack: 852 case Sema::TDK_TooManyArguments: 853 case Sema::TDK_TooFewArguments: 854 case Sema::TDK_InvalidExplicitArguments: 855 case Sema::TDK_SubstitutionFailure: 856 case Sema::TDK_CUDATargetMismatch: 857 case Sema::TDK_NonDependentConversionFailure: 858 case Sema::TDK_ConstraintsNotSatisfied: 859 return nullptr; 860 861 case Sema::TDK_Inconsistent: 862 case Sema::TDK_Underqualified: 863 case Sema::TDK_DeducedMismatch: 864 case Sema::TDK_DeducedMismatchNested: 865 case Sema::TDK_NonDeducedMismatch: 866 return &static_cast<DFIArguments*>(Data)->SecondArg; 867 868 // Unhandled 869 case Sema::TDK_MiscellaneousDeductionFailure: 870 break; 871 } 872 873 return nullptr; 874 } 875 876 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 877 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 878 case Sema::TDK_DeducedMismatch: 879 case Sema::TDK_DeducedMismatchNested: 880 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 881 882 default: 883 return llvm::None; 884 } 885 } 886 887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 888 OverloadedOperatorKind Op) { 889 if (!AllowRewrittenCandidates) 890 return false; 891 return Op == OO_EqualEqual || Op == OO_Spaceship; 892 } 893 894 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 895 ASTContext &Ctx, const FunctionDecl *FD) { 896 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 897 return false; 898 // Don't bother adding a reversed candidate that can never be a better 899 // match than the non-reversed version. 900 return FD->getNumParams() != 2 || 901 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 902 FD->getParamDecl(1)->getType()) || 903 FD->hasAttr<EnableIfAttr>(); 904 } 905 906 void OverloadCandidateSet::destroyCandidates() { 907 for (iterator i = begin(), e = end(); i != e; ++i) { 908 for (auto &C : i->Conversions) 909 C.~ImplicitConversionSequence(); 910 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 911 i->DeductionFailure.Destroy(); 912 } 913 } 914 915 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 916 destroyCandidates(); 917 SlabAllocator.Reset(); 918 NumInlineBytesUsed = 0; 919 Candidates.clear(); 920 Functions.clear(); 921 Kind = CSK; 922 } 923 924 namespace { 925 class UnbridgedCastsSet { 926 struct Entry { 927 Expr **Addr; 928 Expr *Saved; 929 }; 930 SmallVector<Entry, 2> Entries; 931 932 public: 933 void save(Sema &S, Expr *&E) { 934 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 935 Entry entry = { &E, E }; 936 Entries.push_back(entry); 937 E = S.stripARCUnbridgedCast(E); 938 } 939 940 void restore() { 941 for (SmallVectorImpl<Entry>::iterator 942 i = Entries.begin(), e = Entries.end(); i != e; ++i) 943 *i->Addr = i->Saved; 944 } 945 }; 946 } 947 948 /// checkPlaceholderForOverload - Do any interesting placeholder-like 949 /// preprocessing on the given expression. 950 /// 951 /// \param unbridgedCasts a collection to which to add unbridged casts; 952 /// without this, they will be immediately diagnosed as errors 953 /// 954 /// Return true on unrecoverable error. 955 static bool 956 checkPlaceholderForOverload(Sema &S, Expr *&E, 957 UnbridgedCastsSet *unbridgedCasts = nullptr) { 958 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 959 // We can't handle overloaded expressions here because overload 960 // resolution might reasonably tweak them. 961 if (placeholder->getKind() == BuiltinType::Overload) return false; 962 963 // If the context potentially accepts unbridged ARC casts, strip 964 // the unbridged cast and add it to the collection for later restoration. 965 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 966 unbridgedCasts) { 967 unbridgedCasts->save(S, E); 968 return false; 969 } 970 971 // Go ahead and check everything else. 972 ExprResult result = S.CheckPlaceholderExpr(E); 973 if (result.isInvalid()) 974 return true; 975 976 E = result.get(); 977 return false; 978 } 979 980 // Nothing to do. 981 return false; 982 } 983 984 /// checkArgPlaceholdersForOverload - Check a set of call operands for 985 /// placeholders. 986 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 987 UnbridgedCastsSet &unbridged) { 988 for (unsigned i = 0, e = Args.size(); i != e; ++i) 989 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 990 return true; 991 992 return false; 993 } 994 995 /// Determine whether the given New declaration is an overload of the 996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 997 /// New and Old cannot be overloaded, e.g., if New has the same signature as 998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 999 /// functions (or function templates) at all. When it does return Ovl_Match or 1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1002 /// declaration. 1003 /// 1004 /// Example: Given the following input: 1005 /// 1006 /// void f(int, float); // #1 1007 /// void f(int, int); // #2 1008 /// int f(int, int); // #3 1009 /// 1010 /// When we process #1, there is no previous declaration of "f", so IsOverload 1011 /// will not be used. 1012 /// 1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1016 /// unchanged. 1017 /// 1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1022 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1023 /// 1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1025 /// by a using declaration. The rules for whether to hide shadow declarations 1026 /// ignore some properties which otherwise figure into a function template's 1027 /// signature. 1028 Sema::OverloadKind 1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1030 NamedDecl *&Match, bool NewIsUsingDecl) { 1031 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1032 I != E; ++I) { 1033 NamedDecl *OldD = *I; 1034 1035 bool OldIsUsingDecl = false; 1036 if (isa<UsingShadowDecl>(OldD)) { 1037 OldIsUsingDecl = true; 1038 1039 // We can always introduce two using declarations into the same 1040 // context, even if they have identical signatures. 1041 if (NewIsUsingDecl) continue; 1042 1043 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1044 } 1045 1046 // A using-declaration does not conflict with another declaration 1047 // if one of them is hidden. 1048 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1049 continue; 1050 1051 // If either declaration was introduced by a using declaration, 1052 // we'll need to use slightly different rules for matching. 1053 // Essentially, these rules are the normal rules, except that 1054 // function templates hide function templates with different 1055 // return types or template parameter lists. 1056 bool UseMemberUsingDeclRules = 1057 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1058 !New->getFriendObjectKind(); 1059 1060 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1061 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1062 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1063 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1064 continue; 1065 } 1066 1067 if (!isa<FunctionTemplateDecl>(OldD) && 1068 !shouldLinkPossiblyHiddenDecl(*I, New)) 1069 continue; 1070 1071 Match = *I; 1072 return Ovl_Match; 1073 } 1074 1075 // Builtins that have custom typechecking or have a reference should 1076 // not be overloadable or redeclarable. 1077 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1078 Match = *I; 1079 return Ovl_NonFunction; 1080 } 1081 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1082 // We can overload with these, which can show up when doing 1083 // redeclaration checks for UsingDecls. 1084 assert(Old.getLookupKind() == LookupUsingDeclName); 1085 } else if (isa<TagDecl>(OldD)) { 1086 // We can always overload with tags by hiding them. 1087 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1088 // Optimistically assume that an unresolved using decl will 1089 // overload; if it doesn't, we'll have to diagnose during 1090 // template instantiation. 1091 // 1092 // Exception: if the scope is dependent and this is not a class 1093 // member, the using declaration can only introduce an enumerator. 1094 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1095 Match = *I; 1096 return Ovl_NonFunction; 1097 } 1098 } else { 1099 // (C++ 13p1): 1100 // Only function declarations can be overloaded; object and type 1101 // declarations cannot be overloaded. 1102 Match = *I; 1103 return Ovl_NonFunction; 1104 } 1105 } 1106 1107 // C++ [temp.friend]p1: 1108 // For a friend function declaration that is not a template declaration: 1109 // -- if the name of the friend is a qualified or unqualified template-id, 1110 // [...], otherwise 1111 // -- if the name of the friend is a qualified-id and a matching 1112 // non-template function is found in the specified class or namespace, 1113 // the friend declaration refers to that function, otherwise, 1114 // -- if the name of the friend is a qualified-id and a matching function 1115 // template is found in the specified class or namespace, the friend 1116 // declaration refers to the deduced specialization of that function 1117 // template, otherwise 1118 // -- the name shall be an unqualified-id [...] 1119 // If we get here for a qualified friend declaration, we've just reached the 1120 // third bullet. If the type of the friend is dependent, skip this lookup 1121 // until instantiation. 1122 if (New->getFriendObjectKind() && New->getQualifier() && 1123 !New->getDescribedFunctionTemplate() && 1124 !New->getDependentSpecializationInfo() && 1125 !New->getType()->isDependentType()) { 1126 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1127 TemplateSpecResult.addAllDecls(Old); 1128 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1129 /*QualifiedFriend*/true)) { 1130 New->setInvalidDecl(); 1131 return Ovl_Overload; 1132 } 1133 1134 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1135 return Ovl_Match; 1136 } 1137 1138 return Ovl_Overload; 1139 } 1140 1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1142 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1143 bool ConsiderRequiresClauses) { 1144 // C++ [basic.start.main]p2: This function shall not be overloaded. 1145 if (New->isMain()) 1146 return false; 1147 1148 // MSVCRT user defined entry points cannot be overloaded. 1149 if (New->isMSVCRTEntryPoint()) 1150 return false; 1151 1152 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1153 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1154 1155 // C++ [temp.fct]p2: 1156 // A function template can be overloaded with other function templates 1157 // and with normal (non-template) functions. 1158 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1159 return true; 1160 1161 // Is the function New an overload of the function Old? 1162 QualType OldQType = Context.getCanonicalType(Old->getType()); 1163 QualType NewQType = Context.getCanonicalType(New->getType()); 1164 1165 // Compare the signatures (C++ 1.3.10) of the two functions to 1166 // determine whether they are overloads. If we find any mismatch 1167 // in the signature, they are overloads. 1168 1169 // If either of these functions is a K&R-style function (no 1170 // prototype), then we consider them to have matching signatures. 1171 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1172 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1173 return false; 1174 1175 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1176 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1177 1178 // The signature of a function includes the types of its 1179 // parameters (C++ 1.3.10), which includes the presence or absence 1180 // of the ellipsis; see C++ DR 357). 1181 if (OldQType != NewQType && 1182 (OldType->getNumParams() != NewType->getNumParams() || 1183 OldType->isVariadic() != NewType->isVariadic() || 1184 !FunctionParamTypesAreEqual(OldType, NewType))) 1185 return true; 1186 1187 // C++ [temp.over.link]p4: 1188 // The signature of a function template consists of its function 1189 // signature, its return type and its template parameter list. The names 1190 // of the template parameters are significant only for establishing the 1191 // relationship between the template parameters and the rest of the 1192 // signature. 1193 // 1194 // We check the return type and template parameter lists for function 1195 // templates first; the remaining checks follow. 1196 // 1197 // However, we don't consider either of these when deciding whether 1198 // a member introduced by a shadow declaration is hidden. 1199 if (!UseMemberUsingDeclRules && NewTemplate && 1200 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1201 OldTemplate->getTemplateParameters(), 1202 false, TPL_TemplateMatch) || 1203 !Context.hasSameType(Old->getDeclaredReturnType(), 1204 New->getDeclaredReturnType()))) 1205 return true; 1206 1207 // If the function is a class member, its signature includes the 1208 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1209 // 1210 // As part of this, also check whether one of the member functions 1211 // is static, in which case they are not overloads (C++ 1212 // 13.1p2). While not part of the definition of the signature, 1213 // this check is important to determine whether these functions 1214 // can be overloaded. 1215 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1216 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1217 if (OldMethod && NewMethod && 1218 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1219 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1220 if (!UseMemberUsingDeclRules && 1221 (OldMethod->getRefQualifier() == RQ_None || 1222 NewMethod->getRefQualifier() == RQ_None)) { 1223 // C++0x [over.load]p2: 1224 // - Member function declarations with the same name and the same 1225 // parameter-type-list as well as member function template 1226 // declarations with the same name, the same parameter-type-list, and 1227 // the same template parameter lists cannot be overloaded if any of 1228 // them, but not all, have a ref-qualifier (8.3.5). 1229 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1230 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1231 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1232 } 1233 return true; 1234 } 1235 1236 // We may not have applied the implicit const for a constexpr member 1237 // function yet (because we haven't yet resolved whether this is a static 1238 // or non-static member function). Add it now, on the assumption that this 1239 // is a redeclaration of OldMethod. 1240 auto OldQuals = OldMethod->getMethodQualifiers(); 1241 auto NewQuals = NewMethod->getMethodQualifiers(); 1242 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1243 !isa<CXXConstructorDecl>(NewMethod)) 1244 NewQuals.addConst(); 1245 // We do not allow overloading based off of '__restrict'. 1246 OldQuals.removeRestrict(); 1247 NewQuals.removeRestrict(); 1248 if (OldQuals != NewQuals) 1249 return true; 1250 } 1251 1252 // Though pass_object_size is placed on parameters and takes an argument, we 1253 // consider it to be a function-level modifier for the sake of function 1254 // identity. Either the function has one or more parameters with 1255 // pass_object_size or it doesn't. 1256 if (functionHasPassObjectSizeParams(New) != 1257 functionHasPassObjectSizeParams(Old)) 1258 return true; 1259 1260 // enable_if attributes are an order-sensitive part of the signature. 1261 for (specific_attr_iterator<EnableIfAttr> 1262 NewI = New->specific_attr_begin<EnableIfAttr>(), 1263 NewE = New->specific_attr_end<EnableIfAttr>(), 1264 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1265 OldE = Old->specific_attr_end<EnableIfAttr>(); 1266 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1267 if (NewI == NewE || OldI == OldE) 1268 return true; 1269 llvm::FoldingSetNodeID NewID, OldID; 1270 NewI->getCond()->Profile(NewID, Context, true); 1271 OldI->getCond()->Profile(OldID, Context, true); 1272 if (NewID != OldID) 1273 return true; 1274 } 1275 1276 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1277 // Don't allow overloading of destructors. (In theory we could, but it 1278 // would be a giant change to clang.) 1279 if (!isa<CXXDestructorDecl>(New)) { 1280 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1281 OldTarget = IdentifyCUDATarget(Old); 1282 if (NewTarget != CFT_InvalidTarget) { 1283 assert((OldTarget != CFT_InvalidTarget) && 1284 "Unexpected invalid target."); 1285 1286 // Allow overloading of functions with same signature and different CUDA 1287 // target attributes. 1288 if (NewTarget != OldTarget) 1289 return true; 1290 } 1291 } 1292 } 1293 1294 if (ConsiderRequiresClauses) { 1295 Expr *NewRC = New->getTrailingRequiresClause(), 1296 *OldRC = Old->getTrailingRequiresClause(); 1297 if ((NewRC != nullptr) != (OldRC != nullptr)) 1298 // RC are most certainly different - these are overloads. 1299 return true; 1300 1301 if (NewRC) { 1302 llvm::FoldingSetNodeID NewID, OldID; 1303 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1304 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1305 if (NewID != OldID) 1306 // RCs are not equivalent - these are overloads. 1307 return true; 1308 } 1309 } 1310 1311 // The signatures match; this is not an overload. 1312 return false; 1313 } 1314 1315 /// Tries a user-defined conversion from From to ToType. 1316 /// 1317 /// Produces an implicit conversion sequence for when a standard conversion 1318 /// is not an option. See TryImplicitConversion for more information. 1319 static ImplicitConversionSequence 1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1321 bool SuppressUserConversions, 1322 AllowedExplicit AllowExplicit, 1323 bool InOverloadResolution, 1324 bool CStyle, 1325 bool AllowObjCWritebackConversion, 1326 bool AllowObjCConversionOnExplicit) { 1327 ImplicitConversionSequence ICS; 1328 1329 if (SuppressUserConversions) { 1330 // We're not in the case above, so there is no conversion that 1331 // we can perform. 1332 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1333 return ICS; 1334 } 1335 1336 // Attempt user-defined conversion. 1337 OverloadCandidateSet Conversions(From->getExprLoc(), 1338 OverloadCandidateSet::CSK_Normal); 1339 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1340 Conversions, AllowExplicit, 1341 AllowObjCConversionOnExplicit)) { 1342 case OR_Success: 1343 case OR_Deleted: 1344 ICS.setUserDefined(); 1345 // C++ [over.ics.user]p4: 1346 // A conversion of an expression of class type to the same class 1347 // type is given Exact Match rank, and a conversion of an 1348 // expression of class type to a base class of that type is 1349 // given Conversion rank, in spite of the fact that a copy 1350 // constructor (i.e., a user-defined conversion function) is 1351 // called for those cases. 1352 if (CXXConstructorDecl *Constructor 1353 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1354 QualType FromCanon 1355 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1356 QualType ToCanon 1357 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1358 if (Constructor->isCopyConstructor() && 1359 (FromCanon == ToCanon || 1360 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1361 // Turn this into a "standard" conversion sequence, so that it 1362 // gets ranked with standard conversion sequences. 1363 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1364 ICS.setStandard(); 1365 ICS.Standard.setAsIdentityConversion(); 1366 ICS.Standard.setFromType(From->getType()); 1367 ICS.Standard.setAllToTypes(ToType); 1368 ICS.Standard.CopyConstructor = Constructor; 1369 ICS.Standard.FoundCopyConstructor = Found; 1370 if (ToCanon != FromCanon) 1371 ICS.Standard.Second = ICK_Derived_To_Base; 1372 } 1373 } 1374 break; 1375 1376 case OR_Ambiguous: 1377 ICS.setAmbiguous(); 1378 ICS.Ambiguous.setFromType(From->getType()); 1379 ICS.Ambiguous.setToType(ToType); 1380 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1381 Cand != Conversions.end(); ++Cand) 1382 if (Cand->Best) 1383 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1384 break; 1385 1386 // Fall through. 1387 case OR_No_Viable_Function: 1388 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1389 break; 1390 } 1391 1392 return ICS; 1393 } 1394 1395 /// TryImplicitConversion - Attempt to perform an implicit conversion 1396 /// from the given expression (Expr) to the given type (ToType). This 1397 /// function returns an implicit conversion sequence that can be used 1398 /// to perform the initialization. Given 1399 /// 1400 /// void f(float f); 1401 /// void g(int i) { f(i); } 1402 /// 1403 /// this routine would produce an implicit conversion sequence to 1404 /// describe the initialization of f from i, which will be a standard 1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1407 // 1408 /// Note that this routine only determines how the conversion can be 1409 /// performed; it does not actually perform the conversion. As such, 1410 /// it will not produce any diagnostics if no conversion is available, 1411 /// but will instead return an implicit conversion sequence of kind 1412 /// "BadConversion". 1413 /// 1414 /// If @p SuppressUserConversions, then user-defined conversions are 1415 /// not permitted. 1416 /// If @p AllowExplicit, then explicit user-defined conversions are 1417 /// permitted. 1418 /// 1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1420 /// writeback conversion, which allows __autoreleasing id* parameters to 1421 /// be initialized with __strong id* or __weak id* arguments. 1422 static ImplicitConversionSequence 1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1424 bool SuppressUserConversions, 1425 AllowedExplicit AllowExplicit, 1426 bool InOverloadResolution, 1427 bool CStyle, 1428 bool AllowObjCWritebackConversion, 1429 bool AllowObjCConversionOnExplicit) { 1430 ImplicitConversionSequence ICS; 1431 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1432 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1433 ICS.setStandard(); 1434 return ICS; 1435 } 1436 1437 if (!S.getLangOpts().CPlusPlus) { 1438 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1439 return ICS; 1440 } 1441 1442 // C++ [over.ics.user]p4: 1443 // A conversion of an expression of class type to the same class 1444 // type is given Exact Match rank, and a conversion of an 1445 // expression of class type to a base class of that type is 1446 // given Conversion rank, in spite of the fact that a copy/move 1447 // constructor (i.e., a user-defined conversion function) is 1448 // called for those cases. 1449 QualType FromType = From->getType(); 1450 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1451 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1452 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1453 ICS.setStandard(); 1454 ICS.Standard.setAsIdentityConversion(); 1455 ICS.Standard.setFromType(FromType); 1456 ICS.Standard.setAllToTypes(ToType); 1457 1458 // We don't actually check at this point whether there is a valid 1459 // copy/move constructor, since overloading just assumes that it 1460 // exists. When we actually perform initialization, we'll find the 1461 // appropriate constructor to copy the returned object, if needed. 1462 ICS.Standard.CopyConstructor = nullptr; 1463 1464 // Determine whether this is considered a derived-to-base conversion. 1465 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1466 ICS.Standard.Second = ICK_Derived_To_Base; 1467 1468 return ICS; 1469 } 1470 1471 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1472 AllowExplicit, InOverloadResolution, CStyle, 1473 AllowObjCWritebackConversion, 1474 AllowObjCConversionOnExplicit); 1475 } 1476 1477 ImplicitConversionSequence 1478 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1479 bool SuppressUserConversions, 1480 AllowedExplicit AllowExplicit, 1481 bool InOverloadResolution, 1482 bool CStyle, 1483 bool AllowObjCWritebackConversion) { 1484 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1485 AllowExplicit, InOverloadResolution, CStyle, 1486 AllowObjCWritebackConversion, 1487 /*AllowObjCConversionOnExplicit=*/false); 1488 } 1489 1490 /// PerformImplicitConversion - Perform an implicit conversion of the 1491 /// expression From to the type ToType. Returns the 1492 /// converted expression. Flavor is the kind of conversion we're 1493 /// performing, used in the error message. If @p AllowExplicit, 1494 /// explicit user-defined conversions are permitted. 1495 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, 1497 bool AllowExplicit) { 1498 if (checkPlaceholderForOverload(*this, From)) 1499 return ExprError(); 1500 1501 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1502 bool AllowObjCWritebackConversion 1503 = getLangOpts().ObjCAutoRefCount && 1504 (Action == AA_Passing || Action == AA_Sending); 1505 if (getLangOpts().ObjC) 1506 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1507 From->getType(), From); 1508 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1509 *this, From, ToType, 1510 /*SuppressUserConversions=*/false, 1511 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1512 /*InOverloadResolution=*/false, 1513 /*CStyle=*/false, AllowObjCWritebackConversion, 1514 /*AllowObjCConversionOnExplicit=*/false); 1515 return PerformImplicitConversion(From, ToType, ICS, Action); 1516 } 1517 1518 /// Determine whether the conversion from FromType to ToType is a valid 1519 /// conversion that strips "noexcept" or "noreturn" off the nested function 1520 /// type. 1521 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1522 QualType &ResultTy) { 1523 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1524 return false; 1525 1526 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1527 // or F(t noexcept) -> F(t) 1528 // where F adds one of the following at most once: 1529 // - a pointer 1530 // - a member pointer 1531 // - a block pointer 1532 // Changes here need matching changes in FindCompositePointerType. 1533 CanQualType CanTo = Context.getCanonicalType(ToType); 1534 CanQualType CanFrom = Context.getCanonicalType(FromType); 1535 Type::TypeClass TyClass = CanTo->getTypeClass(); 1536 if (TyClass != CanFrom->getTypeClass()) return false; 1537 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1538 if (TyClass == Type::Pointer) { 1539 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1540 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1541 } else if (TyClass == Type::BlockPointer) { 1542 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1543 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1544 } else if (TyClass == Type::MemberPointer) { 1545 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1546 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1547 // A function pointer conversion cannot change the class of the function. 1548 if (ToMPT->getClass() != FromMPT->getClass()) 1549 return false; 1550 CanTo = ToMPT->getPointeeType(); 1551 CanFrom = FromMPT->getPointeeType(); 1552 } else { 1553 return false; 1554 } 1555 1556 TyClass = CanTo->getTypeClass(); 1557 if (TyClass != CanFrom->getTypeClass()) return false; 1558 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1559 return false; 1560 } 1561 1562 const auto *FromFn = cast<FunctionType>(CanFrom); 1563 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1564 1565 const auto *ToFn = cast<FunctionType>(CanTo); 1566 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1567 1568 bool Changed = false; 1569 1570 // Drop 'noreturn' if not present in target type. 1571 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1572 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1573 Changed = true; 1574 } 1575 1576 // Drop 'noexcept' if not present in target type. 1577 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1578 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1579 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1580 FromFn = cast<FunctionType>( 1581 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1582 EST_None) 1583 .getTypePtr()); 1584 Changed = true; 1585 } 1586 1587 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1588 // only if the ExtParameterInfo lists of the two function prototypes can be 1589 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1590 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1591 bool CanUseToFPT, CanUseFromFPT; 1592 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1593 CanUseFromFPT, NewParamInfos) && 1594 CanUseToFPT && !CanUseFromFPT) { 1595 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1596 ExtInfo.ExtParameterInfos = 1597 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1598 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1599 FromFPT->getParamTypes(), ExtInfo); 1600 FromFn = QT->getAs<FunctionType>(); 1601 Changed = true; 1602 } 1603 } 1604 1605 if (!Changed) 1606 return false; 1607 1608 assert(QualType(FromFn, 0).isCanonical()); 1609 if (QualType(FromFn, 0) != CanTo) return false; 1610 1611 ResultTy = ToType; 1612 return true; 1613 } 1614 1615 /// Determine whether the conversion from FromType to ToType is a valid 1616 /// vector conversion. 1617 /// 1618 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1619 /// conversion. 1620 static bool IsVectorConversion(Sema &S, QualType FromType, 1621 QualType ToType, ImplicitConversionKind &ICK) { 1622 // We need at least one of these types to be a vector type to have a vector 1623 // conversion. 1624 if (!ToType->isVectorType() && !FromType->isVectorType()) 1625 return false; 1626 1627 // Identical types require no conversions. 1628 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1629 return false; 1630 1631 // There are no conversions between extended vector types, only identity. 1632 if (ToType->isExtVectorType()) { 1633 // There are no conversions between extended vector types other than the 1634 // identity conversion. 1635 if (FromType->isExtVectorType()) 1636 return false; 1637 1638 // Vector splat from any arithmetic type to a vector. 1639 if (FromType->isArithmeticType()) { 1640 ICK = ICK_Vector_Splat; 1641 return true; 1642 } 1643 } 1644 1645 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1646 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1647 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1648 ICK = ICK_SVE_Vector_Conversion; 1649 return true; 1650 } 1651 1652 // We can perform the conversion between vector types in the following cases: 1653 // 1)vector types are equivalent AltiVec and GCC vector types 1654 // 2)lax vector conversions are permitted and the vector types are of the 1655 // same size 1656 // 3)the destination type does not have the ARM MVE strict-polymorphism 1657 // attribute, which inhibits lax vector conversion for overload resolution 1658 // only 1659 if (ToType->isVectorType() && FromType->isVectorType()) { 1660 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1661 (S.isLaxVectorConversion(FromType, ToType) && 1662 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1663 ICK = ICK_Vector_Conversion; 1664 return true; 1665 } 1666 } 1667 1668 return false; 1669 } 1670 1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1672 bool InOverloadResolution, 1673 StandardConversionSequence &SCS, 1674 bool CStyle); 1675 1676 /// IsStandardConversion - Determines whether there is a standard 1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1678 /// expression From to the type ToType. Standard conversion sequences 1679 /// only consider non-class types; for conversions that involve class 1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1681 /// contain the standard conversion sequence required to perform this 1682 /// conversion and this routine will return true. Otherwise, this 1683 /// routine will return false and the value of SCS is unspecified. 1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1685 bool InOverloadResolution, 1686 StandardConversionSequence &SCS, 1687 bool CStyle, 1688 bool AllowObjCWritebackConversion) { 1689 QualType FromType = From->getType(); 1690 1691 // Standard conversions (C++ [conv]) 1692 SCS.setAsIdentityConversion(); 1693 SCS.IncompatibleObjC = false; 1694 SCS.setFromType(FromType); 1695 SCS.CopyConstructor = nullptr; 1696 1697 // There are no standard conversions for class types in C++, so 1698 // abort early. When overloading in C, however, we do permit them. 1699 if (S.getLangOpts().CPlusPlus && 1700 (FromType->isRecordType() || ToType->isRecordType())) 1701 return false; 1702 1703 // The first conversion can be an lvalue-to-rvalue conversion, 1704 // array-to-pointer conversion, or function-to-pointer conversion 1705 // (C++ 4p1). 1706 1707 if (FromType == S.Context.OverloadTy) { 1708 DeclAccessPair AccessPair; 1709 if (FunctionDecl *Fn 1710 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1711 AccessPair)) { 1712 // We were able to resolve the address of the overloaded function, 1713 // so we can convert to the type of that function. 1714 FromType = Fn->getType(); 1715 SCS.setFromType(FromType); 1716 1717 // we can sometimes resolve &foo<int> regardless of ToType, so check 1718 // if the type matches (identity) or we are converting to bool 1719 if (!S.Context.hasSameUnqualifiedType( 1720 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1721 QualType resultTy; 1722 // if the function type matches except for [[noreturn]], it's ok 1723 if (!S.IsFunctionConversion(FromType, 1724 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1725 // otherwise, only a boolean conversion is standard 1726 if (!ToType->isBooleanType()) 1727 return false; 1728 } 1729 1730 // Check if the "from" expression is taking the address of an overloaded 1731 // function and recompute the FromType accordingly. Take advantage of the 1732 // fact that non-static member functions *must* have such an address-of 1733 // expression. 1734 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1735 if (Method && !Method->isStatic()) { 1736 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1737 "Non-unary operator on non-static member address"); 1738 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1739 == UO_AddrOf && 1740 "Non-address-of operator on non-static member address"); 1741 const Type *ClassType 1742 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1743 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1744 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1745 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1746 UO_AddrOf && 1747 "Non-address-of operator for overloaded function expression"); 1748 FromType = S.Context.getPointerType(FromType); 1749 } 1750 1751 // Check that we've computed the proper type after overload resolution. 1752 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1753 // be calling it from within an NDEBUG block. 1754 assert(S.Context.hasSameType( 1755 FromType, 1756 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1757 } else { 1758 return false; 1759 } 1760 } 1761 // Lvalue-to-rvalue conversion (C++11 4.1): 1762 // A glvalue (3.10) of a non-function, non-array type T can 1763 // be converted to a prvalue. 1764 bool argIsLValue = From->isGLValue(); 1765 if (argIsLValue && 1766 !FromType->isFunctionType() && !FromType->isArrayType() && 1767 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1768 SCS.First = ICK_Lvalue_To_Rvalue; 1769 1770 // C11 6.3.2.1p2: 1771 // ... if the lvalue has atomic type, the value has the non-atomic version 1772 // of the type of the lvalue ... 1773 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1774 FromType = Atomic->getValueType(); 1775 1776 // If T is a non-class type, the type of the rvalue is the 1777 // cv-unqualified version of T. Otherwise, the type of the rvalue 1778 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1779 // just strip the qualifiers because they don't matter. 1780 FromType = FromType.getUnqualifiedType(); 1781 } else if (FromType->isArrayType()) { 1782 // Array-to-pointer conversion (C++ 4.2) 1783 SCS.First = ICK_Array_To_Pointer; 1784 1785 // An lvalue or rvalue of type "array of N T" or "array of unknown 1786 // bound of T" can be converted to an rvalue of type "pointer to 1787 // T" (C++ 4.2p1). 1788 FromType = S.Context.getArrayDecayedType(FromType); 1789 1790 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1791 // This conversion is deprecated in C++03 (D.4) 1792 SCS.DeprecatedStringLiteralToCharPtr = true; 1793 1794 // For the purpose of ranking in overload resolution 1795 // (13.3.3.1.1), this conversion is considered an 1796 // array-to-pointer conversion followed by a qualification 1797 // conversion (4.4). (C++ 4.2p2) 1798 SCS.Second = ICK_Identity; 1799 SCS.Third = ICK_Qualification; 1800 SCS.QualificationIncludesObjCLifetime = false; 1801 SCS.setAllToTypes(FromType); 1802 return true; 1803 } 1804 } else if (FromType->isFunctionType() && argIsLValue) { 1805 // Function-to-pointer conversion (C++ 4.3). 1806 SCS.First = ICK_Function_To_Pointer; 1807 1808 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1809 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1810 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1811 return false; 1812 1813 // An lvalue of function type T can be converted to an rvalue of 1814 // type "pointer to T." The result is a pointer to the 1815 // function. (C++ 4.3p1). 1816 FromType = S.Context.getPointerType(FromType); 1817 } else { 1818 // We don't require any conversions for the first step. 1819 SCS.First = ICK_Identity; 1820 } 1821 SCS.setToType(0, FromType); 1822 1823 // The second conversion can be an integral promotion, floating 1824 // point promotion, integral conversion, floating point conversion, 1825 // floating-integral conversion, pointer conversion, 1826 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1827 // For overloading in C, this can also be a "compatible-type" 1828 // conversion. 1829 bool IncompatibleObjC = false; 1830 ImplicitConversionKind SecondICK = ICK_Identity; 1831 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1832 // The unqualified versions of the types are the same: there's no 1833 // conversion to do. 1834 SCS.Second = ICK_Identity; 1835 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1836 // Integral promotion (C++ 4.5). 1837 SCS.Second = ICK_Integral_Promotion; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1840 // Floating point promotion (C++ 4.6). 1841 SCS.Second = ICK_Floating_Promotion; 1842 FromType = ToType.getUnqualifiedType(); 1843 } else if (S.IsComplexPromotion(FromType, ToType)) { 1844 // Complex promotion (Clang extension) 1845 SCS.Second = ICK_Complex_Promotion; 1846 FromType = ToType.getUnqualifiedType(); 1847 } else if (ToType->isBooleanType() && 1848 (FromType->isArithmeticType() || 1849 FromType->isAnyPointerType() || 1850 FromType->isBlockPointerType() || 1851 FromType->isMemberPointerType())) { 1852 // Boolean conversions (C++ 4.12). 1853 SCS.Second = ICK_Boolean_Conversion; 1854 FromType = S.Context.BoolTy; 1855 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1856 ToType->isIntegralType(S.Context)) { 1857 // Integral conversions (C++ 4.7). 1858 SCS.Second = ICK_Integral_Conversion; 1859 FromType = ToType.getUnqualifiedType(); 1860 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1861 // Complex conversions (C99 6.3.1.6) 1862 SCS.Second = ICK_Complex_Conversion; 1863 FromType = ToType.getUnqualifiedType(); 1864 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1865 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1866 // Complex-real conversions (C99 6.3.1.7) 1867 SCS.Second = ICK_Complex_Real; 1868 FromType = ToType.getUnqualifiedType(); 1869 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1870 // FIXME: disable conversions between long double, __ibm128 and __float128 1871 // if their representation is different until there is back end support 1872 // We of course allow this conversion if long double is really double. 1873 1874 // Conversions between bfloat and other floats are not permitted. 1875 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1876 return false; 1877 1878 // Conversions between IEEE-quad and IBM-extended semantics are not 1879 // permitted. 1880 const llvm::fltSemantics &FromSem = 1881 S.Context.getFloatTypeSemantics(FromType); 1882 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 1883 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 1884 &ToSem == &llvm::APFloat::IEEEquad()) || 1885 (&FromSem == &llvm::APFloat::IEEEquad() && 1886 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 1887 return false; 1888 1889 // Floating point conversions (C++ 4.8). 1890 SCS.Second = ICK_Floating_Conversion; 1891 FromType = ToType.getUnqualifiedType(); 1892 } else if ((FromType->isRealFloatingType() && 1893 ToType->isIntegralType(S.Context)) || 1894 (FromType->isIntegralOrUnscopedEnumerationType() && 1895 ToType->isRealFloatingType())) { 1896 // Conversions between bfloat and int are not permitted. 1897 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1898 return false; 1899 1900 // Floating-integral conversions (C++ 4.9). 1901 SCS.Second = ICK_Floating_Integral; 1902 FromType = ToType.getUnqualifiedType(); 1903 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1904 SCS.Second = ICK_Block_Pointer_Conversion; 1905 } else if (AllowObjCWritebackConversion && 1906 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1907 SCS.Second = ICK_Writeback_Conversion; 1908 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1909 FromType, IncompatibleObjC)) { 1910 // Pointer conversions (C++ 4.10). 1911 SCS.Second = ICK_Pointer_Conversion; 1912 SCS.IncompatibleObjC = IncompatibleObjC; 1913 FromType = FromType.getUnqualifiedType(); 1914 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1915 InOverloadResolution, FromType)) { 1916 // Pointer to member conversions (4.11). 1917 SCS.Second = ICK_Pointer_Member; 1918 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1919 SCS.Second = SecondICK; 1920 FromType = ToType.getUnqualifiedType(); 1921 } else if (!S.getLangOpts().CPlusPlus && 1922 S.Context.typesAreCompatible(ToType, FromType)) { 1923 // Compatible conversions (Clang extension for C function overloading) 1924 SCS.Second = ICK_Compatible_Conversion; 1925 FromType = ToType.getUnqualifiedType(); 1926 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1927 InOverloadResolution, 1928 SCS, CStyle)) { 1929 SCS.Second = ICK_TransparentUnionConversion; 1930 FromType = ToType; 1931 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1932 CStyle)) { 1933 // tryAtomicConversion has updated the standard conversion sequence 1934 // appropriately. 1935 return true; 1936 } else if (ToType->isEventT() && 1937 From->isIntegerConstantExpr(S.getASTContext()) && 1938 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1939 SCS.Second = ICK_Zero_Event_Conversion; 1940 FromType = ToType; 1941 } else if (ToType->isQueueT() && 1942 From->isIntegerConstantExpr(S.getASTContext()) && 1943 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1944 SCS.Second = ICK_Zero_Queue_Conversion; 1945 FromType = ToType; 1946 } else if (ToType->isSamplerT() && 1947 From->isIntegerConstantExpr(S.getASTContext())) { 1948 SCS.Second = ICK_Compatible_Conversion; 1949 FromType = ToType; 1950 } else { 1951 // No second conversion required. 1952 SCS.Second = ICK_Identity; 1953 } 1954 SCS.setToType(1, FromType); 1955 1956 // The third conversion can be a function pointer conversion or a 1957 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1958 bool ObjCLifetimeConversion; 1959 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1960 // Function pointer conversions (removing 'noexcept') including removal of 1961 // 'noreturn' (Clang extension). 1962 SCS.Third = ICK_Function_Conversion; 1963 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1964 ObjCLifetimeConversion)) { 1965 SCS.Third = ICK_Qualification; 1966 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1967 FromType = ToType; 1968 } else { 1969 // No conversion required 1970 SCS.Third = ICK_Identity; 1971 } 1972 1973 // C++ [over.best.ics]p6: 1974 // [...] Any difference in top-level cv-qualification is 1975 // subsumed by the initialization itself and does not constitute 1976 // a conversion. [...] 1977 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1978 QualType CanonTo = S.Context.getCanonicalType(ToType); 1979 if (CanonFrom.getLocalUnqualifiedType() 1980 == CanonTo.getLocalUnqualifiedType() && 1981 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1982 FromType = ToType; 1983 CanonFrom = CanonTo; 1984 } 1985 1986 SCS.setToType(2, FromType); 1987 1988 if (CanonFrom == CanonTo) 1989 return true; 1990 1991 // If we have not converted the argument type to the parameter type, 1992 // this is a bad conversion sequence, unless we're resolving an overload in C. 1993 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1994 return false; 1995 1996 ExprResult ER = ExprResult{From}; 1997 Sema::AssignConvertType Conv = 1998 S.CheckSingleAssignmentConstraints(ToType, ER, 1999 /*Diagnose=*/false, 2000 /*DiagnoseCFAudited=*/false, 2001 /*ConvertRHS=*/false); 2002 ImplicitConversionKind SecondConv; 2003 switch (Conv) { 2004 case Sema::Compatible: 2005 SecondConv = ICK_C_Only_Conversion; 2006 break; 2007 // For our purposes, discarding qualifiers is just as bad as using an 2008 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2009 // qualifiers, as well. 2010 case Sema::CompatiblePointerDiscardsQualifiers: 2011 case Sema::IncompatiblePointer: 2012 case Sema::IncompatiblePointerSign: 2013 SecondConv = ICK_Incompatible_Pointer_Conversion; 2014 break; 2015 default: 2016 return false; 2017 } 2018 2019 // First can only be an lvalue conversion, so we pretend that this was the 2020 // second conversion. First should already be valid from earlier in the 2021 // function. 2022 SCS.Second = SecondConv; 2023 SCS.setToType(1, ToType); 2024 2025 // Third is Identity, because Second should rank us worse than any other 2026 // conversion. This could also be ICK_Qualification, but it's simpler to just 2027 // lump everything in with the second conversion, and we don't gain anything 2028 // from making this ICK_Qualification. 2029 SCS.Third = ICK_Identity; 2030 SCS.setToType(2, ToType); 2031 return true; 2032 } 2033 2034 static bool 2035 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2036 QualType &ToType, 2037 bool InOverloadResolution, 2038 StandardConversionSequence &SCS, 2039 bool CStyle) { 2040 2041 const RecordType *UT = ToType->getAsUnionType(); 2042 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2043 return false; 2044 // The field to initialize within the transparent union. 2045 RecordDecl *UD = UT->getDecl(); 2046 // It's compatible if the expression matches any of the fields. 2047 for (const auto *it : UD->fields()) { 2048 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2049 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2050 ToType = it->getType(); 2051 return true; 2052 } 2053 } 2054 return false; 2055 } 2056 2057 /// IsIntegralPromotion - Determines whether the conversion from the 2058 /// expression From (whose potentially-adjusted type is FromType) to 2059 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2060 /// sets PromotedType to the promoted type. 2061 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2062 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2063 // All integers are built-in. 2064 if (!To) { 2065 return false; 2066 } 2067 2068 // An rvalue of type char, signed char, unsigned char, short int, or 2069 // unsigned short int can be converted to an rvalue of type int if 2070 // int can represent all the values of the source type; otherwise, 2071 // the source rvalue can be converted to an rvalue of type unsigned 2072 // int (C++ 4.5p1). 2073 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2074 !FromType->isEnumeralType()) { 2075 if (// We can promote any signed, promotable integer type to an int 2076 (FromType->isSignedIntegerType() || 2077 // We can promote any unsigned integer type whose size is 2078 // less than int to an int. 2079 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2080 return To->getKind() == BuiltinType::Int; 2081 } 2082 2083 return To->getKind() == BuiltinType::UInt; 2084 } 2085 2086 // C++11 [conv.prom]p3: 2087 // A prvalue of an unscoped enumeration type whose underlying type is not 2088 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2089 // following types that can represent all the values of the enumeration 2090 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2091 // unsigned int, long int, unsigned long int, long long int, or unsigned 2092 // long long int. If none of the types in that list can represent all the 2093 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2094 // type can be converted to an rvalue a prvalue of the extended integer type 2095 // with lowest integer conversion rank (4.13) greater than the rank of long 2096 // long in which all the values of the enumeration can be represented. If 2097 // there are two such extended types, the signed one is chosen. 2098 // C++11 [conv.prom]p4: 2099 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2100 // can be converted to a prvalue of its underlying type. Moreover, if 2101 // integral promotion can be applied to its underlying type, a prvalue of an 2102 // unscoped enumeration type whose underlying type is fixed can also be 2103 // converted to a prvalue of the promoted underlying type. 2104 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2105 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2106 // provided for a scoped enumeration. 2107 if (FromEnumType->getDecl()->isScoped()) 2108 return false; 2109 2110 // We can perform an integral promotion to the underlying type of the enum, 2111 // even if that's not the promoted type. Note that the check for promoting 2112 // the underlying type is based on the type alone, and does not consider 2113 // the bitfield-ness of the actual source expression. 2114 if (FromEnumType->getDecl()->isFixed()) { 2115 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2116 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2117 IsIntegralPromotion(nullptr, Underlying, ToType); 2118 } 2119 2120 // We have already pre-calculated the promotion type, so this is trivial. 2121 if (ToType->isIntegerType() && 2122 isCompleteType(From->getBeginLoc(), FromType)) 2123 return Context.hasSameUnqualifiedType( 2124 ToType, FromEnumType->getDecl()->getPromotionType()); 2125 2126 // C++ [conv.prom]p5: 2127 // If the bit-field has an enumerated type, it is treated as any other 2128 // value of that type for promotion purposes. 2129 // 2130 // ... so do not fall through into the bit-field checks below in C++. 2131 if (getLangOpts().CPlusPlus) 2132 return false; 2133 } 2134 2135 // C++0x [conv.prom]p2: 2136 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2137 // to an rvalue a prvalue of the first of the following types that can 2138 // represent all the values of its underlying type: int, unsigned int, 2139 // long int, unsigned long int, long long int, or unsigned long long int. 2140 // If none of the types in that list can represent all the values of its 2141 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2142 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2143 // type. 2144 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2145 ToType->isIntegerType()) { 2146 // Determine whether the type we're converting from is signed or 2147 // unsigned. 2148 bool FromIsSigned = FromType->isSignedIntegerType(); 2149 uint64_t FromSize = Context.getTypeSize(FromType); 2150 2151 // The types we'll try to promote to, in the appropriate 2152 // order. Try each of these types. 2153 QualType PromoteTypes[6] = { 2154 Context.IntTy, Context.UnsignedIntTy, 2155 Context.LongTy, Context.UnsignedLongTy , 2156 Context.LongLongTy, Context.UnsignedLongLongTy 2157 }; 2158 for (int Idx = 0; Idx < 6; ++Idx) { 2159 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2160 if (FromSize < ToSize || 2161 (FromSize == ToSize && 2162 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2163 // We found the type that we can promote to. If this is the 2164 // type we wanted, we have a promotion. Otherwise, no 2165 // promotion. 2166 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2167 } 2168 } 2169 } 2170 2171 // An rvalue for an integral bit-field (9.6) can be converted to an 2172 // rvalue of type int if int can represent all the values of the 2173 // bit-field; otherwise, it can be converted to unsigned int if 2174 // unsigned int can represent all the values of the bit-field. If 2175 // the bit-field is larger yet, no integral promotion applies to 2176 // it. If the bit-field has an enumerated type, it is treated as any 2177 // other value of that type for promotion purposes (C++ 4.5p3). 2178 // FIXME: We should delay checking of bit-fields until we actually perform the 2179 // conversion. 2180 // 2181 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2182 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2183 // bit-fields and those whose underlying type is larger than int) for GCC 2184 // compatibility. 2185 if (From) { 2186 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2187 Optional<llvm::APSInt> BitWidth; 2188 if (FromType->isIntegralType(Context) && 2189 (BitWidth = 2190 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2191 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2192 ToSize = Context.getTypeSize(ToType); 2193 2194 // Are we promoting to an int from a bitfield that fits in an int? 2195 if (*BitWidth < ToSize || 2196 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2197 return To->getKind() == BuiltinType::Int; 2198 } 2199 2200 // Are we promoting to an unsigned int from an unsigned bitfield 2201 // that fits into an unsigned int? 2202 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2203 return To->getKind() == BuiltinType::UInt; 2204 } 2205 2206 return false; 2207 } 2208 } 2209 } 2210 2211 // An rvalue of type bool can be converted to an rvalue of type int, 2212 // with false becoming zero and true becoming one (C++ 4.5p4). 2213 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2214 return true; 2215 } 2216 2217 return false; 2218 } 2219 2220 /// IsFloatingPointPromotion - Determines whether the conversion from 2221 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2222 /// returns true and sets PromotedType to the promoted type. 2223 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2226 /// An rvalue of type float can be converted to an rvalue of type 2227 /// double. (C++ 4.6p1). 2228 if (FromBuiltin->getKind() == BuiltinType::Float && 2229 ToBuiltin->getKind() == BuiltinType::Double) 2230 return true; 2231 2232 // C99 6.3.1.5p1: 2233 // When a float is promoted to double or long double, or a 2234 // double is promoted to long double [...]. 2235 if (!getLangOpts().CPlusPlus && 2236 (FromBuiltin->getKind() == BuiltinType::Float || 2237 FromBuiltin->getKind() == BuiltinType::Double) && 2238 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2239 ToBuiltin->getKind() == BuiltinType::Float128 || 2240 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2241 return true; 2242 2243 // Half can be promoted to float. 2244 if (!getLangOpts().NativeHalfType && 2245 FromBuiltin->getKind() == BuiltinType::Half && 2246 ToBuiltin->getKind() == BuiltinType::Float) 2247 return true; 2248 } 2249 2250 return false; 2251 } 2252 2253 /// Determine if a conversion is a complex promotion. 2254 /// 2255 /// A complex promotion is defined as a complex -> complex conversion 2256 /// where the conversion between the underlying real types is a 2257 /// floating-point or integral promotion. 2258 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2260 if (!FromComplex) 2261 return false; 2262 2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2264 if (!ToComplex) 2265 return false; 2266 2267 return IsFloatingPointPromotion(FromComplex->getElementType(), 2268 ToComplex->getElementType()) || 2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2270 ToComplex->getElementType()); 2271 } 2272 2273 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2274 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2275 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2276 /// if non-empty, will be a pointer to ToType that may or may not have 2277 /// the right set of qualifiers on its pointee. 2278 /// 2279 static QualType 2280 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2281 QualType ToPointee, QualType ToType, 2282 ASTContext &Context, 2283 bool StripObjCLifetime = false) { 2284 assert((FromPtr->getTypeClass() == Type::Pointer || 2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2286 "Invalid similarly-qualified pointer type"); 2287 2288 /// Conversions to 'id' subsume cv-qualifier conversions. 2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2290 return ToType.getUnqualifiedType(); 2291 2292 QualType CanonFromPointee 2293 = Context.getCanonicalType(FromPtr->getPointeeType()); 2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2295 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2296 2297 if (StripObjCLifetime) 2298 Quals.removeObjCLifetime(); 2299 2300 // Exact qualifier match -> return the pointer type we're converting to. 2301 if (CanonToPointee.getLocalQualifiers() == Quals) { 2302 // ToType is exactly what we need. Return it. 2303 if (!ToType.isNull()) 2304 return ToType.getUnqualifiedType(); 2305 2306 // Build a pointer to ToPointee. It has the right qualifiers 2307 // already. 2308 if (isa<ObjCObjectPointerType>(ToType)) 2309 return Context.getObjCObjectPointerType(ToPointee); 2310 return Context.getPointerType(ToPointee); 2311 } 2312 2313 // Just build a canonical type that has the right qualifiers. 2314 QualType QualifiedCanonToPointee 2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2316 2317 if (isa<ObjCObjectPointerType>(ToType)) 2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2319 return Context.getPointerType(QualifiedCanonToPointee); 2320 } 2321 2322 static bool isNullPointerConstantForConversion(Expr *Expr, 2323 bool InOverloadResolution, 2324 ASTContext &Context) { 2325 // Handle value-dependent integral null pointer constants correctly. 2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2329 return !InOverloadResolution; 2330 2331 return Expr->isNullPointerConstant(Context, 2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2333 : Expr::NPC_ValueDependentIsNull); 2334 } 2335 2336 /// IsPointerConversion - Determines whether the conversion of the 2337 /// expression From, which has the (possibly adjusted) type FromType, 2338 /// can be converted to the type ToType via a pointer conversion (C++ 2339 /// 4.10). If so, returns true and places the converted type (that 2340 /// might differ from ToType in its cv-qualifiers at some level) into 2341 /// ConvertedType. 2342 /// 2343 /// This routine also supports conversions to and from block pointers 2344 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2345 /// pointers to interfaces. FIXME: Once we've determined the 2346 /// appropriate overloading rules for Objective-C, we may want to 2347 /// split the Objective-C checks into a different routine; however, 2348 /// GCC seems to consider all of these conversions to be pointer 2349 /// conversions, so for now they live here. IncompatibleObjC will be 2350 /// set if the conversion is an allowed Objective-C conversion that 2351 /// should result in a warning. 2352 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2353 bool InOverloadResolution, 2354 QualType& ConvertedType, 2355 bool &IncompatibleObjC) { 2356 IncompatibleObjC = false; 2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2358 IncompatibleObjC)) 2359 return true; 2360 2361 // Conversion from a null pointer constant to any Objective-C pointer type. 2362 if (ToType->isObjCObjectPointerType() && 2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2364 ConvertedType = ToType; 2365 return true; 2366 } 2367 2368 // Blocks: Block pointers can be converted to void*. 2369 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2371 ConvertedType = ToType; 2372 return true; 2373 } 2374 // Blocks: A null pointer constant can be converted to a block 2375 // pointer type. 2376 if (ToType->isBlockPointerType() && 2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2378 ConvertedType = ToType; 2379 return true; 2380 } 2381 2382 // If the left-hand-side is nullptr_t, the right side can be a null 2383 // pointer constant. 2384 if (ToType->isNullPtrType() && 2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2386 ConvertedType = ToType; 2387 return true; 2388 } 2389 2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2391 if (!ToTypePtr) 2392 return false; 2393 2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2396 ConvertedType = ToType; 2397 return true; 2398 } 2399 2400 // Beyond this point, both types need to be pointers 2401 // , including objective-c pointers. 2402 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2404 !getLangOpts().ObjCAutoRefCount) { 2405 ConvertedType = BuildSimilarlyQualifiedPointerType( 2406 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2407 Context); 2408 return true; 2409 } 2410 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2411 if (!FromTypePtr) 2412 return false; 2413 2414 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2415 2416 // If the unqualified pointee types are the same, this can't be a 2417 // pointer conversion, so don't do all of the work below. 2418 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2419 return false; 2420 2421 // An rvalue of type "pointer to cv T," where T is an object type, 2422 // can be converted to an rvalue of type "pointer to cv void" (C++ 2423 // 4.10p2). 2424 if (FromPointeeType->isIncompleteOrObjectType() && 2425 ToPointeeType->isVoidType()) { 2426 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2427 ToPointeeType, 2428 ToType, Context, 2429 /*StripObjCLifetime=*/true); 2430 return true; 2431 } 2432 2433 // MSVC allows implicit function to void* type conversion. 2434 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2435 ToPointeeType->isVoidType()) { 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2437 ToPointeeType, 2438 ToType, Context); 2439 return true; 2440 } 2441 2442 // When we're overloading in C, we allow a special kind of pointer 2443 // conversion for compatible-but-not-identical pointee types. 2444 if (!getLangOpts().CPlusPlus && 2445 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2446 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2447 ToPointeeType, 2448 ToType, Context); 2449 return true; 2450 } 2451 2452 // C++ [conv.ptr]p3: 2453 // 2454 // An rvalue of type "pointer to cv D," where D is a class type, 2455 // can be converted to an rvalue of type "pointer to cv B," where 2456 // B is a base class (clause 10) of D. If B is an inaccessible 2457 // (clause 11) or ambiguous (10.2) base class of D, a program that 2458 // necessitates this conversion is ill-formed. The result of the 2459 // conversion is a pointer to the base class sub-object of the 2460 // derived class object. The null pointer value is converted to 2461 // the null pointer value of the destination type. 2462 // 2463 // Note that we do not check for ambiguity or inaccessibility 2464 // here. That is handled by CheckPointerConversion. 2465 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2466 ToPointeeType->isRecordType() && 2467 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2468 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2469 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2470 ToPointeeType, 2471 ToType, Context); 2472 return true; 2473 } 2474 2475 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2476 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2477 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2478 ToPointeeType, 2479 ToType, Context); 2480 return true; 2481 } 2482 2483 return false; 2484 } 2485 2486 /// Adopt the given qualifiers for the given type. 2487 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2488 Qualifiers TQs = T.getQualifiers(); 2489 2490 // Check whether qualifiers already match. 2491 if (TQs == Qs) 2492 return T; 2493 2494 if (Qs.compatiblyIncludes(TQs)) 2495 return Context.getQualifiedType(T, Qs); 2496 2497 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2498 } 2499 2500 /// isObjCPointerConversion - Determines whether this is an 2501 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2502 /// with the same arguments and return values. 2503 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2504 QualType& ConvertedType, 2505 bool &IncompatibleObjC) { 2506 if (!getLangOpts().ObjC) 2507 return false; 2508 2509 // The set of qualifiers on the type we're converting from. 2510 Qualifiers FromQualifiers = FromType.getQualifiers(); 2511 2512 // First, we handle all conversions on ObjC object pointer types. 2513 const ObjCObjectPointerType* ToObjCPtr = 2514 ToType->getAs<ObjCObjectPointerType>(); 2515 const ObjCObjectPointerType *FromObjCPtr = 2516 FromType->getAs<ObjCObjectPointerType>(); 2517 2518 if (ToObjCPtr && FromObjCPtr) { 2519 // If the pointee types are the same (ignoring qualifications), 2520 // then this is not a pointer conversion. 2521 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2522 FromObjCPtr->getPointeeType())) 2523 return false; 2524 2525 // Conversion between Objective-C pointers. 2526 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2527 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2528 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2529 if (getLangOpts().CPlusPlus && LHS && RHS && 2530 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2531 FromObjCPtr->getPointeeType())) 2532 return false; 2533 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2534 ToObjCPtr->getPointeeType(), 2535 ToType, Context); 2536 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2537 return true; 2538 } 2539 2540 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2541 // Okay: this is some kind of implicit downcast of Objective-C 2542 // interfaces, which is permitted. However, we're going to 2543 // complain about it. 2544 IncompatibleObjC = true; 2545 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2546 ToObjCPtr->getPointeeType(), 2547 ToType, Context); 2548 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2549 return true; 2550 } 2551 } 2552 // Beyond this point, both types need to be C pointers or block pointers. 2553 QualType ToPointeeType; 2554 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2555 ToPointeeType = ToCPtr->getPointeeType(); 2556 else if (const BlockPointerType *ToBlockPtr = 2557 ToType->getAs<BlockPointerType>()) { 2558 // Objective C++: We're able to convert from a pointer to any object 2559 // to a block pointer type. 2560 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2561 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2562 return true; 2563 } 2564 ToPointeeType = ToBlockPtr->getPointeeType(); 2565 } 2566 else if (FromType->getAs<BlockPointerType>() && 2567 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2568 // Objective C++: We're able to convert from a block pointer type to a 2569 // pointer to any object. 2570 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2571 return true; 2572 } 2573 else 2574 return false; 2575 2576 QualType FromPointeeType; 2577 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2578 FromPointeeType = FromCPtr->getPointeeType(); 2579 else if (const BlockPointerType *FromBlockPtr = 2580 FromType->getAs<BlockPointerType>()) 2581 FromPointeeType = FromBlockPtr->getPointeeType(); 2582 else 2583 return false; 2584 2585 // If we have pointers to pointers, recursively check whether this 2586 // is an Objective-C conversion. 2587 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2588 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2589 IncompatibleObjC)) { 2590 // We always complain about this conversion. 2591 IncompatibleObjC = true; 2592 ConvertedType = Context.getPointerType(ConvertedType); 2593 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2594 return true; 2595 } 2596 // Allow conversion of pointee being objective-c pointer to another one; 2597 // as in I* to id. 2598 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2599 ToPointeeType->getAs<ObjCObjectPointerType>() && 2600 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2601 IncompatibleObjC)) { 2602 2603 ConvertedType = Context.getPointerType(ConvertedType); 2604 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2605 return true; 2606 } 2607 2608 // If we have pointers to functions or blocks, check whether the only 2609 // differences in the argument and result types are in Objective-C 2610 // pointer conversions. If so, we permit the conversion (but 2611 // complain about it). 2612 const FunctionProtoType *FromFunctionType 2613 = FromPointeeType->getAs<FunctionProtoType>(); 2614 const FunctionProtoType *ToFunctionType 2615 = ToPointeeType->getAs<FunctionProtoType>(); 2616 if (FromFunctionType && ToFunctionType) { 2617 // If the function types are exactly the same, this isn't an 2618 // Objective-C pointer conversion. 2619 if (Context.getCanonicalType(FromPointeeType) 2620 == Context.getCanonicalType(ToPointeeType)) 2621 return false; 2622 2623 // Perform the quick checks that will tell us whether these 2624 // function types are obviously different. 2625 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2626 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2627 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2628 return false; 2629 2630 bool HasObjCConversion = false; 2631 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2632 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2633 // Okay, the types match exactly. Nothing to do. 2634 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2635 ToFunctionType->getReturnType(), 2636 ConvertedType, IncompatibleObjC)) { 2637 // Okay, we have an Objective-C pointer conversion. 2638 HasObjCConversion = true; 2639 } else { 2640 // Function types are too different. Abort. 2641 return false; 2642 } 2643 2644 // Check argument types. 2645 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2646 ArgIdx != NumArgs; ++ArgIdx) { 2647 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2648 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2649 if (Context.getCanonicalType(FromArgType) 2650 == Context.getCanonicalType(ToArgType)) { 2651 // Okay, the types match exactly. Nothing to do. 2652 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2653 ConvertedType, IncompatibleObjC)) { 2654 // Okay, we have an Objective-C pointer conversion. 2655 HasObjCConversion = true; 2656 } else { 2657 // Argument types are too different. Abort. 2658 return false; 2659 } 2660 } 2661 2662 if (HasObjCConversion) { 2663 // We had an Objective-C conversion. Allow this pointer 2664 // conversion, but complain about it. 2665 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2666 IncompatibleObjC = true; 2667 return true; 2668 } 2669 } 2670 2671 return false; 2672 } 2673 2674 /// Determine whether this is an Objective-C writeback conversion, 2675 /// used for parameter passing when performing automatic reference counting. 2676 /// 2677 /// \param FromType The type we're converting form. 2678 /// 2679 /// \param ToType The type we're converting to. 2680 /// 2681 /// \param ConvertedType The type that will be produced after applying 2682 /// this conversion. 2683 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2684 QualType &ConvertedType) { 2685 if (!getLangOpts().ObjCAutoRefCount || 2686 Context.hasSameUnqualifiedType(FromType, ToType)) 2687 return false; 2688 2689 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2690 QualType ToPointee; 2691 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2692 ToPointee = ToPointer->getPointeeType(); 2693 else 2694 return false; 2695 2696 Qualifiers ToQuals = ToPointee.getQualifiers(); 2697 if (!ToPointee->isObjCLifetimeType() || 2698 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2699 !ToQuals.withoutObjCLifetime().empty()) 2700 return false; 2701 2702 // Argument must be a pointer to __strong to __weak. 2703 QualType FromPointee; 2704 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2705 FromPointee = FromPointer->getPointeeType(); 2706 else 2707 return false; 2708 2709 Qualifiers FromQuals = FromPointee.getQualifiers(); 2710 if (!FromPointee->isObjCLifetimeType() || 2711 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2712 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2713 return false; 2714 2715 // Make sure that we have compatible qualifiers. 2716 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2717 if (!ToQuals.compatiblyIncludes(FromQuals)) 2718 return false; 2719 2720 // Remove qualifiers from the pointee type we're converting from; they 2721 // aren't used in the compatibility check belong, and we'll be adding back 2722 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2723 FromPointee = FromPointee.getUnqualifiedType(); 2724 2725 // The unqualified form of the pointee types must be compatible. 2726 ToPointee = ToPointee.getUnqualifiedType(); 2727 bool IncompatibleObjC; 2728 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2729 FromPointee = ToPointee; 2730 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2731 IncompatibleObjC)) 2732 return false; 2733 2734 /// Construct the type we're converting to, which is a pointer to 2735 /// __autoreleasing pointee. 2736 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2737 ConvertedType = Context.getPointerType(FromPointee); 2738 return true; 2739 } 2740 2741 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2742 QualType& ConvertedType) { 2743 QualType ToPointeeType; 2744 if (const BlockPointerType *ToBlockPtr = 2745 ToType->getAs<BlockPointerType>()) 2746 ToPointeeType = ToBlockPtr->getPointeeType(); 2747 else 2748 return false; 2749 2750 QualType FromPointeeType; 2751 if (const BlockPointerType *FromBlockPtr = 2752 FromType->getAs<BlockPointerType>()) 2753 FromPointeeType = FromBlockPtr->getPointeeType(); 2754 else 2755 return false; 2756 // We have pointer to blocks, check whether the only 2757 // differences in the argument and result types are in Objective-C 2758 // pointer conversions. If so, we permit the conversion. 2759 2760 const FunctionProtoType *FromFunctionType 2761 = FromPointeeType->getAs<FunctionProtoType>(); 2762 const FunctionProtoType *ToFunctionType 2763 = ToPointeeType->getAs<FunctionProtoType>(); 2764 2765 if (!FromFunctionType || !ToFunctionType) 2766 return false; 2767 2768 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2769 return true; 2770 2771 // Perform the quick checks that will tell us whether these 2772 // function types are obviously different. 2773 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2774 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2775 return false; 2776 2777 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2778 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2779 if (FromEInfo != ToEInfo) 2780 return false; 2781 2782 bool IncompatibleObjC = false; 2783 if (Context.hasSameType(FromFunctionType->getReturnType(), 2784 ToFunctionType->getReturnType())) { 2785 // Okay, the types match exactly. Nothing to do. 2786 } else { 2787 QualType RHS = FromFunctionType->getReturnType(); 2788 QualType LHS = ToFunctionType->getReturnType(); 2789 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2790 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2791 LHS = LHS.getUnqualifiedType(); 2792 2793 if (Context.hasSameType(RHS,LHS)) { 2794 // OK exact match. 2795 } else if (isObjCPointerConversion(RHS, LHS, 2796 ConvertedType, IncompatibleObjC)) { 2797 if (IncompatibleObjC) 2798 return false; 2799 // Okay, we have an Objective-C pointer conversion. 2800 } 2801 else 2802 return false; 2803 } 2804 2805 // Check argument types. 2806 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2807 ArgIdx != NumArgs; ++ArgIdx) { 2808 IncompatibleObjC = false; 2809 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2810 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2811 if (Context.hasSameType(FromArgType, ToArgType)) { 2812 // Okay, the types match exactly. Nothing to do. 2813 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2814 ConvertedType, IncompatibleObjC)) { 2815 if (IncompatibleObjC) 2816 return false; 2817 // Okay, we have an Objective-C pointer conversion. 2818 } else 2819 // Argument types are too different. Abort. 2820 return false; 2821 } 2822 2823 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2824 bool CanUseToFPT, CanUseFromFPT; 2825 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2826 CanUseToFPT, CanUseFromFPT, 2827 NewParamInfos)) 2828 return false; 2829 2830 ConvertedType = ToType; 2831 return true; 2832 } 2833 2834 enum { 2835 ft_default, 2836 ft_different_class, 2837 ft_parameter_arity, 2838 ft_parameter_mismatch, 2839 ft_return_type, 2840 ft_qualifer_mismatch, 2841 ft_noexcept 2842 }; 2843 2844 /// Attempts to get the FunctionProtoType from a Type. Handles 2845 /// MemberFunctionPointers properly. 2846 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2847 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2848 return FPT; 2849 2850 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2851 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2852 2853 return nullptr; 2854 } 2855 2856 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2857 /// function types. Catches different number of parameter, mismatch in 2858 /// parameter types, and different return types. 2859 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2860 QualType FromType, QualType ToType) { 2861 // If either type is not valid, include no extra info. 2862 if (FromType.isNull() || ToType.isNull()) { 2863 PDiag << ft_default; 2864 return; 2865 } 2866 2867 // Get the function type from the pointers. 2868 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2869 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2870 *ToMember = ToType->castAs<MemberPointerType>(); 2871 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2872 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2873 << QualType(FromMember->getClass(), 0); 2874 return; 2875 } 2876 FromType = FromMember->getPointeeType(); 2877 ToType = ToMember->getPointeeType(); 2878 } 2879 2880 if (FromType->isPointerType()) 2881 FromType = FromType->getPointeeType(); 2882 if (ToType->isPointerType()) 2883 ToType = ToType->getPointeeType(); 2884 2885 // Remove references. 2886 FromType = FromType.getNonReferenceType(); 2887 ToType = ToType.getNonReferenceType(); 2888 2889 // Don't print extra info for non-specialized template functions. 2890 if (FromType->isInstantiationDependentType() && 2891 !FromType->getAs<TemplateSpecializationType>()) { 2892 PDiag << ft_default; 2893 return; 2894 } 2895 2896 // No extra info for same types. 2897 if (Context.hasSameType(FromType, ToType)) { 2898 PDiag << ft_default; 2899 return; 2900 } 2901 2902 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2903 *ToFunction = tryGetFunctionProtoType(ToType); 2904 2905 // Both types need to be function types. 2906 if (!FromFunction || !ToFunction) { 2907 PDiag << ft_default; 2908 return; 2909 } 2910 2911 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2912 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2913 << FromFunction->getNumParams(); 2914 return; 2915 } 2916 2917 // Handle different parameter types. 2918 unsigned ArgPos; 2919 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2920 PDiag << ft_parameter_mismatch << ArgPos + 1 2921 << ToFunction->getParamType(ArgPos) 2922 << FromFunction->getParamType(ArgPos); 2923 return; 2924 } 2925 2926 // Handle different return type. 2927 if (!Context.hasSameType(FromFunction->getReturnType(), 2928 ToFunction->getReturnType())) { 2929 PDiag << ft_return_type << ToFunction->getReturnType() 2930 << FromFunction->getReturnType(); 2931 return; 2932 } 2933 2934 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2935 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2936 << FromFunction->getMethodQuals(); 2937 return; 2938 } 2939 2940 // Handle exception specification differences on canonical type (in C++17 2941 // onwards). 2942 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2943 ->isNothrow() != 2944 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2945 ->isNothrow()) { 2946 PDiag << ft_noexcept; 2947 return; 2948 } 2949 2950 // Unable to find a difference, so add no extra info. 2951 PDiag << ft_default; 2952 } 2953 2954 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2955 /// for equality of their argument types. Caller has already checked that 2956 /// they have same number of arguments. If the parameters are different, 2957 /// ArgPos will have the parameter index of the first different parameter. 2958 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2959 const FunctionProtoType *NewType, 2960 unsigned *ArgPos) { 2961 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2962 N = NewType->param_type_begin(), 2963 E = OldType->param_type_end(); 2964 O && (O != E); ++O, ++N) { 2965 // Ignore address spaces in pointee type. This is to disallow overloading 2966 // on __ptr32/__ptr64 address spaces. 2967 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2968 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2969 2970 if (!Context.hasSameType(Old, New)) { 2971 if (ArgPos) 2972 *ArgPos = O - OldType->param_type_begin(); 2973 return false; 2974 } 2975 } 2976 return true; 2977 } 2978 2979 /// CheckPointerConversion - Check the pointer conversion from the 2980 /// expression From to the type ToType. This routine checks for 2981 /// ambiguous or inaccessible derived-to-base pointer 2982 /// conversions for which IsPointerConversion has already returned 2983 /// true. It returns true and produces a diagnostic if there was an 2984 /// error, or returns false otherwise. 2985 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2986 CastKind &Kind, 2987 CXXCastPath& BasePath, 2988 bool IgnoreBaseAccess, 2989 bool Diagnose) { 2990 QualType FromType = From->getType(); 2991 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2992 2993 Kind = CK_BitCast; 2994 2995 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2996 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2997 Expr::NPCK_ZeroExpression) { 2998 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2999 DiagRuntimeBehavior(From->getExprLoc(), From, 3000 PDiag(diag::warn_impcast_bool_to_null_pointer) 3001 << ToType << From->getSourceRange()); 3002 else if (!isUnevaluatedContext()) 3003 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3004 << ToType << From->getSourceRange(); 3005 } 3006 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3007 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3008 QualType FromPointeeType = FromPtrType->getPointeeType(), 3009 ToPointeeType = ToPtrType->getPointeeType(); 3010 3011 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3012 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3013 // We must have a derived-to-base conversion. Check an 3014 // ambiguous or inaccessible conversion. 3015 unsigned InaccessibleID = 0; 3016 unsigned AmbiguousID = 0; 3017 if (Diagnose) { 3018 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3019 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3020 } 3021 if (CheckDerivedToBaseConversion( 3022 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3023 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3024 &BasePath, IgnoreBaseAccess)) 3025 return true; 3026 3027 // The conversion was successful. 3028 Kind = CK_DerivedToBase; 3029 } 3030 3031 if (Diagnose && !IsCStyleOrFunctionalCast && 3032 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3033 assert(getLangOpts().MSVCCompat && 3034 "this should only be possible with MSVCCompat!"); 3035 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3036 << From->getSourceRange(); 3037 } 3038 } 3039 } else if (const ObjCObjectPointerType *ToPtrType = 3040 ToType->getAs<ObjCObjectPointerType>()) { 3041 if (const ObjCObjectPointerType *FromPtrType = 3042 FromType->getAs<ObjCObjectPointerType>()) { 3043 // Objective-C++ conversions are always okay. 3044 // FIXME: We should have a different class of conversions for the 3045 // Objective-C++ implicit conversions. 3046 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3047 return false; 3048 } else if (FromType->isBlockPointerType()) { 3049 Kind = CK_BlockPointerToObjCPointerCast; 3050 } else { 3051 Kind = CK_CPointerToObjCPointerCast; 3052 } 3053 } else if (ToType->isBlockPointerType()) { 3054 if (!FromType->isBlockPointerType()) 3055 Kind = CK_AnyPointerToBlockPointerCast; 3056 } 3057 3058 // We shouldn't fall into this case unless it's valid for other 3059 // reasons. 3060 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3061 Kind = CK_NullToPointer; 3062 3063 return false; 3064 } 3065 3066 /// IsMemberPointerConversion - Determines whether the conversion of the 3067 /// expression From, which has the (possibly adjusted) type FromType, can be 3068 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3069 /// If so, returns true and places the converted type (that might differ from 3070 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3071 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3072 QualType ToType, 3073 bool InOverloadResolution, 3074 QualType &ConvertedType) { 3075 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3076 if (!ToTypePtr) 3077 return false; 3078 3079 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3080 if (From->isNullPointerConstant(Context, 3081 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3082 : Expr::NPC_ValueDependentIsNull)) { 3083 ConvertedType = ToType; 3084 return true; 3085 } 3086 3087 // Otherwise, both types have to be member pointers. 3088 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3089 if (!FromTypePtr) 3090 return false; 3091 3092 // A pointer to member of B can be converted to a pointer to member of D, 3093 // where D is derived from B (C++ 4.11p2). 3094 QualType FromClass(FromTypePtr->getClass(), 0); 3095 QualType ToClass(ToTypePtr->getClass(), 0); 3096 3097 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3098 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3099 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3100 ToClass.getTypePtr()); 3101 return true; 3102 } 3103 3104 return false; 3105 } 3106 3107 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3108 /// expression From to the type ToType. This routine checks for ambiguous or 3109 /// virtual or inaccessible base-to-derived member pointer conversions 3110 /// for which IsMemberPointerConversion has already returned true. It returns 3111 /// true and produces a diagnostic if there was an error, or returns false 3112 /// otherwise. 3113 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3114 CastKind &Kind, 3115 CXXCastPath &BasePath, 3116 bool IgnoreBaseAccess) { 3117 QualType FromType = From->getType(); 3118 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3119 if (!FromPtrType) { 3120 // This must be a null pointer to member pointer conversion 3121 assert(From->isNullPointerConstant(Context, 3122 Expr::NPC_ValueDependentIsNull) && 3123 "Expr must be null pointer constant!"); 3124 Kind = CK_NullToMemberPointer; 3125 return false; 3126 } 3127 3128 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3129 assert(ToPtrType && "No member pointer cast has a target type " 3130 "that is not a member pointer."); 3131 3132 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3133 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3134 3135 // FIXME: What about dependent types? 3136 assert(FromClass->isRecordType() && "Pointer into non-class."); 3137 assert(ToClass->isRecordType() && "Pointer into non-class."); 3138 3139 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3140 /*DetectVirtual=*/true); 3141 bool DerivationOkay = 3142 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3143 assert(DerivationOkay && 3144 "Should not have been called if derivation isn't OK."); 3145 (void)DerivationOkay; 3146 3147 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3148 getUnqualifiedType())) { 3149 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3150 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3151 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3152 return true; 3153 } 3154 3155 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3156 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3157 << FromClass << ToClass << QualType(VBase, 0) 3158 << From->getSourceRange(); 3159 return true; 3160 } 3161 3162 if (!IgnoreBaseAccess) 3163 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3164 Paths.front(), 3165 diag::err_downcast_from_inaccessible_base); 3166 3167 // Must be a base to derived member conversion. 3168 BuildBasePathArray(Paths, BasePath); 3169 Kind = CK_BaseToDerivedMemberPointer; 3170 return false; 3171 } 3172 3173 /// Determine whether the lifetime conversion between the two given 3174 /// qualifiers sets is nontrivial. 3175 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3176 Qualifiers ToQuals) { 3177 // Converting anything to const __unsafe_unretained is trivial. 3178 if (ToQuals.hasConst() && 3179 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3180 return false; 3181 3182 return true; 3183 } 3184 3185 /// Perform a single iteration of the loop for checking if a qualification 3186 /// conversion is valid. 3187 /// 3188 /// Specifically, check whether any change between the qualifiers of \p 3189 /// FromType and \p ToType is permissible, given knowledge about whether every 3190 /// outer layer is const-qualified. 3191 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3192 bool CStyle, bool IsTopLevel, 3193 bool &PreviousToQualsIncludeConst, 3194 bool &ObjCLifetimeConversion) { 3195 Qualifiers FromQuals = FromType.getQualifiers(); 3196 Qualifiers ToQuals = ToType.getQualifiers(); 3197 3198 // Ignore __unaligned qualifier. 3199 FromQuals.removeUnaligned(); 3200 3201 // Objective-C ARC: 3202 // Check Objective-C lifetime conversions. 3203 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3204 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3205 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3206 ObjCLifetimeConversion = true; 3207 FromQuals.removeObjCLifetime(); 3208 ToQuals.removeObjCLifetime(); 3209 } else { 3210 // Qualification conversions cannot cast between different 3211 // Objective-C lifetime qualifiers. 3212 return false; 3213 } 3214 } 3215 3216 // Allow addition/removal of GC attributes but not changing GC attributes. 3217 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3218 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3219 FromQuals.removeObjCGCAttr(); 3220 ToQuals.removeObjCGCAttr(); 3221 } 3222 3223 // -- for every j > 0, if const is in cv 1,j then const is in cv 3224 // 2,j, and similarly for volatile. 3225 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3226 return false; 3227 3228 // If address spaces mismatch: 3229 // - in top level it is only valid to convert to addr space that is a 3230 // superset in all cases apart from C-style casts where we allow 3231 // conversions between overlapping address spaces. 3232 // - in non-top levels it is not a valid conversion. 3233 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3234 (!IsTopLevel || 3235 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3236 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3237 return false; 3238 3239 // -- if the cv 1,j and cv 2,j are different, then const is in 3240 // every cv for 0 < k < j. 3241 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3242 !PreviousToQualsIncludeConst) 3243 return false; 3244 3245 // The following wording is from C++20, where the result of the conversion 3246 // is T3, not T2. 3247 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3248 // "array of unknown bound of" 3249 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3250 return false; 3251 3252 // -- if the resulting P3,i is different from P1,i [...], then const is 3253 // added to every cv 3_k for 0 < k < i. 3254 if (!CStyle && FromType->isConstantArrayType() && 3255 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3256 return false; 3257 3258 // Keep track of whether all prior cv-qualifiers in the "to" type 3259 // include const. 3260 PreviousToQualsIncludeConst = 3261 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3262 return true; 3263 } 3264 3265 /// IsQualificationConversion - Determines whether the conversion from 3266 /// an rvalue of type FromType to ToType is a qualification conversion 3267 /// (C++ 4.4). 3268 /// 3269 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3270 /// when the qualification conversion involves a change in the Objective-C 3271 /// object lifetime. 3272 bool 3273 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3274 bool CStyle, bool &ObjCLifetimeConversion) { 3275 FromType = Context.getCanonicalType(FromType); 3276 ToType = Context.getCanonicalType(ToType); 3277 ObjCLifetimeConversion = false; 3278 3279 // If FromType and ToType are the same type, this is not a 3280 // qualification conversion. 3281 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3282 return false; 3283 3284 // (C++ 4.4p4): 3285 // A conversion can add cv-qualifiers at levels other than the first 3286 // in multi-level pointers, subject to the following rules: [...] 3287 bool PreviousToQualsIncludeConst = true; 3288 bool UnwrappedAnyPointer = false; 3289 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3290 if (!isQualificationConversionStep( 3291 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3292 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3293 return false; 3294 UnwrappedAnyPointer = true; 3295 } 3296 3297 // We are left with FromType and ToType being the pointee types 3298 // after unwrapping the original FromType and ToType the same number 3299 // of times. If we unwrapped any pointers, and if FromType and 3300 // ToType have the same unqualified type (since we checked 3301 // qualifiers above), then this is a qualification conversion. 3302 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3303 } 3304 3305 /// - Determine whether this is a conversion from a scalar type to an 3306 /// atomic type. 3307 /// 3308 /// If successful, updates \c SCS's second and third steps in the conversion 3309 /// sequence to finish the conversion. 3310 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3311 bool InOverloadResolution, 3312 StandardConversionSequence &SCS, 3313 bool CStyle) { 3314 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3315 if (!ToAtomic) 3316 return false; 3317 3318 StandardConversionSequence InnerSCS; 3319 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3320 InOverloadResolution, InnerSCS, 3321 CStyle, /*AllowObjCWritebackConversion=*/false)) 3322 return false; 3323 3324 SCS.Second = InnerSCS.Second; 3325 SCS.setToType(1, InnerSCS.getToType(1)); 3326 SCS.Third = InnerSCS.Third; 3327 SCS.QualificationIncludesObjCLifetime 3328 = InnerSCS.QualificationIncludesObjCLifetime; 3329 SCS.setToType(2, InnerSCS.getToType(2)); 3330 return true; 3331 } 3332 3333 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3334 CXXConstructorDecl *Constructor, 3335 QualType Type) { 3336 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3337 if (CtorType->getNumParams() > 0) { 3338 QualType FirstArg = CtorType->getParamType(0); 3339 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3340 return true; 3341 } 3342 return false; 3343 } 3344 3345 static OverloadingResult 3346 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3347 CXXRecordDecl *To, 3348 UserDefinedConversionSequence &User, 3349 OverloadCandidateSet &CandidateSet, 3350 bool AllowExplicit) { 3351 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3352 for (auto *D : S.LookupConstructors(To)) { 3353 auto Info = getConstructorInfo(D); 3354 if (!Info) 3355 continue; 3356 3357 bool Usable = !Info.Constructor->isInvalidDecl() && 3358 S.isInitListConstructor(Info.Constructor); 3359 if (Usable) { 3360 bool SuppressUserConversions = false; 3361 if (Info.ConstructorTmpl) 3362 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3363 /*ExplicitArgs*/ nullptr, From, 3364 CandidateSet, SuppressUserConversions, 3365 /*PartialOverloading*/ false, 3366 AllowExplicit); 3367 else 3368 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3369 CandidateSet, SuppressUserConversions, 3370 /*PartialOverloading*/ false, AllowExplicit); 3371 } 3372 } 3373 3374 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3375 3376 OverloadCandidateSet::iterator Best; 3377 switch (auto Result = 3378 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3379 case OR_Deleted: 3380 case OR_Success: { 3381 // Record the standard conversion we used and the conversion function. 3382 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3383 QualType ThisType = Constructor->getThisType(); 3384 // Initializer lists don't have conversions as such. 3385 User.Before.setAsIdentityConversion(); 3386 User.HadMultipleCandidates = HadMultipleCandidates; 3387 User.ConversionFunction = Constructor; 3388 User.FoundConversionFunction = Best->FoundDecl; 3389 User.After.setAsIdentityConversion(); 3390 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3391 User.After.setAllToTypes(ToType); 3392 return Result; 3393 } 3394 3395 case OR_No_Viable_Function: 3396 return OR_No_Viable_Function; 3397 case OR_Ambiguous: 3398 return OR_Ambiguous; 3399 } 3400 3401 llvm_unreachable("Invalid OverloadResult!"); 3402 } 3403 3404 /// Determines whether there is a user-defined conversion sequence 3405 /// (C++ [over.ics.user]) that converts expression From to the type 3406 /// ToType. If such a conversion exists, User will contain the 3407 /// user-defined conversion sequence that performs such a conversion 3408 /// and this routine will return true. Otherwise, this routine returns 3409 /// false and User is unspecified. 3410 /// 3411 /// \param AllowExplicit true if the conversion should consider C++0x 3412 /// "explicit" conversion functions as well as non-explicit conversion 3413 /// functions (C++0x [class.conv.fct]p2). 3414 /// 3415 /// \param AllowObjCConversionOnExplicit true if the conversion should 3416 /// allow an extra Objective-C pointer conversion on uses of explicit 3417 /// constructors. Requires \c AllowExplicit to also be set. 3418 static OverloadingResult 3419 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3420 UserDefinedConversionSequence &User, 3421 OverloadCandidateSet &CandidateSet, 3422 AllowedExplicit AllowExplicit, 3423 bool AllowObjCConversionOnExplicit) { 3424 assert(AllowExplicit != AllowedExplicit::None || 3425 !AllowObjCConversionOnExplicit); 3426 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3427 3428 // Whether we will only visit constructors. 3429 bool ConstructorsOnly = false; 3430 3431 // If the type we are conversion to is a class type, enumerate its 3432 // constructors. 3433 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3434 // C++ [over.match.ctor]p1: 3435 // When objects of class type are direct-initialized (8.5), or 3436 // copy-initialized from an expression of the same or a 3437 // derived class type (8.5), overload resolution selects the 3438 // constructor. [...] For copy-initialization, the candidate 3439 // functions are all the converting constructors (12.3.1) of 3440 // that class. The argument list is the expression-list within 3441 // the parentheses of the initializer. 3442 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3443 (From->getType()->getAs<RecordType>() && 3444 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3445 ConstructorsOnly = true; 3446 3447 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3448 // We're not going to find any constructors. 3449 } else if (CXXRecordDecl *ToRecordDecl 3450 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3451 3452 Expr **Args = &From; 3453 unsigned NumArgs = 1; 3454 bool ListInitializing = false; 3455 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3456 // But first, see if there is an init-list-constructor that will work. 3457 OverloadingResult Result = IsInitializerListConstructorConversion( 3458 S, From, ToType, ToRecordDecl, User, CandidateSet, 3459 AllowExplicit == AllowedExplicit::All); 3460 if (Result != OR_No_Viable_Function) 3461 return Result; 3462 // Never mind. 3463 CandidateSet.clear( 3464 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3465 3466 // If we're list-initializing, we pass the individual elements as 3467 // arguments, not the entire list. 3468 Args = InitList->getInits(); 3469 NumArgs = InitList->getNumInits(); 3470 ListInitializing = true; 3471 } 3472 3473 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3474 auto Info = getConstructorInfo(D); 3475 if (!Info) 3476 continue; 3477 3478 bool Usable = !Info.Constructor->isInvalidDecl(); 3479 if (!ListInitializing) 3480 Usable = Usable && Info.Constructor->isConvertingConstructor( 3481 /*AllowExplicit*/ true); 3482 if (Usable) { 3483 bool SuppressUserConversions = !ConstructorsOnly; 3484 // C++20 [over.best.ics.general]/4.5: 3485 // if the target is the first parameter of a constructor [of class 3486 // X] and the constructor [...] is a candidate by [...] the second 3487 // phase of [over.match.list] when the initializer list has exactly 3488 // one element that is itself an initializer list, [...] and the 3489 // conversion is to X or reference to cv X, user-defined conversion 3490 // sequences are not cnosidered. 3491 if (SuppressUserConversions && ListInitializing) { 3492 SuppressUserConversions = 3493 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3494 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3495 ToType); 3496 } 3497 if (Info.ConstructorTmpl) 3498 S.AddTemplateOverloadCandidate( 3499 Info.ConstructorTmpl, Info.FoundDecl, 3500 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3501 CandidateSet, SuppressUserConversions, 3502 /*PartialOverloading*/ false, 3503 AllowExplicit == AllowedExplicit::All); 3504 else 3505 // Allow one user-defined conversion when user specifies a 3506 // From->ToType conversion via an static cast (c-style, etc). 3507 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3508 llvm::makeArrayRef(Args, NumArgs), 3509 CandidateSet, SuppressUserConversions, 3510 /*PartialOverloading*/ false, 3511 AllowExplicit == AllowedExplicit::All); 3512 } 3513 } 3514 } 3515 } 3516 3517 // Enumerate conversion functions, if we're allowed to. 3518 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3519 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3520 // No conversion functions from incomplete types. 3521 } else if (const RecordType *FromRecordType = 3522 From->getType()->getAs<RecordType>()) { 3523 if (CXXRecordDecl *FromRecordDecl 3524 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3525 // Add all of the conversion functions as candidates. 3526 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3527 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3528 DeclAccessPair FoundDecl = I.getPair(); 3529 NamedDecl *D = FoundDecl.getDecl(); 3530 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3531 if (isa<UsingShadowDecl>(D)) 3532 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3533 3534 CXXConversionDecl *Conv; 3535 FunctionTemplateDecl *ConvTemplate; 3536 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3537 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3538 else 3539 Conv = cast<CXXConversionDecl>(D); 3540 3541 if (ConvTemplate) 3542 S.AddTemplateConversionCandidate( 3543 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3544 CandidateSet, AllowObjCConversionOnExplicit, 3545 AllowExplicit != AllowedExplicit::None); 3546 else 3547 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3548 CandidateSet, AllowObjCConversionOnExplicit, 3549 AllowExplicit != AllowedExplicit::None); 3550 } 3551 } 3552 } 3553 3554 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3555 3556 OverloadCandidateSet::iterator Best; 3557 switch (auto Result = 3558 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3559 case OR_Success: 3560 case OR_Deleted: 3561 // Record the standard conversion we used and the conversion function. 3562 if (CXXConstructorDecl *Constructor 3563 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3564 // C++ [over.ics.user]p1: 3565 // If the user-defined conversion is specified by a 3566 // constructor (12.3.1), the initial standard conversion 3567 // sequence converts the source type to the type required by 3568 // the argument of the constructor. 3569 // 3570 QualType ThisType = Constructor->getThisType(); 3571 if (isa<InitListExpr>(From)) { 3572 // Initializer lists don't have conversions as such. 3573 User.Before.setAsIdentityConversion(); 3574 } else { 3575 if (Best->Conversions[0].isEllipsis()) 3576 User.EllipsisConversion = true; 3577 else { 3578 User.Before = Best->Conversions[0].Standard; 3579 User.EllipsisConversion = false; 3580 } 3581 } 3582 User.HadMultipleCandidates = HadMultipleCandidates; 3583 User.ConversionFunction = Constructor; 3584 User.FoundConversionFunction = Best->FoundDecl; 3585 User.After.setAsIdentityConversion(); 3586 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3587 User.After.setAllToTypes(ToType); 3588 return Result; 3589 } 3590 if (CXXConversionDecl *Conversion 3591 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3592 // C++ [over.ics.user]p1: 3593 // 3594 // [...] If the user-defined conversion is specified by a 3595 // conversion function (12.3.2), the initial standard 3596 // conversion sequence converts the source type to the 3597 // implicit object parameter of the conversion function. 3598 User.Before = Best->Conversions[0].Standard; 3599 User.HadMultipleCandidates = HadMultipleCandidates; 3600 User.ConversionFunction = Conversion; 3601 User.FoundConversionFunction = Best->FoundDecl; 3602 User.EllipsisConversion = false; 3603 3604 // C++ [over.ics.user]p2: 3605 // The second standard conversion sequence converts the 3606 // result of the user-defined conversion to the target type 3607 // for the sequence. Since an implicit conversion sequence 3608 // is an initialization, the special rules for 3609 // initialization by user-defined conversion apply when 3610 // selecting the best user-defined conversion for a 3611 // user-defined conversion sequence (see 13.3.3 and 3612 // 13.3.3.1). 3613 User.After = Best->FinalConversion; 3614 return Result; 3615 } 3616 llvm_unreachable("Not a constructor or conversion function?"); 3617 3618 case OR_No_Viable_Function: 3619 return OR_No_Viable_Function; 3620 3621 case OR_Ambiguous: 3622 return OR_Ambiguous; 3623 } 3624 3625 llvm_unreachable("Invalid OverloadResult!"); 3626 } 3627 3628 bool 3629 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3630 ImplicitConversionSequence ICS; 3631 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3632 OverloadCandidateSet::CSK_Normal); 3633 OverloadingResult OvResult = 3634 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3635 CandidateSet, AllowedExplicit::None, false); 3636 3637 if (!(OvResult == OR_Ambiguous || 3638 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3639 return false; 3640 3641 auto Cands = CandidateSet.CompleteCandidates( 3642 *this, 3643 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3644 From); 3645 if (OvResult == OR_Ambiguous) 3646 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3647 << From->getType() << ToType << From->getSourceRange(); 3648 else { // OR_No_Viable_Function && !CandidateSet.empty() 3649 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3650 diag::err_typecheck_nonviable_condition_incomplete, 3651 From->getType(), From->getSourceRange())) 3652 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3653 << false << From->getType() << From->getSourceRange() << ToType; 3654 } 3655 3656 CandidateSet.NoteCandidates( 3657 *this, From, Cands); 3658 return true; 3659 } 3660 3661 // Helper for compareConversionFunctions that gets the FunctionType that the 3662 // conversion-operator return value 'points' to, or nullptr. 3663 static const FunctionType * 3664 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3665 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3666 const PointerType *RetPtrTy = 3667 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3668 3669 if (!RetPtrTy) 3670 return nullptr; 3671 3672 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3673 } 3674 3675 /// Compare the user-defined conversion functions or constructors 3676 /// of two user-defined conversion sequences to determine whether any ordering 3677 /// is possible. 3678 static ImplicitConversionSequence::CompareKind 3679 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3680 FunctionDecl *Function2) { 3681 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3682 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3683 if (!Conv1 || !Conv2) 3684 return ImplicitConversionSequence::Indistinguishable; 3685 3686 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3687 return ImplicitConversionSequence::Indistinguishable; 3688 3689 // Objective-C++: 3690 // If both conversion functions are implicitly-declared conversions from 3691 // a lambda closure type to a function pointer and a block pointer, 3692 // respectively, always prefer the conversion to a function pointer, 3693 // because the function pointer is more lightweight and is more likely 3694 // to keep code working. 3695 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3696 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3697 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3698 if (Block1 != Block2) 3699 return Block1 ? ImplicitConversionSequence::Worse 3700 : ImplicitConversionSequence::Better; 3701 } 3702 3703 // In order to support multiple calling conventions for the lambda conversion 3704 // operator (such as when the free and member function calling convention is 3705 // different), prefer the 'free' mechanism, followed by the calling-convention 3706 // of operator(). The latter is in place to support the MSVC-like solution of 3707 // defining ALL of the possible conversions in regards to calling-convention. 3708 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3709 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3710 3711 if (Conv1FuncRet && Conv2FuncRet && 3712 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3713 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3714 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3715 3716 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3717 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 3718 3719 CallingConv CallOpCC = 3720 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3721 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3722 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3723 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3724 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3725 3726 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3727 for (CallingConv CC : PrefOrder) { 3728 if (Conv1CC == CC) 3729 return ImplicitConversionSequence::Better; 3730 if (Conv2CC == CC) 3731 return ImplicitConversionSequence::Worse; 3732 } 3733 } 3734 3735 return ImplicitConversionSequence::Indistinguishable; 3736 } 3737 3738 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3739 const ImplicitConversionSequence &ICS) { 3740 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3741 (ICS.isUserDefined() && 3742 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3743 } 3744 3745 /// CompareImplicitConversionSequences - Compare two implicit 3746 /// conversion sequences to determine whether one is better than the 3747 /// other or if they are indistinguishable (C++ 13.3.3.2). 3748 static ImplicitConversionSequence::CompareKind 3749 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3750 const ImplicitConversionSequence& ICS1, 3751 const ImplicitConversionSequence& ICS2) 3752 { 3753 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3754 // conversion sequences (as defined in 13.3.3.1) 3755 // -- a standard conversion sequence (13.3.3.1.1) is a better 3756 // conversion sequence than a user-defined conversion sequence or 3757 // an ellipsis conversion sequence, and 3758 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3759 // conversion sequence than an ellipsis conversion sequence 3760 // (13.3.3.1.3). 3761 // 3762 // C++0x [over.best.ics]p10: 3763 // For the purpose of ranking implicit conversion sequences as 3764 // described in 13.3.3.2, the ambiguous conversion sequence is 3765 // treated as a user-defined sequence that is indistinguishable 3766 // from any other user-defined conversion sequence. 3767 3768 // String literal to 'char *' conversion has been deprecated in C++03. It has 3769 // been removed from C++11. We still accept this conversion, if it happens at 3770 // the best viable function. Otherwise, this conversion is considered worse 3771 // than ellipsis conversion. Consider this as an extension; this is not in the 3772 // standard. For example: 3773 // 3774 // int &f(...); // #1 3775 // void f(char*); // #2 3776 // void g() { int &r = f("foo"); } 3777 // 3778 // In C++03, we pick #2 as the best viable function. 3779 // In C++11, we pick #1 as the best viable function, because ellipsis 3780 // conversion is better than string-literal to char* conversion (since there 3781 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3782 // convert arguments, #2 would be the best viable function in C++11. 3783 // If the best viable function has this conversion, a warning will be issued 3784 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3785 3786 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3787 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3788 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 3789 // Ill-formedness must not differ 3790 ICS1.isBad() == ICS2.isBad()) 3791 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3792 ? ImplicitConversionSequence::Worse 3793 : ImplicitConversionSequence::Better; 3794 3795 if (ICS1.getKindRank() < ICS2.getKindRank()) 3796 return ImplicitConversionSequence::Better; 3797 if (ICS2.getKindRank() < ICS1.getKindRank()) 3798 return ImplicitConversionSequence::Worse; 3799 3800 // The following checks require both conversion sequences to be of 3801 // the same kind. 3802 if (ICS1.getKind() != ICS2.getKind()) 3803 return ImplicitConversionSequence::Indistinguishable; 3804 3805 ImplicitConversionSequence::CompareKind Result = 3806 ImplicitConversionSequence::Indistinguishable; 3807 3808 // Two implicit conversion sequences of the same form are 3809 // indistinguishable conversion sequences unless one of the 3810 // following rules apply: (C++ 13.3.3.2p3): 3811 3812 // List-initialization sequence L1 is a better conversion sequence than 3813 // list-initialization sequence L2 if: 3814 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3815 // if not that, 3816 // — L1 and L2 convert to arrays of the same element type, and either the 3817 // number of elements n_1 initialized by L1 is less than the number of 3818 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 3819 // an array of unknown bound and L1 does not, 3820 // even if one of the other rules in this paragraph would otherwise apply. 3821 if (!ICS1.isBad()) { 3822 bool StdInit1 = false, StdInit2 = false; 3823 if (ICS1.hasInitializerListContainerType()) 3824 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 3825 nullptr); 3826 if (ICS2.hasInitializerListContainerType()) 3827 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 3828 nullptr); 3829 if (StdInit1 != StdInit2) 3830 return StdInit1 ? ImplicitConversionSequence::Better 3831 : ImplicitConversionSequence::Worse; 3832 3833 if (ICS1.hasInitializerListContainerType() && 3834 ICS2.hasInitializerListContainerType()) 3835 if (auto *CAT1 = S.Context.getAsConstantArrayType( 3836 ICS1.getInitializerListContainerType())) 3837 if (auto *CAT2 = S.Context.getAsConstantArrayType( 3838 ICS2.getInitializerListContainerType())) { 3839 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 3840 CAT2->getElementType())) { 3841 // Both to arrays of the same element type 3842 if (CAT1->getSize() != CAT2->getSize()) 3843 // Different sized, the smaller wins 3844 return CAT1->getSize().ult(CAT2->getSize()) 3845 ? ImplicitConversionSequence::Better 3846 : ImplicitConversionSequence::Worse; 3847 if (ICS1.isInitializerListOfIncompleteArray() != 3848 ICS2.isInitializerListOfIncompleteArray()) 3849 // One is incomplete, it loses 3850 return ICS2.isInitializerListOfIncompleteArray() 3851 ? ImplicitConversionSequence::Better 3852 : ImplicitConversionSequence::Worse; 3853 } 3854 } 3855 } 3856 3857 if (ICS1.isStandard()) 3858 // Standard conversion sequence S1 is a better conversion sequence than 3859 // standard conversion sequence S2 if [...] 3860 Result = CompareStandardConversionSequences(S, Loc, 3861 ICS1.Standard, ICS2.Standard); 3862 else if (ICS1.isUserDefined()) { 3863 // User-defined conversion sequence U1 is a better conversion 3864 // sequence than another user-defined conversion sequence U2 if 3865 // they contain the same user-defined conversion function or 3866 // constructor and if the second standard conversion sequence of 3867 // U1 is better than the second standard conversion sequence of 3868 // U2 (C++ 13.3.3.2p3). 3869 if (ICS1.UserDefined.ConversionFunction == 3870 ICS2.UserDefined.ConversionFunction) 3871 Result = CompareStandardConversionSequences(S, Loc, 3872 ICS1.UserDefined.After, 3873 ICS2.UserDefined.After); 3874 else 3875 Result = compareConversionFunctions(S, 3876 ICS1.UserDefined.ConversionFunction, 3877 ICS2.UserDefined.ConversionFunction); 3878 } 3879 3880 return Result; 3881 } 3882 3883 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3884 // determine if one is a proper subset of the other. 3885 static ImplicitConversionSequence::CompareKind 3886 compareStandardConversionSubsets(ASTContext &Context, 3887 const StandardConversionSequence& SCS1, 3888 const StandardConversionSequence& SCS2) { 3889 ImplicitConversionSequence::CompareKind Result 3890 = ImplicitConversionSequence::Indistinguishable; 3891 3892 // the identity conversion sequence is considered to be a subsequence of 3893 // any non-identity conversion sequence 3894 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3895 return ImplicitConversionSequence::Better; 3896 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3897 return ImplicitConversionSequence::Worse; 3898 3899 if (SCS1.Second != SCS2.Second) { 3900 if (SCS1.Second == ICK_Identity) 3901 Result = ImplicitConversionSequence::Better; 3902 else if (SCS2.Second == ICK_Identity) 3903 Result = ImplicitConversionSequence::Worse; 3904 else 3905 return ImplicitConversionSequence::Indistinguishable; 3906 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3907 return ImplicitConversionSequence::Indistinguishable; 3908 3909 if (SCS1.Third == SCS2.Third) { 3910 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3911 : ImplicitConversionSequence::Indistinguishable; 3912 } 3913 3914 if (SCS1.Third == ICK_Identity) 3915 return Result == ImplicitConversionSequence::Worse 3916 ? ImplicitConversionSequence::Indistinguishable 3917 : ImplicitConversionSequence::Better; 3918 3919 if (SCS2.Third == ICK_Identity) 3920 return Result == ImplicitConversionSequence::Better 3921 ? ImplicitConversionSequence::Indistinguishable 3922 : ImplicitConversionSequence::Worse; 3923 3924 return ImplicitConversionSequence::Indistinguishable; 3925 } 3926 3927 /// Determine whether one of the given reference bindings is better 3928 /// than the other based on what kind of bindings they are. 3929 static bool 3930 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3931 const StandardConversionSequence &SCS2) { 3932 // C++0x [over.ics.rank]p3b4: 3933 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3934 // implicit object parameter of a non-static member function declared 3935 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3936 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3937 // lvalue reference to a function lvalue and S2 binds an rvalue 3938 // reference*. 3939 // 3940 // FIXME: Rvalue references. We're going rogue with the above edits, 3941 // because the semantics in the current C++0x working paper (N3225 at the 3942 // time of this writing) break the standard definition of std::forward 3943 // and std::reference_wrapper when dealing with references to functions. 3944 // Proposed wording changes submitted to CWG for consideration. 3945 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3946 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3947 return false; 3948 3949 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3950 SCS2.IsLvalueReference) || 3951 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3952 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3953 } 3954 3955 enum class FixedEnumPromotion { 3956 None, 3957 ToUnderlyingType, 3958 ToPromotedUnderlyingType 3959 }; 3960 3961 /// Returns kind of fixed enum promotion the \a SCS uses. 3962 static FixedEnumPromotion 3963 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3964 3965 if (SCS.Second != ICK_Integral_Promotion) 3966 return FixedEnumPromotion::None; 3967 3968 QualType FromType = SCS.getFromType(); 3969 if (!FromType->isEnumeralType()) 3970 return FixedEnumPromotion::None; 3971 3972 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 3973 if (!Enum->isFixed()) 3974 return FixedEnumPromotion::None; 3975 3976 QualType UnderlyingType = Enum->getIntegerType(); 3977 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3978 return FixedEnumPromotion::ToUnderlyingType; 3979 3980 return FixedEnumPromotion::ToPromotedUnderlyingType; 3981 } 3982 3983 /// CompareStandardConversionSequences - Compare two standard 3984 /// conversion sequences to determine whether one is better than the 3985 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3986 static ImplicitConversionSequence::CompareKind 3987 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3988 const StandardConversionSequence& SCS1, 3989 const StandardConversionSequence& SCS2) 3990 { 3991 // Standard conversion sequence S1 is a better conversion sequence 3992 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3993 3994 // -- S1 is a proper subsequence of S2 (comparing the conversion 3995 // sequences in the canonical form defined by 13.3.3.1.1, 3996 // excluding any Lvalue Transformation; the identity conversion 3997 // sequence is considered to be a subsequence of any 3998 // non-identity conversion sequence) or, if not that, 3999 if (ImplicitConversionSequence::CompareKind CK 4000 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4001 return CK; 4002 4003 // -- the rank of S1 is better than the rank of S2 (by the rules 4004 // defined below), or, if not that, 4005 ImplicitConversionRank Rank1 = SCS1.getRank(); 4006 ImplicitConversionRank Rank2 = SCS2.getRank(); 4007 if (Rank1 < Rank2) 4008 return ImplicitConversionSequence::Better; 4009 else if (Rank2 < Rank1) 4010 return ImplicitConversionSequence::Worse; 4011 4012 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4013 // are indistinguishable unless one of the following rules 4014 // applies: 4015 4016 // A conversion that is not a conversion of a pointer, or 4017 // pointer to member, to bool is better than another conversion 4018 // that is such a conversion. 4019 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4020 return SCS2.isPointerConversionToBool() 4021 ? ImplicitConversionSequence::Better 4022 : ImplicitConversionSequence::Worse; 4023 4024 // C++14 [over.ics.rank]p4b2: 4025 // This is retroactively applied to C++11 by CWG 1601. 4026 // 4027 // A conversion that promotes an enumeration whose underlying type is fixed 4028 // to its underlying type is better than one that promotes to the promoted 4029 // underlying type, if the two are different. 4030 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4031 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4032 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4033 FEP1 != FEP2) 4034 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4035 ? ImplicitConversionSequence::Better 4036 : ImplicitConversionSequence::Worse; 4037 4038 // C++ [over.ics.rank]p4b2: 4039 // 4040 // If class B is derived directly or indirectly from class A, 4041 // conversion of B* to A* is better than conversion of B* to 4042 // void*, and conversion of A* to void* is better than conversion 4043 // of B* to void*. 4044 bool SCS1ConvertsToVoid 4045 = SCS1.isPointerConversionToVoidPointer(S.Context); 4046 bool SCS2ConvertsToVoid 4047 = SCS2.isPointerConversionToVoidPointer(S.Context); 4048 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4049 // Exactly one of the conversion sequences is a conversion to 4050 // a void pointer; it's the worse conversion. 4051 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4052 : ImplicitConversionSequence::Worse; 4053 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4054 // Neither conversion sequence converts to a void pointer; compare 4055 // their derived-to-base conversions. 4056 if (ImplicitConversionSequence::CompareKind DerivedCK 4057 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4058 return DerivedCK; 4059 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4060 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4061 // Both conversion sequences are conversions to void 4062 // pointers. Compare the source types to determine if there's an 4063 // inheritance relationship in their sources. 4064 QualType FromType1 = SCS1.getFromType(); 4065 QualType FromType2 = SCS2.getFromType(); 4066 4067 // Adjust the types we're converting from via the array-to-pointer 4068 // conversion, if we need to. 4069 if (SCS1.First == ICK_Array_To_Pointer) 4070 FromType1 = S.Context.getArrayDecayedType(FromType1); 4071 if (SCS2.First == ICK_Array_To_Pointer) 4072 FromType2 = S.Context.getArrayDecayedType(FromType2); 4073 4074 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4075 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4076 4077 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4078 return ImplicitConversionSequence::Better; 4079 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4080 return ImplicitConversionSequence::Worse; 4081 4082 // Objective-C++: If one interface is more specific than the 4083 // other, it is the better one. 4084 const ObjCObjectPointerType* FromObjCPtr1 4085 = FromType1->getAs<ObjCObjectPointerType>(); 4086 const ObjCObjectPointerType* FromObjCPtr2 4087 = FromType2->getAs<ObjCObjectPointerType>(); 4088 if (FromObjCPtr1 && FromObjCPtr2) { 4089 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4090 FromObjCPtr2); 4091 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4092 FromObjCPtr1); 4093 if (AssignLeft != AssignRight) { 4094 return AssignLeft? ImplicitConversionSequence::Better 4095 : ImplicitConversionSequence::Worse; 4096 } 4097 } 4098 } 4099 4100 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4101 // Check for a better reference binding based on the kind of bindings. 4102 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4103 return ImplicitConversionSequence::Better; 4104 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4105 return ImplicitConversionSequence::Worse; 4106 } 4107 4108 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4109 // bullet 3). 4110 if (ImplicitConversionSequence::CompareKind QualCK 4111 = CompareQualificationConversions(S, SCS1, SCS2)) 4112 return QualCK; 4113 4114 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4115 // C++ [over.ics.rank]p3b4: 4116 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4117 // which the references refer are the same type except for 4118 // top-level cv-qualifiers, and the type to which the reference 4119 // initialized by S2 refers is more cv-qualified than the type 4120 // to which the reference initialized by S1 refers. 4121 QualType T1 = SCS1.getToType(2); 4122 QualType T2 = SCS2.getToType(2); 4123 T1 = S.Context.getCanonicalType(T1); 4124 T2 = S.Context.getCanonicalType(T2); 4125 Qualifiers T1Quals, T2Quals; 4126 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4127 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4128 if (UnqualT1 == UnqualT2) { 4129 // Objective-C++ ARC: If the references refer to objects with different 4130 // lifetimes, prefer bindings that don't change lifetime. 4131 if (SCS1.ObjCLifetimeConversionBinding != 4132 SCS2.ObjCLifetimeConversionBinding) { 4133 return SCS1.ObjCLifetimeConversionBinding 4134 ? ImplicitConversionSequence::Worse 4135 : ImplicitConversionSequence::Better; 4136 } 4137 4138 // If the type is an array type, promote the element qualifiers to the 4139 // type for comparison. 4140 if (isa<ArrayType>(T1) && T1Quals) 4141 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4142 if (isa<ArrayType>(T2) && T2Quals) 4143 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4144 if (T2.isMoreQualifiedThan(T1)) 4145 return ImplicitConversionSequence::Better; 4146 if (T1.isMoreQualifiedThan(T2)) 4147 return ImplicitConversionSequence::Worse; 4148 } 4149 } 4150 4151 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4152 // floating-to-integral conversion if the integral conversion 4153 // is between types of the same size. 4154 // For example: 4155 // void f(float); 4156 // void f(int); 4157 // int main { 4158 // long a; 4159 // f(a); 4160 // } 4161 // Here, MSVC will call f(int) instead of generating a compile error 4162 // as clang will do in standard mode. 4163 if (S.getLangOpts().MSVCCompat && 4164 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4165 SCS1.Second == ICK_Integral_Conversion && 4166 SCS2.Second == ICK_Floating_Integral && 4167 S.Context.getTypeSize(SCS1.getFromType()) == 4168 S.Context.getTypeSize(SCS1.getToType(2))) 4169 return ImplicitConversionSequence::Better; 4170 4171 // Prefer a compatible vector conversion over a lax vector conversion 4172 // For example: 4173 // 4174 // typedef float __v4sf __attribute__((__vector_size__(16))); 4175 // void f(vector float); 4176 // void f(vector signed int); 4177 // int main() { 4178 // __v4sf a; 4179 // f(a); 4180 // } 4181 // Here, we'd like to choose f(vector float) and not 4182 // report an ambiguous call error 4183 if (SCS1.Second == ICK_Vector_Conversion && 4184 SCS2.Second == ICK_Vector_Conversion) { 4185 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4186 SCS1.getFromType(), SCS1.getToType(2)); 4187 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4188 SCS2.getFromType(), SCS2.getToType(2)); 4189 4190 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4191 return SCS1IsCompatibleVectorConversion 4192 ? ImplicitConversionSequence::Better 4193 : ImplicitConversionSequence::Worse; 4194 } 4195 4196 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4197 SCS2.Second == ICK_SVE_Vector_Conversion) { 4198 bool SCS1IsCompatibleSVEVectorConversion = 4199 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4200 bool SCS2IsCompatibleSVEVectorConversion = 4201 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4202 4203 if (SCS1IsCompatibleSVEVectorConversion != 4204 SCS2IsCompatibleSVEVectorConversion) 4205 return SCS1IsCompatibleSVEVectorConversion 4206 ? ImplicitConversionSequence::Better 4207 : ImplicitConversionSequence::Worse; 4208 } 4209 4210 return ImplicitConversionSequence::Indistinguishable; 4211 } 4212 4213 /// CompareQualificationConversions - Compares two standard conversion 4214 /// sequences to determine whether they can be ranked based on their 4215 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4216 static ImplicitConversionSequence::CompareKind 4217 CompareQualificationConversions(Sema &S, 4218 const StandardConversionSequence& SCS1, 4219 const StandardConversionSequence& SCS2) { 4220 // C++ [over.ics.rank]p3: 4221 // -- S1 and S2 differ only in their qualification conversion and 4222 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4223 // [C++98] 4224 // [...] and the cv-qualification signature of type T1 is a proper subset 4225 // of the cv-qualification signature of type T2, and S1 is not the 4226 // deprecated string literal array-to-pointer conversion (4.2). 4227 // [C++2a] 4228 // [...] where T1 can be converted to T2 by a qualification conversion. 4229 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4230 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4231 return ImplicitConversionSequence::Indistinguishable; 4232 4233 // FIXME: the example in the standard doesn't use a qualification 4234 // conversion (!) 4235 QualType T1 = SCS1.getToType(2); 4236 QualType T2 = SCS2.getToType(2); 4237 T1 = S.Context.getCanonicalType(T1); 4238 T2 = S.Context.getCanonicalType(T2); 4239 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4240 Qualifiers T1Quals, T2Quals; 4241 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4242 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4243 4244 // If the types are the same, we won't learn anything by unwrapping 4245 // them. 4246 if (UnqualT1 == UnqualT2) 4247 return ImplicitConversionSequence::Indistinguishable; 4248 4249 // Don't ever prefer a standard conversion sequence that uses the deprecated 4250 // string literal array to pointer conversion. 4251 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4252 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4253 4254 // Objective-C++ ARC: 4255 // Prefer qualification conversions not involving a change in lifetime 4256 // to qualification conversions that do change lifetime. 4257 if (SCS1.QualificationIncludesObjCLifetime && 4258 !SCS2.QualificationIncludesObjCLifetime) 4259 CanPick1 = false; 4260 if (SCS2.QualificationIncludesObjCLifetime && 4261 !SCS1.QualificationIncludesObjCLifetime) 4262 CanPick2 = false; 4263 4264 bool ObjCLifetimeConversion; 4265 if (CanPick1 && 4266 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4267 CanPick1 = false; 4268 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4269 // directions, so we can't short-cut this second check in general. 4270 if (CanPick2 && 4271 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4272 CanPick2 = false; 4273 4274 if (CanPick1 != CanPick2) 4275 return CanPick1 ? ImplicitConversionSequence::Better 4276 : ImplicitConversionSequence::Worse; 4277 return ImplicitConversionSequence::Indistinguishable; 4278 } 4279 4280 /// CompareDerivedToBaseConversions - Compares two standard conversion 4281 /// sequences to determine whether they can be ranked based on their 4282 /// various kinds of derived-to-base conversions (C++ 4283 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4284 /// conversions between Objective-C interface types. 4285 static ImplicitConversionSequence::CompareKind 4286 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4287 const StandardConversionSequence& SCS1, 4288 const StandardConversionSequence& SCS2) { 4289 QualType FromType1 = SCS1.getFromType(); 4290 QualType ToType1 = SCS1.getToType(1); 4291 QualType FromType2 = SCS2.getFromType(); 4292 QualType ToType2 = SCS2.getToType(1); 4293 4294 // Adjust the types we're converting from via the array-to-pointer 4295 // conversion, if we need to. 4296 if (SCS1.First == ICK_Array_To_Pointer) 4297 FromType1 = S.Context.getArrayDecayedType(FromType1); 4298 if (SCS2.First == ICK_Array_To_Pointer) 4299 FromType2 = S.Context.getArrayDecayedType(FromType2); 4300 4301 // Canonicalize all of the types. 4302 FromType1 = S.Context.getCanonicalType(FromType1); 4303 ToType1 = S.Context.getCanonicalType(ToType1); 4304 FromType2 = S.Context.getCanonicalType(FromType2); 4305 ToType2 = S.Context.getCanonicalType(ToType2); 4306 4307 // C++ [over.ics.rank]p4b3: 4308 // 4309 // If class B is derived directly or indirectly from class A and 4310 // class C is derived directly or indirectly from B, 4311 // 4312 // Compare based on pointer conversions. 4313 if (SCS1.Second == ICK_Pointer_Conversion && 4314 SCS2.Second == ICK_Pointer_Conversion && 4315 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4316 FromType1->isPointerType() && FromType2->isPointerType() && 4317 ToType1->isPointerType() && ToType2->isPointerType()) { 4318 QualType FromPointee1 = 4319 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4320 QualType ToPointee1 = 4321 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4322 QualType FromPointee2 = 4323 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4324 QualType ToPointee2 = 4325 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4326 4327 // -- conversion of C* to B* is better than conversion of C* to A*, 4328 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4329 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4330 return ImplicitConversionSequence::Better; 4331 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4332 return ImplicitConversionSequence::Worse; 4333 } 4334 4335 // -- conversion of B* to A* is better than conversion of C* to A*, 4336 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4337 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4338 return ImplicitConversionSequence::Better; 4339 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4340 return ImplicitConversionSequence::Worse; 4341 } 4342 } else if (SCS1.Second == ICK_Pointer_Conversion && 4343 SCS2.Second == ICK_Pointer_Conversion) { 4344 const ObjCObjectPointerType *FromPtr1 4345 = FromType1->getAs<ObjCObjectPointerType>(); 4346 const ObjCObjectPointerType *FromPtr2 4347 = FromType2->getAs<ObjCObjectPointerType>(); 4348 const ObjCObjectPointerType *ToPtr1 4349 = ToType1->getAs<ObjCObjectPointerType>(); 4350 const ObjCObjectPointerType *ToPtr2 4351 = ToType2->getAs<ObjCObjectPointerType>(); 4352 4353 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4354 // Apply the same conversion ranking rules for Objective-C pointer types 4355 // that we do for C++ pointers to class types. However, we employ the 4356 // Objective-C pseudo-subtyping relationship used for assignment of 4357 // Objective-C pointer types. 4358 bool FromAssignLeft 4359 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4360 bool FromAssignRight 4361 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4362 bool ToAssignLeft 4363 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4364 bool ToAssignRight 4365 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4366 4367 // A conversion to an a non-id object pointer type or qualified 'id' 4368 // type is better than a conversion to 'id'. 4369 if (ToPtr1->isObjCIdType() && 4370 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4371 return ImplicitConversionSequence::Worse; 4372 if (ToPtr2->isObjCIdType() && 4373 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4374 return ImplicitConversionSequence::Better; 4375 4376 // A conversion to a non-id object pointer type is better than a 4377 // conversion to a qualified 'id' type 4378 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4379 return ImplicitConversionSequence::Worse; 4380 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4381 return ImplicitConversionSequence::Better; 4382 4383 // A conversion to an a non-Class object pointer type or qualified 'Class' 4384 // type is better than a conversion to 'Class'. 4385 if (ToPtr1->isObjCClassType() && 4386 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4387 return ImplicitConversionSequence::Worse; 4388 if (ToPtr2->isObjCClassType() && 4389 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4390 return ImplicitConversionSequence::Better; 4391 4392 // A conversion to a non-Class object pointer type is better than a 4393 // conversion to a qualified 'Class' type. 4394 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4395 return ImplicitConversionSequence::Worse; 4396 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4397 return ImplicitConversionSequence::Better; 4398 4399 // -- "conversion of C* to B* is better than conversion of C* to A*," 4400 if (S.Context.hasSameType(FromType1, FromType2) && 4401 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4402 (ToAssignLeft != ToAssignRight)) { 4403 if (FromPtr1->isSpecialized()) { 4404 // "conversion of B<A> * to B * is better than conversion of B * to 4405 // C *. 4406 bool IsFirstSame = 4407 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4408 bool IsSecondSame = 4409 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4410 if (IsFirstSame) { 4411 if (!IsSecondSame) 4412 return ImplicitConversionSequence::Better; 4413 } else if (IsSecondSame) 4414 return ImplicitConversionSequence::Worse; 4415 } 4416 return ToAssignLeft? ImplicitConversionSequence::Worse 4417 : ImplicitConversionSequence::Better; 4418 } 4419 4420 // -- "conversion of B* to A* is better than conversion of C* to A*," 4421 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4422 (FromAssignLeft != FromAssignRight)) 4423 return FromAssignLeft? ImplicitConversionSequence::Better 4424 : ImplicitConversionSequence::Worse; 4425 } 4426 } 4427 4428 // Ranking of member-pointer types. 4429 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4430 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4431 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4432 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4433 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4434 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4435 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4436 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4437 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4438 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4439 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4440 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4441 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4442 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4443 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4444 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4445 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4446 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4447 return ImplicitConversionSequence::Worse; 4448 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4449 return ImplicitConversionSequence::Better; 4450 } 4451 // conversion of B::* to C::* is better than conversion of A::* to C::* 4452 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4453 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4454 return ImplicitConversionSequence::Better; 4455 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4456 return ImplicitConversionSequence::Worse; 4457 } 4458 } 4459 4460 if (SCS1.Second == ICK_Derived_To_Base) { 4461 // -- conversion of C to B is better than conversion of C to A, 4462 // -- binding of an expression of type C to a reference of type 4463 // B& is better than binding an expression of type C to a 4464 // reference of type A&, 4465 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4466 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4467 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4468 return ImplicitConversionSequence::Better; 4469 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4470 return ImplicitConversionSequence::Worse; 4471 } 4472 4473 // -- conversion of B to A is better than conversion of C to A. 4474 // -- binding of an expression of type B to a reference of type 4475 // A& is better than binding an expression of type C to a 4476 // reference of type A&, 4477 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4478 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4479 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4480 return ImplicitConversionSequence::Better; 4481 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4482 return ImplicitConversionSequence::Worse; 4483 } 4484 } 4485 4486 return ImplicitConversionSequence::Indistinguishable; 4487 } 4488 4489 /// Determine whether the given type is valid, e.g., it is not an invalid 4490 /// C++ class. 4491 static bool isTypeValid(QualType T) { 4492 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4493 return !Record->isInvalidDecl(); 4494 4495 return true; 4496 } 4497 4498 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4499 if (!T.getQualifiers().hasUnaligned()) 4500 return T; 4501 4502 Qualifiers Q; 4503 T = Ctx.getUnqualifiedArrayType(T, Q); 4504 Q.removeUnaligned(); 4505 return Ctx.getQualifiedType(T, Q); 4506 } 4507 4508 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4509 /// determine whether they are reference-compatible, 4510 /// reference-related, or incompatible, for use in C++ initialization by 4511 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4512 /// type, and the first type (T1) is the pointee type of the reference 4513 /// type being initialized. 4514 Sema::ReferenceCompareResult 4515 Sema::CompareReferenceRelationship(SourceLocation Loc, 4516 QualType OrigT1, QualType OrigT2, 4517 ReferenceConversions *ConvOut) { 4518 assert(!OrigT1->isReferenceType() && 4519 "T1 must be the pointee type of the reference type"); 4520 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4521 4522 QualType T1 = Context.getCanonicalType(OrigT1); 4523 QualType T2 = Context.getCanonicalType(OrigT2); 4524 Qualifiers T1Quals, T2Quals; 4525 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4526 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4527 4528 ReferenceConversions ConvTmp; 4529 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4530 Conv = ReferenceConversions(); 4531 4532 // C++2a [dcl.init.ref]p4: 4533 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4534 // reference-related to "cv2 T2" if T1 is similar to T2, or 4535 // T1 is a base class of T2. 4536 // "cv1 T1" is reference-compatible with "cv2 T2" if 4537 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4538 // "pointer to cv1 T1" via a standard conversion sequence. 4539 4540 // Check for standard conversions we can apply to pointers: derived-to-base 4541 // conversions, ObjC pointer conversions, and function pointer conversions. 4542 // (Qualification conversions are checked last.) 4543 QualType ConvertedT2; 4544 if (UnqualT1 == UnqualT2) { 4545 // Nothing to do. 4546 } else if (isCompleteType(Loc, OrigT2) && 4547 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4548 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4549 Conv |= ReferenceConversions::DerivedToBase; 4550 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4551 UnqualT2->isObjCObjectOrInterfaceType() && 4552 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4553 Conv |= ReferenceConversions::ObjC; 4554 else if (UnqualT2->isFunctionType() && 4555 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4556 Conv |= ReferenceConversions::Function; 4557 // No need to check qualifiers; function types don't have them. 4558 return Ref_Compatible; 4559 } 4560 bool ConvertedReferent = Conv != 0; 4561 4562 // We can have a qualification conversion. Compute whether the types are 4563 // similar at the same time. 4564 bool PreviousToQualsIncludeConst = true; 4565 bool TopLevel = true; 4566 do { 4567 if (T1 == T2) 4568 break; 4569 4570 // We will need a qualification conversion. 4571 Conv |= ReferenceConversions::Qualification; 4572 4573 // Track whether we performed a qualification conversion anywhere other 4574 // than the top level. This matters for ranking reference bindings in 4575 // overload resolution. 4576 if (!TopLevel) 4577 Conv |= ReferenceConversions::NestedQualification; 4578 4579 // MS compiler ignores __unaligned qualifier for references; do the same. 4580 T1 = withoutUnaligned(Context, T1); 4581 T2 = withoutUnaligned(Context, T2); 4582 4583 // If we find a qualifier mismatch, the types are not reference-compatible, 4584 // but are still be reference-related if they're similar. 4585 bool ObjCLifetimeConversion = false; 4586 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4587 PreviousToQualsIncludeConst, 4588 ObjCLifetimeConversion)) 4589 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4590 ? Ref_Related 4591 : Ref_Incompatible; 4592 4593 // FIXME: Should we track this for any level other than the first? 4594 if (ObjCLifetimeConversion) 4595 Conv |= ReferenceConversions::ObjCLifetime; 4596 4597 TopLevel = false; 4598 } while (Context.UnwrapSimilarTypes(T1, T2)); 4599 4600 // At this point, if the types are reference-related, we must either have the 4601 // same inner type (ignoring qualifiers), or must have already worked out how 4602 // to convert the referent. 4603 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4604 ? Ref_Compatible 4605 : Ref_Incompatible; 4606 } 4607 4608 /// Look for a user-defined conversion to a value reference-compatible 4609 /// with DeclType. Return true if something definite is found. 4610 static bool 4611 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4612 QualType DeclType, SourceLocation DeclLoc, 4613 Expr *Init, QualType T2, bool AllowRvalues, 4614 bool AllowExplicit) { 4615 assert(T2->isRecordType() && "Can only find conversions of record types."); 4616 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4617 4618 OverloadCandidateSet CandidateSet( 4619 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4620 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4621 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4622 NamedDecl *D = *I; 4623 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4624 if (isa<UsingShadowDecl>(D)) 4625 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4626 4627 FunctionTemplateDecl *ConvTemplate 4628 = dyn_cast<FunctionTemplateDecl>(D); 4629 CXXConversionDecl *Conv; 4630 if (ConvTemplate) 4631 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4632 else 4633 Conv = cast<CXXConversionDecl>(D); 4634 4635 if (AllowRvalues) { 4636 // If we are initializing an rvalue reference, don't permit conversion 4637 // functions that return lvalues. 4638 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4639 const ReferenceType *RefType 4640 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4641 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4642 continue; 4643 } 4644 4645 if (!ConvTemplate && 4646 S.CompareReferenceRelationship( 4647 DeclLoc, 4648 Conv->getConversionType() 4649 .getNonReferenceType() 4650 .getUnqualifiedType(), 4651 DeclType.getNonReferenceType().getUnqualifiedType()) == 4652 Sema::Ref_Incompatible) 4653 continue; 4654 } else { 4655 // If the conversion function doesn't return a reference type, 4656 // it can't be considered for this conversion. An rvalue reference 4657 // is only acceptable if its referencee is a function type. 4658 4659 const ReferenceType *RefType = 4660 Conv->getConversionType()->getAs<ReferenceType>(); 4661 if (!RefType || 4662 (!RefType->isLValueReferenceType() && 4663 !RefType->getPointeeType()->isFunctionType())) 4664 continue; 4665 } 4666 4667 if (ConvTemplate) 4668 S.AddTemplateConversionCandidate( 4669 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4670 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4671 else 4672 S.AddConversionCandidate( 4673 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4674 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4675 } 4676 4677 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4678 4679 OverloadCandidateSet::iterator Best; 4680 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4681 case OR_Success: 4682 // C++ [over.ics.ref]p1: 4683 // 4684 // [...] If the parameter binds directly to the result of 4685 // applying a conversion function to the argument 4686 // expression, the implicit conversion sequence is a 4687 // user-defined conversion sequence (13.3.3.1.2), with the 4688 // second standard conversion sequence either an identity 4689 // conversion or, if the conversion function returns an 4690 // entity of a type that is a derived class of the parameter 4691 // type, a derived-to-base Conversion. 4692 if (!Best->FinalConversion.DirectBinding) 4693 return false; 4694 4695 ICS.setUserDefined(); 4696 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4697 ICS.UserDefined.After = Best->FinalConversion; 4698 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4699 ICS.UserDefined.ConversionFunction = Best->Function; 4700 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4701 ICS.UserDefined.EllipsisConversion = false; 4702 assert(ICS.UserDefined.After.ReferenceBinding && 4703 ICS.UserDefined.After.DirectBinding && 4704 "Expected a direct reference binding!"); 4705 return true; 4706 4707 case OR_Ambiguous: 4708 ICS.setAmbiguous(); 4709 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4710 Cand != CandidateSet.end(); ++Cand) 4711 if (Cand->Best) 4712 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4713 return true; 4714 4715 case OR_No_Viable_Function: 4716 case OR_Deleted: 4717 // There was no suitable conversion, or we found a deleted 4718 // conversion; continue with other checks. 4719 return false; 4720 } 4721 4722 llvm_unreachable("Invalid OverloadResult!"); 4723 } 4724 4725 /// Compute an implicit conversion sequence for reference 4726 /// initialization. 4727 static ImplicitConversionSequence 4728 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4729 SourceLocation DeclLoc, 4730 bool SuppressUserConversions, 4731 bool AllowExplicit) { 4732 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4733 4734 // Most paths end in a failed conversion. 4735 ImplicitConversionSequence ICS; 4736 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4737 4738 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4739 QualType T2 = Init->getType(); 4740 4741 // If the initializer is the address of an overloaded function, try 4742 // to resolve the overloaded function. If all goes well, T2 is the 4743 // type of the resulting function. 4744 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4745 DeclAccessPair Found; 4746 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4747 false, Found)) 4748 T2 = Fn->getType(); 4749 } 4750 4751 // Compute some basic properties of the types and the initializer. 4752 bool isRValRef = DeclType->isRValueReferenceType(); 4753 Expr::Classification InitCategory = Init->Classify(S.Context); 4754 4755 Sema::ReferenceConversions RefConv; 4756 Sema::ReferenceCompareResult RefRelationship = 4757 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4758 4759 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4760 ICS.setStandard(); 4761 ICS.Standard.First = ICK_Identity; 4762 // FIXME: A reference binding can be a function conversion too. We should 4763 // consider that when ordering reference-to-function bindings. 4764 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4765 ? ICK_Derived_To_Base 4766 : (RefConv & Sema::ReferenceConversions::ObjC) 4767 ? ICK_Compatible_Conversion 4768 : ICK_Identity; 4769 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4770 // a reference binding that performs a non-top-level qualification 4771 // conversion as a qualification conversion, not as an identity conversion. 4772 ICS.Standard.Third = (RefConv & 4773 Sema::ReferenceConversions::NestedQualification) 4774 ? ICK_Qualification 4775 : ICK_Identity; 4776 ICS.Standard.setFromType(T2); 4777 ICS.Standard.setToType(0, T2); 4778 ICS.Standard.setToType(1, T1); 4779 ICS.Standard.setToType(2, T1); 4780 ICS.Standard.ReferenceBinding = true; 4781 ICS.Standard.DirectBinding = BindsDirectly; 4782 ICS.Standard.IsLvalueReference = !isRValRef; 4783 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4784 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4785 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4786 ICS.Standard.ObjCLifetimeConversionBinding = 4787 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4788 ICS.Standard.CopyConstructor = nullptr; 4789 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4790 }; 4791 4792 // C++0x [dcl.init.ref]p5: 4793 // A reference to type "cv1 T1" is initialized by an expression 4794 // of type "cv2 T2" as follows: 4795 4796 // -- If reference is an lvalue reference and the initializer expression 4797 if (!isRValRef) { 4798 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4799 // reference-compatible with "cv2 T2," or 4800 // 4801 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4802 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4803 // C++ [over.ics.ref]p1: 4804 // When a parameter of reference type binds directly (8.5.3) 4805 // to an argument expression, the implicit conversion sequence 4806 // is the identity conversion, unless the argument expression 4807 // has a type that is a derived class of the parameter type, 4808 // in which case the implicit conversion sequence is a 4809 // derived-to-base Conversion (13.3.3.1). 4810 SetAsReferenceBinding(/*BindsDirectly=*/true); 4811 4812 // Nothing more to do: the inaccessibility/ambiguity check for 4813 // derived-to-base conversions is suppressed when we're 4814 // computing the implicit conversion sequence (C++ 4815 // [over.best.ics]p2). 4816 return ICS; 4817 } 4818 4819 // -- has a class type (i.e., T2 is a class type), where T1 is 4820 // not reference-related to T2, and can be implicitly 4821 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4822 // is reference-compatible with "cv3 T3" 92) (this 4823 // conversion is selected by enumerating the applicable 4824 // conversion functions (13.3.1.6) and choosing the best 4825 // one through overload resolution (13.3)), 4826 if (!SuppressUserConversions && T2->isRecordType() && 4827 S.isCompleteType(DeclLoc, T2) && 4828 RefRelationship == Sema::Ref_Incompatible) { 4829 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4830 Init, T2, /*AllowRvalues=*/false, 4831 AllowExplicit)) 4832 return ICS; 4833 } 4834 } 4835 4836 // -- Otherwise, the reference shall be an lvalue reference to a 4837 // non-volatile const type (i.e., cv1 shall be const), or the reference 4838 // shall be an rvalue reference. 4839 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4840 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4841 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4842 return ICS; 4843 } 4844 4845 // -- If the initializer expression 4846 // 4847 // -- is an xvalue, class prvalue, array prvalue or function 4848 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4849 if (RefRelationship == Sema::Ref_Compatible && 4850 (InitCategory.isXValue() || 4851 (InitCategory.isPRValue() && 4852 (T2->isRecordType() || T2->isArrayType())) || 4853 (InitCategory.isLValue() && T2->isFunctionType()))) { 4854 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4855 // binding unless we're binding to a class prvalue. 4856 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4857 // allow the use of rvalue references in C++98/03 for the benefit of 4858 // standard library implementors; therefore, we need the xvalue check here. 4859 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4860 !(InitCategory.isPRValue() || T2->isRecordType())); 4861 return ICS; 4862 } 4863 4864 // -- has a class type (i.e., T2 is a class type), where T1 is not 4865 // reference-related to T2, and can be implicitly converted to 4866 // an xvalue, class prvalue, or function lvalue of type 4867 // "cv3 T3", where "cv1 T1" is reference-compatible with 4868 // "cv3 T3", 4869 // 4870 // then the reference is bound to the value of the initializer 4871 // expression in the first case and to the result of the conversion 4872 // in the second case (or, in either case, to an appropriate base 4873 // class subobject). 4874 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4875 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4876 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4877 Init, T2, /*AllowRvalues=*/true, 4878 AllowExplicit)) { 4879 // In the second case, if the reference is an rvalue reference 4880 // and the second standard conversion sequence of the 4881 // user-defined conversion sequence includes an lvalue-to-rvalue 4882 // conversion, the program is ill-formed. 4883 if (ICS.isUserDefined() && isRValRef && 4884 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4885 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4886 4887 return ICS; 4888 } 4889 4890 // A temporary of function type cannot be created; don't even try. 4891 if (T1->isFunctionType()) 4892 return ICS; 4893 4894 // -- Otherwise, a temporary of type "cv1 T1" is created and 4895 // initialized from the initializer expression using the 4896 // rules for a non-reference copy initialization (8.5). The 4897 // reference is then bound to the temporary. If T1 is 4898 // reference-related to T2, cv1 must be the same 4899 // cv-qualification as, or greater cv-qualification than, 4900 // cv2; otherwise, the program is ill-formed. 4901 if (RefRelationship == Sema::Ref_Related) { 4902 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4903 // we would be reference-compatible or reference-compatible with 4904 // added qualification. But that wasn't the case, so the reference 4905 // initialization fails. 4906 // 4907 // Note that we only want to check address spaces and cvr-qualifiers here. 4908 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4909 Qualifiers T1Quals = T1.getQualifiers(); 4910 Qualifiers T2Quals = T2.getQualifiers(); 4911 T1Quals.removeObjCGCAttr(); 4912 T1Quals.removeObjCLifetime(); 4913 T2Quals.removeObjCGCAttr(); 4914 T2Quals.removeObjCLifetime(); 4915 // MS compiler ignores __unaligned qualifier for references; do the same. 4916 T1Quals.removeUnaligned(); 4917 T2Quals.removeUnaligned(); 4918 if (!T1Quals.compatiblyIncludes(T2Quals)) 4919 return ICS; 4920 } 4921 4922 // If at least one of the types is a class type, the types are not 4923 // related, and we aren't allowed any user conversions, the 4924 // reference binding fails. This case is important for breaking 4925 // recursion, since TryImplicitConversion below will attempt to 4926 // create a temporary through the use of a copy constructor. 4927 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4928 (T1->isRecordType() || T2->isRecordType())) 4929 return ICS; 4930 4931 // If T1 is reference-related to T2 and the reference is an rvalue 4932 // reference, the initializer expression shall not be an lvalue. 4933 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4934 Init->Classify(S.Context).isLValue()) { 4935 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4936 return ICS; 4937 } 4938 4939 // C++ [over.ics.ref]p2: 4940 // When a parameter of reference type is not bound directly to 4941 // an argument expression, the conversion sequence is the one 4942 // required to convert the argument expression to the 4943 // underlying type of the reference according to 4944 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4945 // to copy-initializing a temporary of the underlying type with 4946 // the argument expression. Any difference in top-level 4947 // cv-qualification is subsumed by the initialization itself 4948 // and does not constitute a conversion. 4949 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4950 AllowedExplicit::None, 4951 /*InOverloadResolution=*/false, 4952 /*CStyle=*/false, 4953 /*AllowObjCWritebackConversion=*/false, 4954 /*AllowObjCConversionOnExplicit=*/false); 4955 4956 // Of course, that's still a reference binding. 4957 if (ICS.isStandard()) { 4958 ICS.Standard.ReferenceBinding = true; 4959 ICS.Standard.IsLvalueReference = !isRValRef; 4960 ICS.Standard.BindsToFunctionLvalue = false; 4961 ICS.Standard.BindsToRvalue = true; 4962 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4963 ICS.Standard.ObjCLifetimeConversionBinding = false; 4964 } else if (ICS.isUserDefined()) { 4965 const ReferenceType *LValRefType = 4966 ICS.UserDefined.ConversionFunction->getReturnType() 4967 ->getAs<LValueReferenceType>(); 4968 4969 // C++ [over.ics.ref]p3: 4970 // Except for an implicit object parameter, for which see 13.3.1, a 4971 // standard conversion sequence cannot be formed if it requires [...] 4972 // binding an rvalue reference to an lvalue other than a function 4973 // lvalue. 4974 // Note that the function case is not possible here. 4975 if (isRValRef && LValRefType) { 4976 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4977 return ICS; 4978 } 4979 4980 ICS.UserDefined.After.ReferenceBinding = true; 4981 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4982 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4983 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4984 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4985 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4986 } 4987 4988 return ICS; 4989 } 4990 4991 static ImplicitConversionSequence 4992 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4993 bool SuppressUserConversions, 4994 bool InOverloadResolution, 4995 bool AllowObjCWritebackConversion, 4996 bool AllowExplicit = false); 4997 4998 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4999 /// initializer list From. 5000 static ImplicitConversionSequence 5001 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5002 bool SuppressUserConversions, 5003 bool InOverloadResolution, 5004 bool AllowObjCWritebackConversion) { 5005 // C++11 [over.ics.list]p1: 5006 // When an argument is an initializer list, it is not an expression and 5007 // special rules apply for converting it to a parameter type. 5008 5009 ImplicitConversionSequence Result; 5010 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5011 5012 // We need a complete type for what follows. With one C++20 exception, 5013 // incomplete types can never be initialized from init lists. 5014 QualType InitTy = ToType; 5015 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5016 if (AT && S.getLangOpts().CPlusPlus20) 5017 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5018 // C++20 allows list initialization of an incomplete array type. 5019 InitTy = IAT->getElementType(); 5020 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5021 return Result; 5022 5023 // Per DR1467: 5024 // If the parameter type is a class X and the initializer list has a single 5025 // element of type cv U, where U is X or a class derived from X, the 5026 // implicit conversion sequence is the one required to convert the element 5027 // to the parameter type. 5028 // 5029 // Otherwise, if the parameter type is a character array [... ] 5030 // and the initializer list has a single element that is an 5031 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5032 // implicit conversion sequence is the identity conversion. 5033 if (From->getNumInits() == 1) { 5034 if (ToType->isRecordType()) { 5035 QualType InitType = From->getInit(0)->getType(); 5036 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5037 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5038 return TryCopyInitialization(S, From->getInit(0), ToType, 5039 SuppressUserConversions, 5040 InOverloadResolution, 5041 AllowObjCWritebackConversion); 5042 } 5043 5044 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5045 InitializedEntity Entity = 5046 InitializedEntity::InitializeParameter(S.Context, ToType, 5047 /*Consumed=*/false); 5048 if (S.CanPerformCopyInitialization(Entity, From)) { 5049 Result.setStandard(); 5050 Result.Standard.setAsIdentityConversion(); 5051 Result.Standard.setFromType(ToType); 5052 Result.Standard.setAllToTypes(ToType); 5053 return Result; 5054 } 5055 } 5056 } 5057 5058 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5059 // C++11 [over.ics.list]p2: 5060 // If the parameter type is std::initializer_list<X> or "array of X" and 5061 // all the elements can be implicitly converted to X, the implicit 5062 // conversion sequence is the worst conversion necessary to convert an 5063 // element of the list to X. 5064 // 5065 // C++14 [over.ics.list]p3: 5066 // Otherwise, if the parameter type is "array of N X", if the initializer 5067 // list has exactly N elements or if it has fewer than N elements and X is 5068 // default-constructible, and if all the elements of the initializer list 5069 // can be implicitly converted to X, the implicit conversion sequence is 5070 // the worst conversion necessary to convert an element of the list to X. 5071 if (AT || S.isStdInitializerList(ToType, &InitTy)) { 5072 unsigned e = From->getNumInits(); 5073 ImplicitConversionSequence DfltElt; 5074 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5075 QualType()); 5076 QualType ContTy = ToType; 5077 bool IsUnbounded = false; 5078 if (AT) { 5079 InitTy = AT->getElementType(); 5080 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5081 if (CT->getSize().ult(e)) { 5082 // Too many inits, fatally bad 5083 Result.setBad(BadConversionSequence::too_many_initializers, From, 5084 ToType); 5085 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5086 return Result; 5087 } 5088 if (CT->getSize().ugt(e)) { 5089 // Need an init from empty {}, is there one? 5090 InitListExpr EmptyList(S.Context, From->getEndLoc(), None, 5091 From->getEndLoc()); 5092 EmptyList.setType(S.Context.VoidTy); 5093 DfltElt = TryListConversion( 5094 S, &EmptyList, InitTy, SuppressUserConversions, 5095 InOverloadResolution, AllowObjCWritebackConversion); 5096 if (DfltElt.isBad()) { 5097 // No {} init, fatally bad 5098 Result.setBad(BadConversionSequence::too_few_initializers, From, 5099 ToType); 5100 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5101 return Result; 5102 } 5103 } 5104 } else { 5105 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5106 IsUnbounded = true; 5107 if (!e) { 5108 // Cannot convert to zero-sized. 5109 Result.setBad(BadConversionSequence::too_few_initializers, From, 5110 ToType); 5111 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5112 return Result; 5113 } 5114 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5115 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5116 ArrayType::Normal, 0); 5117 } 5118 } 5119 5120 Result.setStandard(); 5121 Result.Standard.setAsIdentityConversion(); 5122 Result.Standard.setFromType(InitTy); 5123 Result.Standard.setAllToTypes(InitTy); 5124 for (unsigned i = 0; i < e; ++i) { 5125 Expr *Init = From->getInit(i); 5126 ImplicitConversionSequence ICS = TryCopyInitialization( 5127 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5128 AllowObjCWritebackConversion); 5129 5130 // Keep the worse conversion seen so far. 5131 // FIXME: Sequences are not totally ordered, so 'worse' can be 5132 // ambiguous. CWG has been informed. 5133 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5134 Result) == 5135 ImplicitConversionSequence::Worse) { 5136 Result = ICS; 5137 // Bail as soon as we find something unconvertible. 5138 if (Result.isBad()) { 5139 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5140 return Result; 5141 } 5142 } 5143 } 5144 5145 // If we needed any implicit {} initialization, compare that now. 5146 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5147 // has been informed that this might not be the best thing. 5148 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5149 S, From->getEndLoc(), DfltElt, Result) == 5150 ImplicitConversionSequence::Worse) 5151 Result = DfltElt; 5152 // Record the type being initialized so that we may compare sequences 5153 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5154 return Result; 5155 } 5156 5157 // C++14 [over.ics.list]p4: 5158 // C++11 [over.ics.list]p3: 5159 // Otherwise, if the parameter is a non-aggregate class X and overload 5160 // resolution chooses a single best constructor [...] the implicit 5161 // conversion sequence is a user-defined conversion sequence. If multiple 5162 // constructors are viable but none is better than the others, the 5163 // implicit conversion sequence is a user-defined conversion sequence. 5164 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5165 // This function can deal with initializer lists. 5166 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5167 AllowedExplicit::None, 5168 InOverloadResolution, /*CStyle=*/false, 5169 AllowObjCWritebackConversion, 5170 /*AllowObjCConversionOnExplicit=*/false); 5171 } 5172 5173 // C++14 [over.ics.list]p5: 5174 // C++11 [over.ics.list]p4: 5175 // Otherwise, if the parameter has an aggregate type which can be 5176 // initialized from the initializer list [...] the implicit conversion 5177 // sequence is a user-defined conversion sequence. 5178 if (ToType->isAggregateType()) { 5179 // Type is an aggregate, argument is an init list. At this point it comes 5180 // down to checking whether the initialization works. 5181 // FIXME: Find out whether this parameter is consumed or not. 5182 InitializedEntity Entity = 5183 InitializedEntity::InitializeParameter(S.Context, ToType, 5184 /*Consumed=*/false); 5185 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5186 From)) { 5187 Result.setUserDefined(); 5188 Result.UserDefined.Before.setAsIdentityConversion(); 5189 // Initializer lists don't have a type. 5190 Result.UserDefined.Before.setFromType(QualType()); 5191 Result.UserDefined.Before.setAllToTypes(QualType()); 5192 5193 Result.UserDefined.After.setAsIdentityConversion(); 5194 Result.UserDefined.After.setFromType(ToType); 5195 Result.UserDefined.After.setAllToTypes(ToType); 5196 Result.UserDefined.ConversionFunction = nullptr; 5197 } 5198 return Result; 5199 } 5200 5201 // C++14 [over.ics.list]p6: 5202 // C++11 [over.ics.list]p5: 5203 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5204 if (ToType->isReferenceType()) { 5205 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5206 // mention initializer lists in any way. So we go by what list- 5207 // initialization would do and try to extrapolate from that. 5208 5209 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5210 5211 // If the initializer list has a single element that is reference-related 5212 // to the parameter type, we initialize the reference from that. 5213 if (From->getNumInits() == 1) { 5214 Expr *Init = From->getInit(0); 5215 5216 QualType T2 = Init->getType(); 5217 5218 // If the initializer is the address of an overloaded function, try 5219 // to resolve the overloaded function. If all goes well, T2 is the 5220 // type of the resulting function. 5221 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5222 DeclAccessPair Found; 5223 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5224 Init, ToType, false, Found)) 5225 T2 = Fn->getType(); 5226 } 5227 5228 // Compute some basic properties of the types and the initializer. 5229 Sema::ReferenceCompareResult RefRelationship = 5230 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5231 5232 if (RefRelationship >= Sema::Ref_Related) { 5233 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5234 SuppressUserConversions, 5235 /*AllowExplicit=*/false); 5236 } 5237 } 5238 5239 // Otherwise, we bind the reference to a temporary created from the 5240 // initializer list. 5241 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5242 InOverloadResolution, 5243 AllowObjCWritebackConversion); 5244 if (Result.isFailure()) 5245 return Result; 5246 assert(!Result.isEllipsis() && 5247 "Sub-initialization cannot result in ellipsis conversion."); 5248 5249 // Can we even bind to a temporary? 5250 if (ToType->isRValueReferenceType() || 5251 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5252 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5253 Result.UserDefined.After; 5254 SCS.ReferenceBinding = true; 5255 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5256 SCS.BindsToRvalue = true; 5257 SCS.BindsToFunctionLvalue = false; 5258 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5259 SCS.ObjCLifetimeConversionBinding = false; 5260 } else 5261 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5262 From, ToType); 5263 return Result; 5264 } 5265 5266 // C++14 [over.ics.list]p7: 5267 // C++11 [over.ics.list]p6: 5268 // Otherwise, if the parameter type is not a class: 5269 if (!ToType->isRecordType()) { 5270 // - if the initializer list has one element that is not itself an 5271 // initializer list, the implicit conversion sequence is the one 5272 // required to convert the element to the parameter type. 5273 unsigned NumInits = From->getNumInits(); 5274 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5275 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5276 SuppressUserConversions, 5277 InOverloadResolution, 5278 AllowObjCWritebackConversion); 5279 // - if the initializer list has no elements, the implicit conversion 5280 // sequence is the identity conversion. 5281 else if (NumInits == 0) { 5282 Result.setStandard(); 5283 Result.Standard.setAsIdentityConversion(); 5284 Result.Standard.setFromType(ToType); 5285 Result.Standard.setAllToTypes(ToType); 5286 } 5287 return Result; 5288 } 5289 5290 // C++14 [over.ics.list]p8: 5291 // C++11 [over.ics.list]p7: 5292 // In all cases other than those enumerated above, no conversion is possible 5293 return Result; 5294 } 5295 5296 /// TryCopyInitialization - Try to copy-initialize a value of type 5297 /// ToType from the expression From. Return the implicit conversion 5298 /// sequence required to pass this argument, which may be a bad 5299 /// conversion sequence (meaning that the argument cannot be passed to 5300 /// a parameter of this type). If @p SuppressUserConversions, then we 5301 /// do not permit any user-defined conversion sequences. 5302 static ImplicitConversionSequence 5303 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5304 bool SuppressUserConversions, 5305 bool InOverloadResolution, 5306 bool AllowObjCWritebackConversion, 5307 bool AllowExplicit) { 5308 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5309 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5310 InOverloadResolution,AllowObjCWritebackConversion); 5311 5312 if (ToType->isReferenceType()) 5313 return TryReferenceInit(S, From, ToType, 5314 /*FIXME:*/ From->getBeginLoc(), 5315 SuppressUserConversions, AllowExplicit); 5316 5317 return TryImplicitConversion(S, From, ToType, 5318 SuppressUserConversions, 5319 AllowedExplicit::None, 5320 InOverloadResolution, 5321 /*CStyle=*/false, 5322 AllowObjCWritebackConversion, 5323 /*AllowObjCConversionOnExplicit=*/false); 5324 } 5325 5326 static bool TryCopyInitialization(const CanQualType FromQTy, 5327 const CanQualType ToQTy, 5328 Sema &S, 5329 SourceLocation Loc, 5330 ExprValueKind FromVK) { 5331 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5332 ImplicitConversionSequence ICS = 5333 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5334 5335 return !ICS.isBad(); 5336 } 5337 5338 /// TryObjectArgumentInitialization - Try to initialize the object 5339 /// parameter of the given member function (@c Method) from the 5340 /// expression @p From. 5341 static ImplicitConversionSequence 5342 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5343 Expr::Classification FromClassification, 5344 CXXMethodDecl *Method, 5345 CXXRecordDecl *ActingContext) { 5346 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5347 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5348 // const volatile object. 5349 Qualifiers Quals = Method->getMethodQualifiers(); 5350 if (isa<CXXDestructorDecl>(Method)) { 5351 Quals.addConst(); 5352 Quals.addVolatile(); 5353 } 5354 5355 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5356 5357 // Set up the conversion sequence as a "bad" conversion, to allow us 5358 // to exit early. 5359 ImplicitConversionSequence ICS; 5360 5361 // We need to have an object of class type. 5362 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5363 FromType = PT->getPointeeType(); 5364 5365 // When we had a pointer, it's implicitly dereferenced, so we 5366 // better have an lvalue. 5367 assert(FromClassification.isLValue()); 5368 } 5369 5370 assert(FromType->isRecordType()); 5371 5372 // C++0x [over.match.funcs]p4: 5373 // For non-static member functions, the type of the implicit object 5374 // parameter is 5375 // 5376 // - "lvalue reference to cv X" for functions declared without a 5377 // ref-qualifier or with the & ref-qualifier 5378 // - "rvalue reference to cv X" for functions declared with the && 5379 // ref-qualifier 5380 // 5381 // where X is the class of which the function is a member and cv is the 5382 // cv-qualification on the member function declaration. 5383 // 5384 // However, when finding an implicit conversion sequence for the argument, we 5385 // are not allowed to perform user-defined conversions 5386 // (C++ [over.match.funcs]p5). We perform a simplified version of 5387 // reference binding here, that allows class rvalues to bind to 5388 // non-constant references. 5389 5390 // First check the qualifiers. 5391 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5392 if (ImplicitParamType.getCVRQualifiers() 5393 != FromTypeCanon.getLocalCVRQualifiers() && 5394 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5395 ICS.setBad(BadConversionSequence::bad_qualifiers, 5396 FromType, ImplicitParamType); 5397 return ICS; 5398 } 5399 5400 if (FromTypeCanon.hasAddressSpace()) { 5401 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5402 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5403 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5404 ICS.setBad(BadConversionSequence::bad_qualifiers, 5405 FromType, ImplicitParamType); 5406 return ICS; 5407 } 5408 } 5409 5410 // Check that we have either the same type or a derived type. It 5411 // affects the conversion rank. 5412 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5413 ImplicitConversionKind SecondKind; 5414 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5415 SecondKind = ICK_Identity; 5416 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5417 SecondKind = ICK_Derived_To_Base; 5418 else { 5419 ICS.setBad(BadConversionSequence::unrelated_class, 5420 FromType, ImplicitParamType); 5421 return ICS; 5422 } 5423 5424 // Check the ref-qualifier. 5425 switch (Method->getRefQualifier()) { 5426 case RQ_None: 5427 // Do nothing; we don't care about lvalueness or rvalueness. 5428 break; 5429 5430 case RQ_LValue: 5431 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5432 // non-const lvalue reference cannot bind to an rvalue 5433 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5434 ImplicitParamType); 5435 return ICS; 5436 } 5437 break; 5438 5439 case RQ_RValue: 5440 if (!FromClassification.isRValue()) { 5441 // rvalue reference cannot bind to an lvalue 5442 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5443 ImplicitParamType); 5444 return ICS; 5445 } 5446 break; 5447 } 5448 5449 // Success. Mark this as a reference binding. 5450 ICS.setStandard(); 5451 ICS.Standard.setAsIdentityConversion(); 5452 ICS.Standard.Second = SecondKind; 5453 ICS.Standard.setFromType(FromType); 5454 ICS.Standard.setAllToTypes(ImplicitParamType); 5455 ICS.Standard.ReferenceBinding = true; 5456 ICS.Standard.DirectBinding = true; 5457 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5458 ICS.Standard.BindsToFunctionLvalue = false; 5459 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5460 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5461 = (Method->getRefQualifier() == RQ_None); 5462 return ICS; 5463 } 5464 5465 /// PerformObjectArgumentInitialization - Perform initialization of 5466 /// the implicit object parameter for the given Method with the given 5467 /// expression. 5468 ExprResult 5469 Sema::PerformObjectArgumentInitialization(Expr *From, 5470 NestedNameSpecifier *Qualifier, 5471 NamedDecl *FoundDecl, 5472 CXXMethodDecl *Method) { 5473 QualType FromRecordType, DestType; 5474 QualType ImplicitParamRecordType = 5475 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5476 5477 Expr::Classification FromClassification; 5478 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5479 FromRecordType = PT->getPointeeType(); 5480 DestType = Method->getThisType(); 5481 FromClassification = Expr::Classification::makeSimpleLValue(); 5482 } else { 5483 FromRecordType = From->getType(); 5484 DestType = ImplicitParamRecordType; 5485 FromClassification = From->Classify(Context); 5486 5487 // When performing member access on a prvalue, materialize a temporary. 5488 if (From->isPRValue()) { 5489 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5490 Method->getRefQualifier() != 5491 RefQualifierKind::RQ_RValue); 5492 } 5493 } 5494 5495 // Note that we always use the true parent context when performing 5496 // the actual argument initialization. 5497 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5498 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5499 Method->getParent()); 5500 if (ICS.isBad()) { 5501 switch (ICS.Bad.Kind) { 5502 case BadConversionSequence::bad_qualifiers: { 5503 Qualifiers FromQs = FromRecordType.getQualifiers(); 5504 Qualifiers ToQs = DestType.getQualifiers(); 5505 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5506 if (CVR) { 5507 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5508 << Method->getDeclName() << FromRecordType << (CVR - 1) 5509 << From->getSourceRange(); 5510 Diag(Method->getLocation(), diag::note_previous_decl) 5511 << Method->getDeclName(); 5512 return ExprError(); 5513 } 5514 break; 5515 } 5516 5517 case BadConversionSequence::lvalue_ref_to_rvalue: 5518 case BadConversionSequence::rvalue_ref_to_lvalue: { 5519 bool IsRValueQualified = 5520 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5521 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5522 << Method->getDeclName() << FromClassification.isRValue() 5523 << IsRValueQualified; 5524 Diag(Method->getLocation(), diag::note_previous_decl) 5525 << Method->getDeclName(); 5526 return ExprError(); 5527 } 5528 5529 case BadConversionSequence::no_conversion: 5530 case BadConversionSequence::unrelated_class: 5531 break; 5532 5533 case BadConversionSequence::too_few_initializers: 5534 case BadConversionSequence::too_many_initializers: 5535 llvm_unreachable("Lists are not objects"); 5536 } 5537 5538 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5539 << ImplicitParamRecordType << FromRecordType 5540 << From->getSourceRange(); 5541 } 5542 5543 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5544 ExprResult FromRes = 5545 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5546 if (FromRes.isInvalid()) 5547 return ExprError(); 5548 From = FromRes.get(); 5549 } 5550 5551 if (!Context.hasSameType(From->getType(), DestType)) { 5552 CastKind CK; 5553 QualType PteeTy = DestType->getPointeeType(); 5554 LangAS DestAS = 5555 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5556 if (FromRecordType.getAddressSpace() != DestAS) 5557 CK = CK_AddressSpaceConversion; 5558 else 5559 CK = CK_NoOp; 5560 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5561 } 5562 return From; 5563 } 5564 5565 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5566 /// expression From to bool (C++0x [conv]p3). 5567 static ImplicitConversionSequence 5568 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5569 // C++ [dcl.init]/17.8: 5570 // - Otherwise, if the initialization is direct-initialization, the source 5571 // type is std::nullptr_t, and the destination type is bool, the initial 5572 // value of the object being initialized is false. 5573 if (From->getType()->isNullPtrType()) 5574 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5575 S.Context.BoolTy, 5576 From->isGLValue()); 5577 5578 // All other direct-initialization of bool is equivalent to an implicit 5579 // conversion to bool in which explicit conversions are permitted. 5580 return TryImplicitConversion(S, From, S.Context.BoolTy, 5581 /*SuppressUserConversions=*/false, 5582 AllowedExplicit::Conversions, 5583 /*InOverloadResolution=*/false, 5584 /*CStyle=*/false, 5585 /*AllowObjCWritebackConversion=*/false, 5586 /*AllowObjCConversionOnExplicit=*/false); 5587 } 5588 5589 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5590 /// of the expression From to bool (C++0x [conv]p3). 5591 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5592 if (checkPlaceholderForOverload(*this, From)) 5593 return ExprError(); 5594 5595 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5596 if (!ICS.isBad()) 5597 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5598 5599 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5600 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5601 << From->getType() << From->getSourceRange(); 5602 return ExprError(); 5603 } 5604 5605 /// Check that the specified conversion is permitted in a converted constant 5606 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5607 /// is acceptable. 5608 static bool CheckConvertedConstantConversions(Sema &S, 5609 StandardConversionSequence &SCS) { 5610 // Since we know that the target type is an integral or unscoped enumeration 5611 // type, most conversion kinds are impossible. All possible First and Third 5612 // conversions are fine. 5613 switch (SCS.Second) { 5614 case ICK_Identity: 5615 case ICK_Integral_Promotion: 5616 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5617 case ICK_Zero_Queue_Conversion: 5618 return true; 5619 5620 case ICK_Boolean_Conversion: 5621 // Conversion from an integral or unscoped enumeration type to bool is 5622 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5623 // conversion, so we allow it in a converted constant expression. 5624 // 5625 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5626 // a lot of popular code. We should at least add a warning for this 5627 // (non-conforming) extension. 5628 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5629 SCS.getToType(2)->isBooleanType(); 5630 5631 case ICK_Pointer_Conversion: 5632 case ICK_Pointer_Member: 5633 // C++1z: null pointer conversions and null member pointer conversions are 5634 // only permitted if the source type is std::nullptr_t. 5635 return SCS.getFromType()->isNullPtrType(); 5636 5637 case ICK_Floating_Promotion: 5638 case ICK_Complex_Promotion: 5639 case ICK_Floating_Conversion: 5640 case ICK_Complex_Conversion: 5641 case ICK_Floating_Integral: 5642 case ICK_Compatible_Conversion: 5643 case ICK_Derived_To_Base: 5644 case ICK_Vector_Conversion: 5645 case ICK_SVE_Vector_Conversion: 5646 case ICK_Vector_Splat: 5647 case ICK_Complex_Real: 5648 case ICK_Block_Pointer_Conversion: 5649 case ICK_TransparentUnionConversion: 5650 case ICK_Writeback_Conversion: 5651 case ICK_Zero_Event_Conversion: 5652 case ICK_C_Only_Conversion: 5653 case ICK_Incompatible_Pointer_Conversion: 5654 return false; 5655 5656 case ICK_Lvalue_To_Rvalue: 5657 case ICK_Array_To_Pointer: 5658 case ICK_Function_To_Pointer: 5659 llvm_unreachable("found a first conversion kind in Second"); 5660 5661 case ICK_Function_Conversion: 5662 case ICK_Qualification: 5663 llvm_unreachable("found a third conversion kind in Second"); 5664 5665 case ICK_Num_Conversion_Kinds: 5666 break; 5667 } 5668 5669 llvm_unreachable("unknown conversion kind"); 5670 } 5671 5672 /// CheckConvertedConstantExpression - Check that the expression From is a 5673 /// converted constant expression of type T, perform the conversion and produce 5674 /// the converted expression, per C++11 [expr.const]p3. 5675 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5676 QualType T, APValue &Value, 5677 Sema::CCEKind CCE, 5678 bool RequireInt, 5679 NamedDecl *Dest) { 5680 assert(S.getLangOpts().CPlusPlus11 && 5681 "converted constant expression outside C++11"); 5682 5683 if (checkPlaceholderForOverload(S, From)) 5684 return ExprError(); 5685 5686 // C++1z [expr.const]p3: 5687 // A converted constant expression of type T is an expression, 5688 // implicitly converted to type T, where the converted 5689 // expression is a constant expression and the implicit conversion 5690 // sequence contains only [... list of conversions ...]. 5691 ImplicitConversionSequence ICS = 5692 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 5693 ? TryContextuallyConvertToBool(S, From) 5694 : TryCopyInitialization(S, From, T, 5695 /*SuppressUserConversions=*/false, 5696 /*InOverloadResolution=*/false, 5697 /*AllowObjCWritebackConversion=*/false, 5698 /*AllowExplicit=*/false); 5699 StandardConversionSequence *SCS = nullptr; 5700 switch (ICS.getKind()) { 5701 case ImplicitConversionSequence::StandardConversion: 5702 SCS = &ICS.Standard; 5703 break; 5704 case ImplicitConversionSequence::UserDefinedConversion: 5705 if (T->isRecordType()) 5706 SCS = &ICS.UserDefined.Before; 5707 else 5708 SCS = &ICS.UserDefined.After; 5709 break; 5710 case ImplicitConversionSequence::AmbiguousConversion: 5711 case ImplicitConversionSequence::BadConversion: 5712 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5713 return S.Diag(From->getBeginLoc(), 5714 diag::err_typecheck_converted_constant_expression) 5715 << From->getType() << From->getSourceRange() << T; 5716 return ExprError(); 5717 5718 case ImplicitConversionSequence::EllipsisConversion: 5719 llvm_unreachable("ellipsis conversion in converted constant expression"); 5720 } 5721 5722 // Check that we would only use permitted conversions. 5723 if (!CheckConvertedConstantConversions(S, *SCS)) { 5724 return S.Diag(From->getBeginLoc(), 5725 diag::err_typecheck_converted_constant_expression_disallowed) 5726 << From->getType() << From->getSourceRange() << T; 5727 } 5728 // [...] and where the reference binding (if any) binds directly. 5729 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5730 return S.Diag(From->getBeginLoc(), 5731 diag::err_typecheck_converted_constant_expression_indirect) 5732 << From->getType() << From->getSourceRange() << T; 5733 } 5734 5735 // Usually we can simply apply the ImplicitConversionSequence we formed 5736 // earlier, but that's not guaranteed to work when initializing an object of 5737 // class type. 5738 ExprResult Result; 5739 if (T->isRecordType()) { 5740 assert(CCE == Sema::CCEK_TemplateArg && 5741 "unexpected class type converted constant expr"); 5742 Result = S.PerformCopyInitialization( 5743 InitializedEntity::InitializeTemplateParameter( 5744 T, cast<NonTypeTemplateParmDecl>(Dest)), 5745 SourceLocation(), From); 5746 } else { 5747 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5748 } 5749 if (Result.isInvalid()) 5750 return Result; 5751 5752 // C++2a [intro.execution]p5: 5753 // A full-expression is [...] a constant-expression [...] 5754 Result = 5755 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5756 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5757 if (Result.isInvalid()) 5758 return Result; 5759 5760 // Check for a narrowing implicit conversion. 5761 bool ReturnPreNarrowingValue = false; 5762 APValue PreNarrowingValue; 5763 QualType PreNarrowingType; 5764 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5765 PreNarrowingType)) { 5766 case NK_Dependent_Narrowing: 5767 // Implicit conversion to a narrower type, but the expression is 5768 // value-dependent so we can't tell whether it's actually narrowing. 5769 case NK_Variable_Narrowing: 5770 // Implicit conversion to a narrower type, and the value is not a constant 5771 // expression. We'll diagnose this in a moment. 5772 case NK_Not_Narrowing: 5773 break; 5774 5775 case NK_Constant_Narrowing: 5776 if (CCE == Sema::CCEK_ArrayBound && 5777 PreNarrowingType->isIntegralOrEnumerationType() && 5778 PreNarrowingValue.isInt()) { 5779 // Don't diagnose array bound narrowing here; we produce more precise 5780 // errors by allowing the un-narrowed value through. 5781 ReturnPreNarrowingValue = true; 5782 break; 5783 } 5784 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5785 << CCE << /*Constant*/ 1 5786 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5787 break; 5788 5789 case NK_Type_Narrowing: 5790 // FIXME: It would be better to diagnose that the expression is not a 5791 // constant expression. 5792 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5793 << CCE << /*Constant*/ 0 << From->getType() << T; 5794 break; 5795 } 5796 5797 if (Result.get()->isValueDependent()) { 5798 Value = APValue(); 5799 return Result; 5800 } 5801 5802 // Check the expression is a constant expression. 5803 SmallVector<PartialDiagnosticAt, 8> Notes; 5804 Expr::EvalResult Eval; 5805 Eval.Diag = &Notes; 5806 5807 ConstantExprKind Kind; 5808 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5809 Kind = ConstantExprKind::ClassTemplateArgument; 5810 else if (CCE == Sema::CCEK_TemplateArg) 5811 Kind = ConstantExprKind::NonClassTemplateArgument; 5812 else 5813 Kind = ConstantExprKind::Normal; 5814 5815 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5816 (RequireInt && !Eval.Val.isInt())) { 5817 // The expression can't be folded, so we can't keep it at this position in 5818 // the AST. 5819 Result = ExprError(); 5820 } else { 5821 Value = Eval.Val; 5822 5823 if (Notes.empty()) { 5824 // It's a constant expression. 5825 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5826 if (ReturnPreNarrowingValue) 5827 Value = std::move(PreNarrowingValue); 5828 return E; 5829 } 5830 } 5831 5832 // It's not a constant expression. Produce an appropriate diagnostic. 5833 if (Notes.size() == 1 && 5834 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5835 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5836 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5837 diag::note_constexpr_invalid_template_arg) { 5838 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5839 for (unsigned I = 0; I < Notes.size(); ++I) 5840 S.Diag(Notes[I].first, Notes[I].second); 5841 } else { 5842 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5843 << CCE << From->getSourceRange(); 5844 for (unsigned I = 0; I < Notes.size(); ++I) 5845 S.Diag(Notes[I].first, Notes[I].second); 5846 } 5847 return ExprError(); 5848 } 5849 5850 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5851 APValue &Value, CCEKind CCE, 5852 NamedDecl *Dest) { 5853 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5854 Dest); 5855 } 5856 5857 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5858 llvm::APSInt &Value, 5859 CCEKind CCE) { 5860 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5861 5862 APValue V; 5863 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5864 /*Dest=*/nullptr); 5865 if (!R.isInvalid() && !R.get()->isValueDependent()) 5866 Value = V.getInt(); 5867 return R; 5868 } 5869 5870 5871 /// dropPointerConversions - If the given standard conversion sequence 5872 /// involves any pointer conversions, remove them. This may change 5873 /// the result type of the conversion sequence. 5874 static void dropPointerConversion(StandardConversionSequence &SCS) { 5875 if (SCS.Second == ICK_Pointer_Conversion) { 5876 SCS.Second = ICK_Identity; 5877 SCS.Third = ICK_Identity; 5878 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5879 } 5880 } 5881 5882 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5883 /// convert the expression From to an Objective-C pointer type. 5884 static ImplicitConversionSequence 5885 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5886 // Do an implicit conversion to 'id'. 5887 QualType Ty = S.Context.getObjCIdType(); 5888 ImplicitConversionSequence ICS 5889 = TryImplicitConversion(S, From, Ty, 5890 // FIXME: Are these flags correct? 5891 /*SuppressUserConversions=*/false, 5892 AllowedExplicit::Conversions, 5893 /*InOverloadResolution=*/false, 5894 /*CStyle=*/false, 5895 /*AllowObjCWritebackConversion=*/false, 5896 /*AllowObjCConversionOnExplicit=*/true); 5897 5898 // Strip off any final conversions to 'id'. 5899 switch (ICS.getKind()) { 5900 case ImplicitConversionSequence::BadConversion: 5901 case ImplicitConversionSequence::AmbiguousConversion: 5902 case ImplicitConversionSequence::EllipsisConversion: 5903 break; 5904 5905 case ImplicitConversionSequence::UserDefinedConversion: 5906 dropPointerConversion(ICS.UserDefined.After); 5907 break; 5908 5909 case ImplicitConversionSequence::StandardConversion: 5910 dropPointerConversion(ICS.Standard); 5911 break; 5912 } 5913 5914 return ICS; 5915 } 5916 5917 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5918 /// conversion of the expression From to an Objective-C pointer type. 5919 /// Returns a valid but null ExprResult if no conversion sequence exists. 5920 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5921 if (checkPlaceholderForOverload(*this, From)) 5922 return ExprError(); 5923 5924 QualType Ty = Context.getObjCIdType(); 5925 ImplicitConversionSequence ICS = 5926 TryContextuallyConvertToObjCPointer(*this, From); 5927 if (!ICS.isBad()) 5928 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5929 return ExprResult(); 5930 } 5931 5932 /// Determine whether the provided type is an integral type, or an enumeration 5933 /// type of a permitted flavor. 5934 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5935 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5936 : T->isIntegralOrUnscopedEnumerationType(); 5937 } 5938 5939 static ExprResult 5940 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5941 Sema::ContextualImplicitConverter &Converter, 5942 QualType T, UnresolvedSetImpl &ViableConversions) { 5943 5944 if (Converter.Suppress) 5945 return ExprError(); 5946 5947 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5948 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5949 CXXConversionDecl *Conv = 5950 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5951 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5952 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5953 } 5954 return From; 5955 } 5956 5957 static bool 5958 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5959 Sema::ContextualImplicitConverter &Converter, 5960 QualType T, bool HadMultipleCandidates, 5961 UnresolvedSetImpl &ExplicitConversions) { 5962 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5963 DeclAccessPair Found = ExplicitConversions[0]; 5964 CXXConversionDecl *Conversion = 5965 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5966 5967 // The user probably meant to invoke the given explicit 5968 // conversion; use it. 5969 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5970 std::string TypeStr; 5971 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5972 5973 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5974 << FixItHint::CreateInsertion(From->getBeginLoc(), 5975 "static_cast<" + TypeStr + ">(") 5976 << FixItHint::CreateInsertion( 5977 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5978 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5979 5980 // If we aren't in a SFINAE context, build a call to the 5981 // explicit conversion function. 5982 if (SemaRef.isSFINAEContext()) 5983 return true; 5984 5985 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5986 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5987 HadMultipleCandidates); 5988 if (Result.isInvalid()) 5989 return true; 5990 // Record usage of conversion in an implicit cast. 5991 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5992 CK_UserDefinedConversion, Result.get(), 5993 nullptr, Result.get()->getValueKind(), 5994 SemaRef.CurFPFeatureOverrides()); 5995 } 5996 return false; 5997 } 5998 5999 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6000 Sema::ContextualImplicitConverter &Converter, 6001 QualType T, bool HadMultipleCandidates, 6002 DeclAccessPair &Found) { 6003 CXXConversionDecl *Conversion = 6004 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6005 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6006 6007 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6008 if (!Converter.SuppressConversion) { 6009 if (SemaRef.isSFINAEContext()) 6010 return true; 6011 6012 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6013 << From->getSourceRange(); 6014 } 6015 6016 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6017 HadMultipleCandidates); 6018 if (Result.isInvalid()) 6019 return true; 6020 // Record usage of conversion in an implicit cast. 6021 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6022 CK_UserDefinedConversion, Result.get(), 6023 nullptr, Result.get()->getValueKind(), 6024 SemaRef.CurFPFeatureOverrides()); 6025 return false; 6026 } 6027 6028 static ExprResult finishContextualImplicitConversion( 6029 Sema &SemaRef, SourceLocation Loc, Expr *From, 6030 Sema::ContextualImplicitConverter &Converter) { 6031 if (!Converter.match(From->getType()) && !Converter.Suppress) 6032 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6033 << From->getSourceRange(); 6034 6035 return SemaRef.DefaultLvalueConversion(From); 6036 } 6037 6038 static void 6039 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6040 UnresolvedSetImpl &ViableConversions, 6041 OverloadCandidateSet &CandidateSet) { 6042 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6043 DeclAccessPair FoundDecl = ViableConversions[I]; 6044 NamedDecl *D = FoundDecl.getDecl(); 6045 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6046 if (isa<UsingShadowDecl>(D)) 6047 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6048 6049 CXXConversionDecl *Conv; 6050 FunctionTemplateDecl *ConvTemplate; 6051 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6052 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6053 else 6054 Conv = cast<CXXConversionDecl>(D); 6055 6056 if (ConvTemplate) 6057 SemaRef.AddTemplateConversionCandidate( 6058 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6059 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6060 else 6061 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6062 ToType, CandidateSet, 6063 /*AllowObjCConversionOnExplicit=*/false, 6064 /*AllowExplicit*/ true); 6065 } 6066 } 6067 6068 /// Attempt to convert the given expression to a type which is accepted 6069 /// by the given converter. 6070 /// 6071 /// This routine will attempt to convert an expression of class type to a 6072 /// type accepted by the specified converter. In C++11 and before, the class 6073 /// must have a single non-explicit conversion function converting to a matching 6074 /// type. In C++1y, there can be multiple such conversion functions, but only 6075 /// one target type. 6076 /// 6077 /// \param Loc The source location of the construct that requires the 6078 /// conversion. 6079 /// 6080 /// \param From The expression we're converting from. 6081 /// 6082 /// \param Converter Used to control and diagnose the conversion process. 6083 /// 6084 /// \returns The expression, converted to an integral or enumeration type if 6085 /// successful. 6086 ExprResult Sema::PerformContextualImplicitConversion( 6087 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6088 // We can't perform any more checking for type-dependent expressions. 6089 if (From->isTypeDependent()) 6090 return From; 6091 6092 // Process placeholders immediately. 6093 if (From->hasPlaceholderType()) { 6094 ExprResult result = CheckPlaceholderExpr(From); 6095 if (result.isInvalid()) 6096 return result; 6097 From = result.get(); 6098 } 6099 6100 // If the expression already has a matching type, we're golden. 6101 QualType T = From->getType(); 6102 if (Converter.match(T)) 6103 return DefaultLvalueConversion(From); 6104 6105 // FIXME: Check for missing '()' if T is a function type? 6106 6107 // We can only perform contextual implicit conversions on objects of class 6108 // type. 6109 const RecordType *RecordTy = T->getAs<RecordType>(); 6110 if (!RecordTy || !getLangOpts().CPlusPlus) { 6111 if (!Converter.Suppress) 6112 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6113 return From; 6114 } 6115 6116 // We must have a complete class type. 6117 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6118 ContextualImplicitConverter &Converter; 6119 Expr *From; 6120 6121 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6122 : Converter(Converter), From(From) {} 6123 6124 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6125 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6126 } 6127 } IncompleteDiagnoser(Converter, From); 6128 6129 if (Converter.Suppress ? !isCompleteType(Loc, T) 6130 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6131 return From; 6132 6133 // Look for a conversion to an integral or enumeration type. 6134 UnresolvedSet<4> 6135 ViableConversions; // These are *potentially* viable in C++1y. 6136 UnresolvedSet<4> ExplicitConversions; 6137 const auto &Conversions = 6138 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6139 6140 bool HadMultipleCandidates = 6141 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6142 6143 // To check that there is only one target type, in C++1y: 6144 QualType ToType; 6145 bool HasUniqueTargetType = true; 6146 6147 // Collect explicit or viable (potentially in C++1y) conversions. 6148 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6149 NamedDecl *D = (*I)->getUnderlyingDecl(); 6150 CXXConversionDecl *Conversion; 6151 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6152 if (ConvTemplate) { 6153 if (getLangOpts().CPlusPlus14) 6154 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6155 else 6156 continue; // C++11 does not consider conversion operator templates(?). 6157 } else 6158 Conversion = cast<CXXConversionDecl>(D); 6159 6160 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6161 "Conversion operator templates are considered potentially " 6162 "viable in C++1y"); 6163 6164 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6165 if (Converter.match(CurToType) || ConvTemplate) { 6166 6167 if (Conversion->isExplicit()) { 6168 // FIXME: For C++1y, do we need this restriction? 6169 // cf. diagnoseNoViableConversion() 6170 if (!ConvTemplate) 6171 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6172 } else { 6173 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6174 if (ToType.isNull()) 6175 ToType = CurToType.getUnqualifiedType(); 6176 else if (HasUniqueTargetType && 6177 (CurToType.getUnqualifiedType() != ToType)) 6178 HasUniqueTargetType = false; 6179 } 6180 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6181 } 6182 } 6183 } 6184 6185 if (getLangOpts().CPlusPlus14) { 6186 // C++1y [conv]p6: 6187 // ... An expression e of class type E appearing in such a context 6188 // is said to be contextually implicitly converted to a specified 6189 // type T and is well-formed if and only if e can be implicitly 6190 // converted to a type T that is determined as follows: E is searched 6191 // for conversion functions whose return type is cv T or reference to 6192 // cv T such that T is allowed by the context. There shall be 6193 // exactly one such T. 6194 6195 // If no unique T is found: 6196 if (ToType.isNull()) { 6197 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6198 HadMultipleCandidates, 6199 ExplicitConversions)) 6200 return ExprError(); 6201 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6202 } 6203 6204 // If more than one unique Ts are found: 6205 if (!HasUniqueTargetType) 6206 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6207 ViableConversions); 6208 6209 // If one unique T is found: 6210 // First, build a candidate set from the previously recorded 6211 // potentially viable conversions. 6212 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6213 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6214 CandidateSet); 6215 6216 // Then, perform overload resolution over the candidate set. 6217 OverloadCandidateSet::iterator Best; 6218 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6219 case OR_Success: { 6220 // Apply this conversion. 6221 DeclAccessPair Found = 6222 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6223 if (recordConversion(*this, Loc, From, Converter, T, 6224 HadMultipleCandidates, Found)) 6225 return ExprError(); 6226 break; 6227 } 6228 case OR_Ambiguous: 6229 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6230 ViableConversions); 6231 case OR_No_Viable_Function: 6232 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6233 HadMultipleCandidates, 6234 ExplicitConversions)) 6235 return ExprError(); 6236 LLVM_FALLTHROUGH; 6237 case OR_Deleted: 6238 // We'll complain below about a non-integral condition type. 6239 break; 6240 } 6241 } else { 6242 switch (ViableConversions.size()) { 6243 case 0: { 6244 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6245 HadMultipleCandidates, 6246 ExplicitConversions)) 6247 return ExprError(); 6248 6249 // We'll complain below about a non-integral condition type. 6250 break; 6251 } 6252 case 1: { 6253 // Apply this conversion. 6254 DeclAccessPair Found = ViableConversions[0]; 6255 if (recordConversion(*this, Loc, From, Converter, T, 6256 HadMultipleCandidates, Found)) 6257 return ExprError(); 6258 break; 6259 } 6260 default: 6261 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6262 ViableConversions); 6263 } 6264 } 6265 6266 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6267 } 6268 6269 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6270 /// an acceptable non-member overloaded operator for a call whose 6271 /// arguments have types T1 (and, if non-empty, T2). This routine 6272 /// implements the check in C++ [over.match.oper]p3b2 concerning 6273 /// enumeration types. 6274 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6275 FunctionDecl *Fn, 6276 ArrayRef<Expr *> Args) { 6277 QualType T1 = Args[0]->getType(); 6278 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6279 6280 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6281 return true; 6282 6283 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6284 return true; 6285 6286 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6287 if (Proto->getNumParams() < 1) 6288 return false; 6289 6290 if (T1->isEnumeralType()) { 6291 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6292 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6293 return true; 6294 } 6295 6296 if (Proto->getNumParams() < 2) 6297 return false; 6298 6299 if (!T2.isNull() && T2->isEnumeralType()) { 6300 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6301 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6302 return true; 6303 } 6304 6305 return false; 6306 } 6307 6308 /// AddOverloadCandidate - Adds the given function to the set of 6309 /// candidate functions, using the given function call arguments. If 6310 /// @p SuppressUserConversions, then don't allow user-defined 6311 /// conversions via constructors or conversion operators. 6312 /// 6313 /// \param PartialOverloading true if we are performing "partial" overloading 6314 /// based on an incomplete set of function arguments. This feature is used by 6315 /// code completion. 6316 void Sema::AddOverloadCandidate( 6317 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6318 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6319 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6320 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6321 OverloadCandidateParamOrder PO) { 6322 const FunctionProtoType *Proto 6323 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6324 assert(Proto && "Functions without a prototype cannot be overloaded"); 6325 assert(!Function->getDescribedFunctionTemplate() && 6326 "Use AddTemplateOverloadCandidate for function templates"); 6327 6328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6329 if (!isa<CXXConstructorDecl>(Method)) { 6330 // If we get here, it's because we're calling a member function 6331 // that is named without a member access expression (e.g., 6332 // "this->f") that was either written explicitly or created 6333 // implicitly. This can happen with a qualified call to a member 6334 // function, e.g., X::f(). We use an empty type for the implied 6335 // object argument (C++ [over.call.func]p3), and the acting context 6336 // is irrelevant. 6337 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6338 Expr::Classification::makeSimpleLValue(), Args, 6339 CandidateSet, SuppressUserConversions, 6340 PartialOverloading, EarlyConversions, PO); 6341 return; 6342 } 6343 // We treat a constructor like a non-member function, since its object 6344 // argument doesn't participate in overload resolution. 6345 } 6346 6347 if (!CandidateSet.isNewCandidate(Function, PO)) 6348 return; 6349 6350 // C++11 [class.copy]p11: [DR1402] 6351 // A defaulted move constructor that is defined as deleted is ignored by 6352 // overload resolution. 6353 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6354 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6355 Constructor->isMoveConstructor()) 6356 return; 6357 6358 // Overload resolution is always an unevaluated context. 6359 EnterExpressionEvaluationContext Unevaluated( 6360 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6361 6362 // C++ [over.match.oper]p3: 6363 // if no operand has a class type, only those non-member functions in the 6364 // lookup set that have a first parameter of type T1 or "reference to 6365 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6366 // is a right operand) a second parameter of type T2 or "reference to 6367 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6368 // candidate functions. 6369 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6370 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6371 return; 6372 6373 // Add this candidate 6374 OverloadCandidate &Candidate = 6375 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6376 Candidate.FoundDecl = FoundDecl; 6377 Candidate.Function = Function; 6378 Candidate.Viable = true; 6379 Candidate.RewriteKind = 6380 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6381 Candidate.IsSurrogate = false; 6382 Candidate.IsADLCandidate = IsADLCandidate; 6383 Candidate.IgnoreObjectArgument = false; 6384 Candidate.ExplicitCallArguments = Args.size(); 6385 6386 // Explicit functions are not actually candidates at all if we're not 6387 // allowing them in this context, but keep them around so we can point 6388 // to them in diagnostics. 6389 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6390 Candidate.Viable = false; 6391 Candidate.FailureKind = ovl_fail_explicit; 6392 return; 6393 } 6394 6395 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6396 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6397 Candidate.Viable = false; 6398 Candidate.FailureKind = ovl_non_default_multiversion_function; 6399 return; 6400 } 6401 6402 if (Constructor) { 6403 // C++ [class.copy]p3: 6404 // A member function template is never instantiated to perform the copy 6405 // of a class object to an object of its class type. 6406 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6407 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6408 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6409 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6410 ClassType))) { 6411 Candidate.Viable = false; 6412 Candidate.FailureKind = ovl_fail_illegal_constructor; 6413 return; 6414 } 6415 6416 // C++ [over.match.funcs]p8: (proposed DR resolution) 6417 // A constructor inherited from class type C that has a first parameter 6418 // of type "reference to P" (including such a constructor instantiated 6419 // from a template) is excluded from the set of candidate functions when 6420 // constructing an object of type cv D if the argument list has exactly 6421 // one argument and D is reference-related to P and P is reference-related 6422 // to C. 6423 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6424 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6425 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6426 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6427 QualType C = Context.getRecordType(Constructor->getParent()); 6428 QualType D = Context.getRecordType(Shadow->getParent()); 6429 SourceLocation Loc = Args.front()->getExprLoc(); 6430 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6431 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6432 Candidate.Viable = false; 6433 Candidate.FailureKind = ovl_fail_inhctor_slice; 6434 return; 6435 } 6436 } 6437 6438 // Check that the constructor is capable of constructing an object in the 6439 // destination address space. 6440 if (!Qualifiers::isAddressSpaceSupersetOf( 6441 Constructor->getMethodQualifiers().getAddressSpace(), 6442 CandidateSet.getDestAS())) { 6443 Candidate.Viable = false; 6444 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6445 } 6446 } 6447 6448 unsigned NumParams = Proto->getNumParams(); 6449 6450 // (C++ 13.3.2p2): A candidate function having fewer than m 6451 // parameters is viable only if it has an ellipsis in its parameter 6452 // list (8.3.5). 6453 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6454 !Proto->isVariadic() && 6455 shouldEnforceArgLimit(PartialOverloading, Function)) { 6456 Candidate.Viable = false; 6457 Candidate.FailureKind = ovl_fail_too_many_arguments; 6458 return; 6459 } 6460 6461 // (C++ 13.3.2p2): A candidate function having more than m parameters 6462 // is viable only if the (m+1)st parameter has a default argument 6463 // (8.3.6). For the purposes of overload resolution, the 6464 // parameter list is truncated on the right, so that there are 6465 // exactly m parameters. 6466 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6467 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6468 // Not enough arguments. 6469 Candidate.Viable = false; 6470 Candidate.FailureKind = ovl_fail_too_few_arguments; 6471 return; 6472 } 6473 6474 // (CUDA B.1): Check for invalid calls between targets. 6475 if (getLangOpts().CUDA) 6476 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6477 // Skip the check for callers that are implicit members, because in this 6478 // case we may not yet know what the member's target is; the target is 6479 // inferred for the member automatically, based on the bases and fields of 6480 // the class. 6481 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6482 Candidate.Viable = false; 6483 Candidate.FailureKind = ovl_fail_bad_target; 6484 return; 6485 } 6486 6487 if (Function->getTrailingRequiresClause()) { 6488 ConstraintSatisfaction Satisfaction; 6489 if (CheckFunctionConstraints(Function, Satisfaction) || 6490 !Satisfaction.IsSatisfied) { 6491 Candidate.Viable = false; 6492 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6493 return; 6494 } 6495 } 6496 6497 // Determine the implicit conversion sequences for each of the 6498 // arguments. 6499 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6500 unsigned ConvIdx = 6501 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6502 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6503 // We already formed a conversion sequence for this parameter during 6504 // template argument deduction. 6505 } else if (ArgIdx < NumParams) { 6506 // (C++ 13.3.2p3): for F to be a viable function, there shall 6507 // exist for each argument an implicit conversion sequence 6508 // (13.3.3.1) that converts that argument to the corresponding 6509 // parameter of F. 6510 QualType ParamType = Proto->getParamType(ArgIdx); 6511 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6512 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6513 /*InOverloadResolution=*/true, 6514 /*AllowObjCWritebackConversion=*/ 6515 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6516 if (Candidate.Conversions[ConvIdx].isBad()) { 6517 Candidate.Viable = false; 6518 Candidate.FailureKind = ovl_fail_bad_conversion; 6519 return; 6520 } 6521 } else { 6522 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6523 // argument for which there is no corresponding parameter is 6524 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6525 Candidate.Conversions[ConvIdx].setEllipsis(); 6526 } 6527 } 6528 6529 if (EnableIfAttr *FailedAttr = 6530 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6531 Candidate.Viable = false; 6532 Candidate.FailureKind = ovl_fail_enable_if; 6533 Candidate.DeductionFailure.Data = FailedAttr; 6534 return; 6535 } 6536 } 6537 6538 ObjCMethodDecl * 6539 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6540 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6541 if (Methods.size() <= 1) 6542 return nullptr; 6543 6544 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6545 bool Match = true; 6546 ObjCMethodDecl *Method = Methods[b]; 6547 unsigned NumNamedArgs = Sel.getNumArgs(); 6548 // Method might have more arguments than selector indicates. This is due 6549 // to addition of c-style arguments in method. 6550 if (Method->param_size() > NumNamedArgs) 6551 NumNamedArgs = Method->param_size(); 6552 if (Args.size() < NumNamedArgs) 6553 continue; 6554 6555 for (unsigned i = 0; i < NumNamedArgs; i++) { 6556 // We can't do any type-checking on a type-dependent argument. 6557 if (Args[i]->isTypeDependent()) { 6558 Match = false; 6559 break; 6560 } 6561 6562 ParmVarDecl *param = Method->parameters()[i]; 6563 Expr *argExpr = Args[i]; 6564 assert(argExpr && "SelectBestMethod(): missing expression"); 6565 6566 // Strip the unbridged-cast placeholder expression off unless it's 6567 // a consumed argument. 6568 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6569 !param->hasAttr<CFConsumedAttr>()) 6570 argExpr = stripARCUnbridgedCast(argExpr); 6571 6572 // If the parameter is __unknown_anytype, move on to the next method. 6573 if (param->getType() == Context.UnknownAnyTy) { 6574 Match = false; 6575 break; 6576 } 6577 6578 ImplicitConversionSequence ConversionState 6579 = TryCopyInitialization(*this, argExpr, param->getType(), 6580 /*SuppressUserConversions*/false, 6581 /*InOverloadResolution=*/true, 6582 /*AllowObjCWritebackConversion=*/ 6583 getLangOpts().ObjCAutoRefCount, 6584 /*AllowExplicit*/false); 6585 // This function looks for a reasonably-exact match, so we consider 6586 // incompatible pointer conversions to be a failure here. 6587 if (ConversionState.isBad() || 6588 (ConversionState.isStandard() && 6589 ConversionState.Standard.Second == 6590 ICK_Incompatible_Pointer_Conversion)) { 6591 Match = false; 6592 break; 6593 } 6594 } 6595 // Promote additional arguments to variadic methods. 6596 if (Match && Method->isVariadic()) { 6597 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6598 if (Args[i]->isTypeDependent()) { 6599 Match = false; 6600 break; 6601 } 6602 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6603 nullptr); 6604 if (Arg.isInvalid()) { 6605 Match = false; 6606 break; 6607 } 6608 } 6609 } else { 6610 // Check for extra arguments to non-variadic methods. 6611 if (Args.size() != NumNamedArgs) 6612 Match = false; 6613 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6614 // Special case when selectors have no argument. In this case, select 6615 // one with the most general result type of 'id'. 6616 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6617 QualType ReturnT = Methods[b]->getReturnType(); 6618 if (ReturnT->isObjCIdType()) 6619 return Methods[b]; 6620 } 6621 } 6622 } 6623 6624 if (Match) 6625 return Method; 6626 } 6627 return nullptr; 6628 } 6629 6630 static bool convertArgsForAvailabilityChecks( 6631 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6632 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6633 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6634 if (ThisArg) { 6635 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6636 assert(!isa<CXXConstructorDecl>(Method) && 6637 "Shouldn't have `this` for ctors!"); 6638 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6639 ExprResult R = S.PerformObjectArgumentInitialization( 6640 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6641 if (R.isInvalid()) 6642 return false; 6643 ConvertedThis = R.get(); 6644 } else { 6645 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6646 (void)MD; 6647 assert((MissingImplicitThis || MD->isStatic() || 6648 isa<CXXConstructorDecl>(MD)) && 6649 "Expected `this` for non-ctor instance methods"); 6650 } 6651 ConvertedThis = nullptr; 6652 } 6653 6654 // Ignore any variadic arguments. Converting them is pointless, since the 6655 // user can't refer to them in the function condition. 6656 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6657 6658 // Convert the arguments. 6659 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6660 ExprResult R; 6661 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6662 S.Context, Function->getParamDecl(I)), 6663 SourceLocation(), Args[I]); 6664 6665 if (R.isInvalid()) 6666 return false; 6667 6668 ConvertedArgs.push_back(R.get()); 6669 } 6670 6671 if (Trap.hasErrorOccurred()) 6672 return false; 6673 6674 // Push default arguments if needed. 6675 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6676 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6677 ParmVarDecl *P = Function->getParamDecl(i); 6678 if (!P->hasDefaultArg()) 6679 return false; 6680 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6681 if (R.isInvalid()) 6682 return false; 6683 ConvertedArgs.push_back(R.get()); 6684 } 6685 6686 if (Trap.hasErrorOccurred()) 6687 return false; 6688 } 6689 return true; 6690 } 6691 6692 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6693 SourceLocation CallLoc, 6694 ArrayRef<Expr *> Args, 6695 bool MissingImplicitThis) { 6696 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6697 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6698 return nullptr; 6699 6700 SFINAETrap Trap(*this); 6701 SmallVector<Expr *, 16> ConvertedArgs; 6702 // FIXME: We should look into making enable_if late-parsed. 6703 Expr *DiscardedThis; 6704 if (!convertArgsForAvailabilityChecks( 6705 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6706 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6707 return *EnableIfAttrs.begin(); 6708 6709 for (auto *EIA : EnableIfAttrs) { 6710 APValue Result; 6711 // FIXME: This doesn't consider value-dependent cases, because doing so is 6712 // very difficult. Ideally, we should handle them more gracefully. 6713 if (EIA->getCond()->isValueDependent() || 6714 !EIA->getCond()->EvaluateWithSubstitution( 6715 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6716 return EIA; 6717 6718 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6719 return EIA; 6720 } 6721 return nullptr; 6722 } 6723 6724 template <typename CheckFn> 6725 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6726 bool ArgDependent, SourceLocation Loc, 6727 CheckFn &&IsSuccessful) { 6728 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6729 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6730 if (ArgDependent == DIA->getArgDependent()) 6731 Attrs.push_back(DIA); 6732 } 6733 6734 // Common case: No diagnose_if attributes, so we can quit early. 6735 if (Attrs.empty()) 6736 return false; 6737 6738 auto WarningBegin = std::stable_partition( 6739 Attrs.begin(), Attrs.end(), 6740 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6741 6742 // Note that diagnose_if attributes are late-parsed, so they appear in the 6743 // correct order (unlike enable_if attributes). 6744 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6745 IsSuccessful); 6746 if (ErrAttr != WarningBegin) { 6747 const DiagnoseIfAttr *DIA = *ErrAttr; 6748 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6749 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6750 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6751 return true; 6752 } 6753 6754 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6755 if (IsSuccessful(DIA)) { 6756 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6757 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6758 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6759 } 6760 6761 return false; 6762 } 6763 6764 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6765 const Expr *ThisArg, 6766 ArrayRef<const Expr *> Args, 6767 SourceLocation Loc) { 6768 return diagnoseDiagnoseIfAttrsWith( 6769 *this, Function, /*ArgDependent=*/true, Loc, 6770 [&](const DiagnoseIfAttr *DIA) { 6771 APValue Result; 6772 // It's sane to use the same Args for any redecl of this function, since 6773 // EvaluateWithSubstitution only cares about the position of each 6774 // argument in the arg list, not the ParmVarDecl* it maps to. 6775 if (!DIA->getCond()->EvaluateWithSubstitution( 6776 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6777 return false; 6778 return Result.isInt() && Result.getInt().getBoolValue(); 6779 }); 6780 } 6781 6782 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6783 SourceLocation Loc) { 6784 return diagnoseDiagnoseIfAttrsWith( 6785 *this, ND, /*ArgDependent=*/false, Loc, 6786 [&](const DiagnoseIfAttr *DIA) { 6787 bool Result; 6788 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6789 Result; 6790 }); 6791 } 6792 6793 /// Add all of the function declarations in the given function set to 6794 /// the overload candidate set. 6795 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6796 ArrayRef<Expr *> Args, 6797 OverloadCandidateSet &CandidateSet, 6798 TemplateArgumentListInfo *ExplicitTemplateArgs, 6799 bool SuppressUserConversions, 6800 bool PartialOverloading, 6801 bool FirstArgumentIsBase) { 6802 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6803 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6804 ArrayRef<Expr *> FunctionArgs = Args; 6805 6806 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6807 FunctionDecl *FD = 6808 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6809 6810 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6811 QualType ObjectType; 6812 Expr::Classification ObjectClassification; 6813 if (Args.size() > 0) { 6814 if (Expr *E = Args[0]) { 6815 // Use the explicit base to restrict the lookup: 6816 ObjectType = E->getType(); 6817 // Pointers in the object arguments are implicitly dereferenced, so we 6818 // always classify them as l-values. 6819 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6820 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6821 else 6822 ObjectClassification = E->Classify(Context); 6823 } // .. else there is an implicit base. 6824 FunctionArgs = Args.slice(1); 6825 } 6826 if (FunTmpl) { 6827 AddMethodTemplateCandidate( 6828 FunTmpl, F.getPair(), 6829 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6830 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6831 FunctionArgs, CandidateSet, SuppressUserConversions, 6832 PartialOverloading); 6833 } else { 6834 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6835 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6836 ObjectClassification, FunctionArgs, CandidateSet, 6837 SuppressUserConversions, PartialOverloading); 6838 } 6839 } else { 6840 // This branch handles both standalone functions and static methods. 6841 6842 // Slice the first argument (which is the base) when we access 6843 // static method as non-static. 6844 if (Args.size() > 0 && 6845 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6846 !isa<CXXConstructorDecl>(FD)))) { 6847 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6848 FunctionArgs = Args.slice(1); 6849 } 6850 if (FunTmpl) { 6851 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6852 ExplicitTemplateArgs, FunctionArgs, 6853 CandidateSet, SuppressUserConversions, 6854 PartialOverloading); 6855 } else { 6856 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6857 SuppressUserConversions, PartialOverloading); 6858 } 6859 } 6860 } 6861 } 6862 6863 /// AddMethodCandidate - Adds a named decl (which is some kind of 6864 /// method) as a method candidate to the given overload set. 6865 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6866 Expr::Classification ObjectClassification, 6867 ArrayRef<Expr *> Args, 6868 OverloadCandidateSet &CandidateSet, 6869 bool SuppressUserConversions, 6870 OverloadCandidateParamOrder PO) { 6871 NamedDecl *Decl = FoundDecl.getDecl(); 6872 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6873 6874 if (isa<UsingShadowDecl>(Decl)) 6875 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6876 6877 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6878 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6879 "Expected a member function template"); 6880 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6881 /*ExplicitArgs*/ nullptr, ObjectType, 6882 ObjectClassification, Args, CandidateSet, 6883 SuppressUserConversions, false, PO); 6884 } else { 6885 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6886 ObjectType, ObjectClassification, Args, CandidateSet, 6887 SuppressUserConversions, false, None, PO); 6888 } 6889 } 6890 6891 /// AddMethodCandidate - Adds the given C++ member function to the set 6892 /// of candidate functions, using the given function call arguments 6893 /// and the object argument (@c Object). For example, in a call 6894 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6895 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6896 /// allow user-defined conversions via constructors or conversion 6897 /// operators. 6898 void 6899 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6900 CXXRecordDecl *ActingContext, QualType ObjectType, 6901 Expr::Classification ObjectClassification, 6902 ArrayRef<Expr *> Args, 6903 OverloadCandidateSet &CandidateSet, 6904 bool SuppressUserConversions, 6905 bool PartialOverloading, 6906 ConversionSequenceList EarlyConversions, 6907 OverloadCandidateParamOrder PO) { 6908 const FunctionProtoType *Proto 6909 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6910 assert(Proto && "Methods without a prototype cannot be overloaded"); 6911 assert(!isa<CXXConstructorDecl>(Method) && 6912 "Use AddOverloadCandidate for constructors"); 6913 6914 if (!CandidateSet.isNewCandidate(Method, PO)) 6915 return; 6916 6917 // C++11 [class.copy]p23: [DR1402] 6918 // A defaulted move assignment operator that is defined as deleted is 6919 // ignored by overload resolution. 6920 if (Method->isDefaulted() && Method->isDeleted() && 6921 Method->isMoveAssignmentOperator()) 6922 return; 6923 6924 // Overload resolution is always an unevaluated context. 6925 EnterExpressionEvaluationContext Unevaluated( 6926 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6927 6928 // Add this candidate 6929 OverloadCandidate &Candidate = 6930 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6931 Candidate.FoundDecl = FoundDecl; 6932 Candidate.Function = Method; 6933 Candidate.RewriteKind = 6934 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6935 Candidate.IsSurrogate = false; 6936 Candidate.IgnoreObjectArgument = false; 6937 Candidate.ExplicitCallArguments = Args.size(); 6938 6939 unsigned NumParams = Proto->getNumParams(); 6940 6941 // (C++ 13.3.2p2): A candidate function having fewer than m 6942 // parameters is viable only if it has an ellipsis in its parameter 6943 // list (8.3.5). 6944 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6945 !Proto->isVariadic() && 6946 shouldEnforceArgLimit(PartialOverloading, Method)) { 6947 Candidate.Viable = false; 6948 Candidate.FailureKind = ovl_fail_too_many_arguments; 6949 return; 6950 } 6951 6952 // (C++ 13.3.2p2): A candidate function having more than m parameters 6953 // is viable only if the (m+1)st parameter has a default argument 6954 // (8.3.6). For the purposes of overload resolution, the 6955 // parameter list is truncated on the right, so that there are 6956 // exactly m parameters. 6957 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6958 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6959 // Not enough arguments. 6960 Candidate.Viable = false; 6961 Candidate.FailureKind = ovl_fail_too_few_arguments; 6962 return; 6963 } 6964 6965 Candidate.Viable = true; 6966 6967 if (Method->isStatic() || ObjectType.isNull()) 6968 // The implicit object argument is ignored. 6969 Candidate.IgnoreObjectArgument = true; 6970 else { 6971 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6972 // Determine the implicit conversion sequence for the object 6973 // parameter. 6974 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6975 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6976 Method, ActingContext); 6977 if (Candidate.Conversions[ConvIdx].isBad()) { 6978 Candidate.Viable = false; 6979 Candidate.FailureKind = ovl_fail_bad_conversion; 6980 return; 6981 } 6982 } 6983 6984 // (CUDA B.1): Check for invalid calls between targets. 6985 if (getLangOpts().CUDA) 6986 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6987 if (!IsAllowedCUDACall(Caller, Method)) { 6988 Candidate.Viable = false; 6989 Candidate.FailureKind = ovl_fail_bad_target; 6990 return; 6991 } 6992 6993 if (Method->getTrailingRequiresClause()) { 6994 ConstraintSatisfaction Satisfaction; 6995 if (CheckFunctionConstraints(Method, Satisfaction) || 6996 !Satisfaction.IsSatisfied) { 6997 Candidate.Viable = false; 6998 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6999 return; 7000 } 7001 } 7002 7003 // Determine the implicit conversion sequences for each of the 7004 // arguments. 7005 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7006 unsigned ConvIdx = 7007 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7008 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7009 // We already formed a conversion sequence for this parameter during 7010 // template argument deduction. 7011 } else if (ArgIdx < NumParams) { 7012 // (C++ 13.3.2p3): for F to be a viable function, there shall 7013 // exist for each argument an implicit conversion sequence 7014 // (13.3.3.1) that converts that argument to the corresponding 7015 // parameter of F. 7016 QualType ParamType = Proto->getParamType(ArgIdx); 7017 Candidate.Conversions[ConvIdx] 7018 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7019 SuppressUserConversions, 7020 /*InOverloadResolution=*/true, 7021 /*AllowObjCWritebackConversion=*/ 7022 getLangOpts().ObjCAutoRefCount); 7023 if (Candidate.Conversions[ConvIdx].isBad()) { 7024 Candidate.Viable = false; 7025 Candidate.FailureKind = ovl_fail_bad_conversion; 7026 return; 7027 } 7028 } else { 7029 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7030 // argument for which there is no corresponding parameter is 7031 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7032 Candidate.Conversions[ConvIdx].setEllipsis(); 7033 } 7034 } 7035 7036 if (EnableIfAttr *FailedAttr = 7037 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7038 Candidate.Viable = false; 7039 Candidate.FailureKind = ovl_fail_enable_if; 7040 Candidate.DeductionFailure.Data = FailedAttr; 7041 return; 7042 } 7043 7044 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 7045 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 7046 Candidate.Viable = false; 7047 Candidate.FailureKind = ovl_non_default_multiversion_function; 7048 } 7049 } 7050 7051 /// Add a C++ member function template as a candidate to the candidate 7052 /// set, using template argument deduction to produce an appropriate member 7053 /// function template specialization. 7054 void Sema::AddMethodTemplateCandidate( 7055 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7056 CXXRecordDecl *ActingContext, 7057 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7058 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7059 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7060 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7061 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7062 return; 7063 7064 // C++ [over.match.funcs]p7: 7065 // In each case where a candidate is a function template, candidate 7066 // function template specializations are generated using template argument 7067 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7068 // candidate functions in the usual way.113) A given name can refer to one 7069 // or more function templates and also to a set of overloaded non-template 7070 // functions. In such a case, the candidate functions generated from each 7071 // function template are combined with the set of non-template candidate 7072 // functions. 7073 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7074 FunctionDecl *Specialization = nullptr; 7075 ConversionSequenceList Conversions; 7076 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7077 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7078 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7079 return CheckNonDependentConversions( 7080 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7081 SuppressUserConversions, ActingContext, ObjectType, 7082 ObjectClassification, PO); 7083 })) { 7084 OverloadCandidate &Candidate = 7085 CandidateSet.addCandidate(Conversions.size(), Conversions); 7086 Candidate.FoundDecl = FoundDecl; 7087 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7088 Candidate.Viable = false; 7089 Candidate.RewriteKind = 7090 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7091 Candidate.IsSurrogate = false; 7092 Candidate.IgnoreObjectArgument = 7093 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7094 ObjectType.isNull(); 7095 Candidate.ExplicitCallArguments = Args.size(); 7096 if (Result == TDK_NonDependentConversionFailure) 7097 Candidate.FailureKind = ovl_fail_bad_conversion; 7098 else { 7099 Candidate.FailureKind = ovl_fail_bad_deduction; 7100 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7101 Info); 7102 } 7103 return; 7104 } 7105 7106 // Add the function template specialization produced by template argument 7107 // deduction as a candidate. 7108 assert(Specialization && "Missing member function template specialization?"); 7109 assert(isa<CXXMethodDecl>(Specialization) && 7110 "Specialization is not a member function?"); 7111 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7112 ActingContext, ObjectType, ObjectClassification, Args, 7113 CandidateSet, SuppressUserConversions, PartialOverloading, 7114 Conversions, PO); 7115 } 7116 7117 /// Determine whether a given function template has a simple explicit specifier 7118 /// or a non-value-dependent explicit-specification that evaluates to true. 7119 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7120 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7121 } 7122 7123 /// Add a C++ function template specialization as a candidate 7124 /// in the candidate set, using template argument deduction to produce 7125 /// an appropriate function template specialization. 7126 void Sema::AddTemplateOverloadCandidate( 7127 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7128 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7129 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7130 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7131 OverloadCandidateParamOrder PO) { 7132 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7133 return; 7134 7135 // If the function template has a non-dependent explicit specification, 7136 // exclude it now if appropriate; we are not permitted to perform deduction 7137 // and substitution in this case. 7138 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7139 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7140 Candidate.FoundDecl = FoundDecl; 7141 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7142 Candidate.Viable = false; 7143 Candidate.FailureKind = ovl_fail_explicit; 7144 return; 7145 } 7146 7147 // C++ [over.match.funcs]p7: 7148 // In each case where a candidate is a function template, candidate 7149 // function template specializations are generated using template argument 7150 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7151 // candidate functions in the usual way.113) A given name can refer to one 7152 // or more function templates and also to a set of overloaded non-template 7153 // functions. In such a case, the candidate functions generated from each 7154 // function template are combined with the set of non-template candidate 7155 // functions. 7156 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7157 FunctionDecl *Specialization = nullptr; 7158 ConversionSequenceList Conversions; 7159 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7160 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7161 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7162 return CheckNonDependentConversions( 7163 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7164 SuppressUserConversions, nullptr, QualType(), {}, PO); 7165 })) { 7166 OverloadCandidate &Candidate = 7167 CandidateSet.addCandidate(Conversions.size(), Conversions); 7168 Candidate.FoundDecl = FoundDecl; 7169 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7170 Candidate.Viable = false; 7171 Candidate.RewriteKind = 7172 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7173 Candidate.IsSurrogate = false; 7174 Candidate.IsADLCandidate = IsADLCandidate; 7175 // Ignore the object argument if there is one, since we don't have an object 7176 // type. 7177 Candidate.IgnoreObjectArgument = 7178 isa<CXXMethodDecl>(Candidate.Function) && 7179 !isa<CXXConstructorDecl>(Candidate.Function); 7180 Candidate.ExplicitCallArguments = Args.size(); 7181 if (Result == TDK_NonDependentConversionFailure) 7182 Candidate.FailureKind = ovl_fail_bad_conversion; 7183 else { 7184 Candidate.FailureKind = ovl_fail_bad_deduction; 7185 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7186 Info); 7187 } 7188 return; 7189 } 7190 7191 // Add the function template specialization produced by template argument 7192 // deduction as a candidate. 7193 assert(Specialization && "Missing function template specialization?"); 7194 AddOverloadCandidate( 7195 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7196 PartialOverloading, AllowExplicit, 7197 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7198 } 7199 7200 /// Check that implicit conversion sequences can be formed for each argument 7201 /// whose corresponding parameter has a non-dependent type, per DR1391's 7202 /// [temp.deduct.call]p10. 7203 bool Sema::CheckNonDependentConversions( 7204 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7205 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7206 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7207 CXXRecordDecl *ActingContext, QualType ObjectType, 7208 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7209 // FIXME: The cases in which we allow explicit conversions for constructor 7210 // arguments never consider calling a constructor template. It's not clear 7211 // that is correct. 7212 const bool AllowExplicit = false; 7213 7214 auto *FD = FunctionTemplate->getTemplatedDecl(); 7215 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7216 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7217 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7218 7219 Conversions = 7220 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7221 7222 // Overload resolution is always an unevaluated context. 7223 EnterExpressionEvaluationContext Unevaluated( 7224 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7225 7226 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7227 // require that, but this check should never result in a hard error, and 7228 // overload resolution is permitted to sidestep instantiations. 7229 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7230 !ObjectType.isNull()) { 7231 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7232 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7233 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7234 Method, ActingContext); 7235 if (Conversions[ConvIdx].isBad()) 7236 return true; 7237 } 7238 7239 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7240 ++I) { 7241 QualType ParamType = ParamTypes[I]; 7242 if (!ParamType->isDependentType()) { 7243 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7244 ? 0 7245 : (ThisConversions + I); 7246 Conversions[ConvIdx] 7247 = TryCopyInitialization(*this, Args[I], ParamType, 7248 SuppressUserConversions, 7249 /*InOverloadResolution=*/true, 7250 /*AllowObjCWritebackConversion=*/ 7251 getLangOpts().ObjCAutoRefCount, 7252 AllowExplicit); 7253 if (Conversions[ConvIdx].isBad()) 7254 return true; 7255 } 7256 } 7257 7258 return false; 7259 } 7260 7261 /// Determine whether this is an allowable conversion from the result 7262 /// of an explicit conversion operator to the expected type, per C++ 7263 /// [over.match.conv]p1 and [over.match.ref]p1. 7264 /// 7265 /// \param ConvType The return type of the conversion function. 7266 /// 7267 /// \param ToType The type we are converting to. 7268 /// 7269 /// \param AllowObjCPointerConversion Allow a conversion from one 7270 /// Objective-C pointer to another. 7271 /// 7272 /// \returns true if the conversion is allowable, false otherwise. 7273 static bool isAllowableExplicitConversion(Sema &S, 7274 QualType ConvType, QualType ToType, 7275 bool AllowObjCPointerConversion) { 7276 QualType ToNonRefType = ToType.getNonReferenceType(); 7277 7278 // Easy case: the types are the same. 7279 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7280 return true; 7281 7282 // Allow qualification conversions. 7283 bool ObjCLifetimeConversion; 7284 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7285 ObjCLifetimeConversion)) 7286 return true; 7287 7288 // If we're not allowed to consider Objective-C pointer conversions, 7289 // we're done. 7290 if (!AllowObjCPointerConversion) 7291 return false; 7292 7293 // Is this an Objective-C pointer conversion? 7294 bool IncompatibleObjC = false; 7295 QualType ConvertedType; 7296 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7297 IncompatibleObjC); 7298 } 7299 7300 /// AddConversionCandidate - Add a C++ conversion function as a 7301 /// candidate in the candidate set (C++ [over.match.conv], 7302 /// C++ [over.match.copy]). From is the expression we're converting from, 7303 /// and ToType is the type that we're eventually trying to convert to 7304 /// (which may or may not be the same type as the type that the 7305 /// conversion function produces). 7306 void Sema::AddConversionCandidate( 7307 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7308 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7309 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7310 bool AllowExplicit, bool AllowResultConversion) { 7311 assert(!Conversion->getDescribedFunctionTemplate() && 7312 "Conversion function templates use AddTemplateConversionCandidate"); 7313 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7314 if (!CandidateSet.isNewCandidate(Conversion)) 7315 return; 7316 7317 // If the conversion function has an undeduced return type, trigger its 7318 // deduction now. 7319 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7320 if (DeduceReturnType(Conversion, From->getExprLoc())) 7321 return; 7322 ConvType = Conversion->getConversionType().getNonReferenceType(); 7323 } 7324 7325 // If we don't allow any conversion of the result type, ignore conversion 7326 // functions that don't convert to exactly (possibly cv-qualified) T. 7327 if (!AllowResultConversion && 7328 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7329 return; 7330 7331 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7332 // operator is only a candidate if its return type is the target type or 7333 // can be converted to the target type with a qualification conversion. 7334 // 7335 // FIXME: Include such functions in the candidate list and explain why we 7336 // can't select them. 7337 if (Conversion->isExplicit() && 7338 !isAllowableExplicitConversion(*this, ConvType, ToType, 7339 AllowObjCConversionOnExplicit)) 7340 return; 7341 7342 // Overload resolution is always an unevaluated context. 7343 EnterExpressionEvaluationContext Unevaluated( 7344 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7345 7346 // Add this candidate 7347 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7348 Candidate.FoundDecl = FoundDecl; 7349 Candidate.Function = Conversion; 7350 Candidate.IsSurrogate = false; 7351 Candidate.IgnoreObjectArgument = false; 7352 Candidate.FinalConversion.setAsIdentityConversion(); 7353 Candidate.FinalConversion.setFromType(ConvType); 7354 Candidate.FinalConversion.setAllToTypes(ToType); 7355 Candidate.Viable = true; 7356 Candidate.ExplicitCallArguments = 1; 7357 7358 // Explicit functions are not actually candidates at all if we're not 7359 // allowing them in this context, but keep them around so we can point 7360 // to them in diagnostics. 7361 if (!AllowExplicit && Conversion->isExplicit()) { 7362 Candidate.Viable = false; 7363 Candidate.FailureKind = ovl_fail_explicit; 7364 return; 7365 } 7366 7367 // C++ [over.match.funcs]p4: 7368 // For conversion functions, the function is considered to be a member of 7369 // the class of the implicit implied object argument for the purpose of 7370 // defining the type of the implicit object parameter. 7371 // 7372 // Determine the implicit conversion sequence for the implicit 7373 // object parameter. 7374 QualType ImplicitParamType = From->getType(); 7375 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7376 ImplicitParamType = FromPtrType->getPointeeType(); 7377 CXXRecordDecl *ConversionContext 7378 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7379 7380 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7381 *this, CandidateSet.getLocation(), From->getType(), 7382 From->Classify(Context), Conversion, ConversionContext); 7383 7384 if (Candidate.Conversions[0].isBad()) { 7385 Candidate.Viable = false; 7386 Candidate.FailureKind = ovl_fail_bad_conversion; 7387 return; 7388 } 7389 7390 if (Conversion->getTrailingRequiresClause()) { 7391 ConstraintSatisfaction Satisfaction; 7392 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7393 !Satisfaction.IsSatisfied) { 7394 Candidate.Viable = false; 7395 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7396 return; 7397 } 7398 } 7399 7400 // We won't go through a user-defined type conversion function to convert a 7401 // derived to base as such conversions are given Conversion Rank. They only 7402 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7403 QualType FromCanon 7404 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7405 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7406 if (FromCanon == ToCanon || 7407 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7408 Candidate.Viable = false; 7409 Candidate.FailureKind = ovl_fail_trivial_conversion; 7410 return; 7411 } 7412 7413 // To determine what the conversion from the result of calling the 7414 // conversion function to the type we're eventually trying to 7415 // convert to (ToType), we need to synthesize a call to the 7416 // conversion function and attempt copy initialization from it. This 7417 // makes sure that we get the right semantics with respect to 7418 // lvalues/rvalues and the type. Fortunately, we can allocate this 7419 // call on the stack and we don't need its arguments to be 7420 // well-formed. 7421 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7422 VK_LValue, From->getBeginLoc()); 7423 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7424 Context.getPointerType(Conversion->getType()), 7425 CK_FunctionToPointerDecay, &ConversionRef, 7426 VK_PRValue, FPOptionsOverride()); 7427 7428 QualType ConversionType = Conversion->getConversionType(); 7429 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7430 Candidate.Viable = false; 7431 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7432 return; 7433 } 7434 7435 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7436 7437 // Note that it is safe to allocate CallExpr on the stack here because 7438 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7439 // allocator). 7440 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7441 7442 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7443 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7444 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7445 7446 ImplicitConversionSequence ICS = 7447 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7448 /*SuppressUserConversions=*/true, 7449 /*InOverloadResolution=*/false, 7450 /*AllowObjCWritebackConversion=*/false); 7451 7452 switch (ICS.getKind()) { 7453 case ImplicitConversionSequence::StandardConversion: 7454 Candidate.FinalConversion = ICS.Standard; 7455 7456 // C++ [over.ics.user]p3: 7457 // If the user-defined conversion is specified by a specialization of a 7458 // conversion function template, the second standard conversion sequence 7459 // shall have exact match rank. 7460 if (Conversion->getPrimaryTemplate() && 7461 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7462 Candidate.Viable = false; 7463 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7464 return; 7465 } 7466 7467 // C++0x [dcl.init.ref]p5: 7468 // In the second case, if the reference is an rvalue reference and 7469 // the second standard conversion sequence of the user-defined 7470 // conversion sequence includes an lvalue-to-rvalue conversion, the 7471 // program is ill-formed. 7472 if (ToType->isRValueReferenceType() && 7473 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7474 Candidate.Viable = false; 7475 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7476 return; 7477 } 7478 break; 7479 7480 case ImplicitConversionSequence::BadConversion: 7481 Candidate.Viable = false; 7482 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7483 return; 7484 7485 default: 7486 llvm_unreachable( 7487 "Can only end up with a standard conversion sequence or failure"); 7488 } 7489 7490 if (EnableIfAttr *FailedAttr = 7491 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7492 Candidate.Viable = false; 7493 Candidate.FailureKind = ovl_fail_enable_if; 7494 Candidate.DeductionFailure.Data = FailedAttr; 7495 return; 7496 } 7497 7498 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7499 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7500 Candidate.Viable = false; 7501 Candidate.FailureKind = ovl_non_default_multiversion_function; 7502 } 7503 } 7504 7505 /// Adds a conversion function template specialization 7506 /// candidate to the overload set, using template argument deduction 7507 /// to deduce the template arguments of the conversion function 7508 /// template from the type that we are converting to (C++ 7509 /// [temp.deduct.conv]). 7510 void Sema::AddTemplateConversionCandidate( 7511 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7512 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7513 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7514 bool AllowExplicit, bool AllowResultConversion) { 7515 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7516 "Only conversion function templates permitted here"); 7517 7518 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7519 return; 7520 7521 // If the function template has a non-dependent explicit specification, 7522 // exclude it now if appropriate; we are not permitted to perform deduction 7523 // and substitution in this case. 7524 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7525 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7526 Candidate.FoundDecl = FoundDecl; 7527 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7528 Candidate.Viable = false; 7529 Candidate.FailureKind = ovl_fail_explicit; 7530 return; 7531 } 7532 7533 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7534 CXXConversionDecl *Specialization = nullptr; 7535 if (TemplateDeductionResult Result 7536 = DeduceTemplateArguments(FunctionTemplate, ToType, 7537 Specialization, Info)) { 7538 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7539 Candidate.FoundDecl = FoundDecl; 7540 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7541 Candidate.Viable = false; 7542 Candidate.FailureKind = ovl_fail_bad_deduction; 7543 Candidate.IsSurrogate = false; 7544 Candidate.IgnoreObjectArgument = false; 7545 Candidate.ExplicitCallArguments = 1; 7546 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7547 Info); 7548 return; 7549 } 7550 7551 // Add the conversion function template specialization produced by 7552 // template argument deduction as a candidate. 7553 assert(Specialization && "Missing function template specialization?"); 7554 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7555 CandidateSet, AllowObjCConversionOnExplicit, 7556 AllowExplicit, AllowResultConversion); 7557 } 7558 7559 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7560 /// converts the given @c Object to a function pointer via the 7561 /// conversion function @c Conversion, and then attempts to call it 7562 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7563 /// the type of function that we'll eventually be calling. 7564 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7565 DeclAccessPair FoundDecl, 7566 CXXRecordDecl *ActingContext, 7567 const FunctionProtoType *Proto, 7568 Expr *Object, 7569 ArrayRef<Expr *> Args, 7570 OverloadCandidateSet& CandidateSet) { 7571 if (!CandidateSet.isNewCandidate(Conversion)) 7572 return; 7573 7574 // Overload resolution is always an unevaluated context. 7575 EnterExpressionEvaluationContext Unevaluated( 7576 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7577 7578 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7579 Candidate.FoundDecl = FoundDecl; 7580 Candidate.Function = nullptr; 7581 Candidate.Surrogate = Conversion; 7582 Candidate.Viable = true; 7583 Candidate.IsSurrogate = true; 7584 Candidate.IgnoreObjectArgument = false; 7585 Candidate.ExplicitCallArguments = Args.size(); 7586 7587 // Determine the implicit conversion sequence for the implicit 7588 // object parameter. 7589 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7590 *this, CandidateSet.getLocation(), Object->getType(), 7591 Object->Classify(Context), Conversion, ActingContext); 7592 if (ObjectInit.isBad()) { 7593 Candidate.Viable = false; 7594 Candidate.FailureKind = ovl_fail_bad_conversion; 7595 Candidate.Conversions[0] = ObjectInit; 7596 return; 7597 } 7598 7599 // The first conversion is actually a user-defined conversion whose 7600 // first conversion is ObjectInit's standard conversion (which is 7601 // effectively a reference binding). Record it as such. 7602 Candidate.Conversions[0].setUserDefined(); 7603 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7604 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7605 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7606 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7607 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7608 Candidate.Conversions[0].UserDefined.After 7609 = Candidate.Conversions[0].UserDefined.Before; 7610 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7611 7612 // Find the 7613 unsigned NumParams = Proto->getNumParams(); 7614 7615 // (C++ 13.3.2p2): A candidate function having fewer than m 7616 // parameters is viable only if it has an ellipsis in its parameter 7617 // list (8.3.5). 7618 if (Args.size() > NumParams && !Proto->isVariadic()) { 7619 Candidate.Viable = false; 7620 Candidate.FailureKind = ovl_fail_too_many_arguments; 7621 return; 7622 } 7623 7624 // Function types don't have any default arguments, so just check if 7625 // we have enough arguments. 7626 if (Args.size() < NumParams) { 7627 // Not enough arguments. 7628 Candidate.Viable = false; 7629 Candidate.FailureKind = ovl_fail_too_few_arguments; 7630 return; 7631 } 7632 7633 // Determine the implicit conversion sequences for each of the 7634 // arguments. 7635 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7636 if (ArgIdx < NumParams) { 7637 // (C++ 13.3.2p3): for F to be a viable function, there shall 7638 // exist for each argument an implicit conversion sequence 7639 // (13.3.3.1) that converts that argument to the corresponding 7640 // parameter of F. 7641 QualType ParamType = Proto->getParamType(ArgIdx); 7642 Candidate.Conversions[ArgIdx + 1] 7643 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7644 /*SuppressUserConversions=*/false, 7645 /*InOverloadResolution=*/false, 7646 /*AllowObjCWritebackConversion=*/ 7647 getLangOpts().ObjCAutoRefCount); 7648 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7649 Candidate.Viable = false; 7650 Candidate.FailureKind = ovl_fail_bad_conversion; 7651 return; 7652 } 7653 } else { 7654 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7655 // argument for which there is no corresponding parameter is 7656 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7657 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7658 } 7659 } 7660 7661 if (EnableIfAttr *FailedAttr = 7662 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7663 Candidate.Viable = false; 7664 Candidate.FailureKind = ovl_fail_enable_if; 7665 Candidate.DeductionFailure.Data = FailedAttr; 7666 return; 7667 } 7668 } 7669 7670 /// Add all of the non-member operator function declarations in the given 7671 /// function set to the overload candidate set. 7672 void Sema::AddNonMemberOperatorCandidates( 7673 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7674 OverloadCandidateSet &CandidateSet, 7675 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7676 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7677 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7678 ArrayRef<Expr *> FunctionArgs = Args; 7679 7680 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7681 FunctionDecl *FD = 7682 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7683 7684 // Don't consider rewritten functions if we're not rewriting. 7685 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7686 continue; 7687 7688 assert(!isa<CXXMethodDecl>(FD) && 7689 "unqualified operator lookup found a member function"); 7690 7691 if (FunTmpl) { 7692 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7693 FunctionArgs, CandidateSet); 7694 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7695 AddTemplateOverloadCandidate( 7696 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7697 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7698 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7699 } else { 7700 if (ExplicitTemplateArgs) 7701 continue; 7702 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7703 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7704 AddOverloadCandidate(FD, F.getPair(), 7705 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7706 false, false, true, false, ADLCallKind::NotADL, 7707 None, OverloadCandidateParamOrder::Reversed); 7708 } 7709 } 7710 } 7711 7712 /// Add overload candidates for overloaded operators that are 7713 /// member functions. 7714 /// 7715 /// Add the overloaded operator candidates that are member functions 7716 /// for the operator Op that was used in an operator expression such 7717 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7718 /// CandidateSet will store the added overload candidates. (C++ 7719 /// [over.match.oper]). 7720 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7721 SourceLocation OpLoc, 7722 ArrayRef<Expr *> Args, 7723 OverloadCandidateSet &CandidateSet, 7724 OverloadCandidateParamOrder PO) { 7725 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7726 7727 // C++ [over.match.oper]p3: 7728 // For a unary operator @ with an operand of a type whose 7729 // cv-unqualified version is T1, and for a binary operator @ with 7730 // a left operand of a type whose cv-unqualified version is T1 and 7731 // a right operand of a type whose cv-unqualified version is T2, 7732 // three sets of candidate functions, designated member 7733 // candidates, non-member candidates and built-in candidates, are 7734 // constructed as follows: 7735 QualType T1 = Args[0]->getType(); 7736 7737 // -- If T1 is a complete class type or a class currently being 7738 // defined, the set of member candidates is the result of the 7739 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7740 // the set of member candidates is empty. 7741 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7742 // Complete the type if it can be completed. 7743 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7744 return; 7745 // If the type is neither complete nor being defined, bail out now. 7746 if (!T1Rec->getDecl()->getDefinition()) 7747 return; 7748 7749 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7750 LookupQualifiedName(Operators, T1Rec->getDecl()); 7751 Operators.suppressDiagnostics(); 7752 7753 for (LookupResult::iterator Oper = Operators.begin(), 7754 OperEnd = Operators.end(); 7755 Oper != OperEnd; 7756 ++Oper) 7757 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7758 Args[0]->Classify(Context), Args.slice(1), 7759 CandidateSet, /*SuppressUserConversion=*/false, PO); 7760 } 7761 } 7762 7763 /// AddBuiltinCandidate - Add a candidate for a built-in 7764 /// operator. ResultTy and ParamTys are the result and parameter types 7765 /// of the built-in candidate, respectively. Args and NumArgs are the 7766 /// arguments being passed to the candidate. IsAssignmentOperator 7767 /// should be true when this built-in candidate is an assignment 7768 /// operator. NumContextualBoolArguments is the number of arguments 7769 /// (at the beginning of the argument list) that will be contextually 7770 /// converted to bool. 7771 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7772 OverloadCandidateSet& CandidateSet, 7773 bool IsAssignmentOperator, 7774 unsigned NumContextualBoolArguments) { 7775 // Overload resolution is always an unevaluated context. 7776 EnterExpressionEvaluationContext Unevaluated( 7777 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7778 7779 // Add this candidate 7780 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7781 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7782 Candidate.Function = nullptr; 7783 Candidate.IsSurrogate = false; 7784 Candidate.IgnoreObjectArgument = false; 7785 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7786 7787 // Determine the implicit conversion sequences for each of the 7788 // arguments. 7789 Candidate.Viable = true; 7790 Candidate.ExplicitCallArguments = Args.size(); 7791 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7792 // C++ [over.match.oper]p4: 7793 // For the built-in assignment operators, conversions of the 7794 // left operand are restricted as follows: 7795 // -- no temporaries are introduced to hold the left operand, and 7796 // -- no user-defined conversions are applied to the left 7797 // operand to achieve a type match with the left-most 7798 // parameter of a built-in candidate. 7799 // 7800 // We block these conversions by turning off user-defined 7801 // conversions, since that is the only way that initialization of 7802 // a reference to a non-class type can occur from something that 7803 // is not of the same type. 7804 if (ArgIdx < NumContextualBoolArguments) { 7805 assert(ParamTys[ArgIdx] == Context.BoolTy && 7806 "Contextual conversion to bool requires bool type"); 7807 Candidate.Conversions[ArgIdx] 7808 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7809 } else { 7810 Candidate.Conversions[ArgIdx] 7811 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7812 ArgIdx == 0 && IsAssignmentOperator, 7813 /*InOverloadResolution=*/false, 7814 /*AllowObjCWritebackConversion=*/ 7815 getLangOpts().ObjCAutoRefCount); 7816 } 7817 if (Candidate.Conversions[ArgIdx].isBad()) { 7818 Candidate.Viable = false; 7819 Candidate.FailureKind = ovl_fail_bad_conversion; 7820 break; 7821 } 7822 } 7823 } 7824 7825 namespace { 7826 7827 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7828 /// candidate operator functions for built-in operators (C++ 7829 /// [over.built]). The types are separated into pointer types and 7830 /// enumeration types. 7831 class BuiltinCandidateTypeSet { 7832 /// TypeSet - A set of types. 7833 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7834 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7835 7836 /// PointerTypes - The set of pointer types that will be used in the 7837 /// built-in candidates. 7838 TypeSet PointerTypes; 7839 7840 /// MemberPointerTypes - The set of member pointer types that will be 7841 /// used in the built-in candidates. 7842 TypeSet MemberPointerTypes; 7843 7844 /// EnumerationTypes - The set of enumeration types that will be 7845 /// used in the built-in candidates. 7846 TypeSet EnumerationTypes; 7847 7848 /// The set of vector types that will be used in the built-in 7849 /// candidates. 7850 TypeSet VectorTypes; 7851 7852 /// The set of matrix types that will be used in the built-in 7853 /// candidates. 7854 TypeSet MatrixTypes; 7855 7856 /// A flag indicating non-record types are viable candidates 7857 bool HasNonRecordTypes; 7858 7859 /// A flag indicating whether either arithmetic or enumeration types 7860 /// were present in the candidate set. 7861 bool HasArithmeticOrEnumeralTypes; 7862 7863 /// A flag indicating whether the nullptr type was present in the 7864 /// candidate set. 7865 bool HasNullPtrType; 7866 7867 /// Sema - The semantic analysis instance where we are building the 7868 /// candidate type set. 7869 Sema &SemaRef; 7870 7871 /// Context - The AST context in which we will build the type sets. 7872 ASTContext &Context; 7873 7874 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7875 const Qualifiers &VisibleQuals); 7876 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7877 7878 public: 7879 /// iterator - Iterates through the types that are part of the set. 7880 typedef TypeSet::iterator iterator; 7881 7882 BuiltinCandidateTypeSet(Sema &SemaRef) 7883 : HasNonRecordTypes(false), 7884 HasArithmeticOrEnumeralTypes(false), 7885 HasNullPtrType(false), 7886 SemaRef(SemaRef), 7887 Context(SemaRef.Context) { } 7888 7889 void AddTypesConvertedFrom(QualType Ty, 7890 SourceLocation Loc, 7891 bool AllowUserConversions, 7892 bool AllowExplicitConversions, 7893 const Qualifiers &VisibleTypeConversionsQuals); 7894 7895 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7896 llvm::iterator_range<iterator> member_pointer_types() { 7897 return MemberPointerTypes; 7898 } 7899 llvm::iterator_range<iterator> enumeration_types() { 7900 return EnumerationTypes; 7901 } 7902 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7903 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7904 7905 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7906 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7907 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7908 bool hasNullPtrType() const { return HasNullPtrType; } 7909 }; 7910 7911 } // end anonymous namespace 7912 7913 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7914 /// the set of pointer types along with any more-qualified variants of 7915 /// that type. For example, if @p Ty is "int const *", this routine 7916 /// will add "int const *", "int const volatile *", "int const 7917 /// restrict *", and "int const volatile restrict *" to the set of 7918 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7919 /// false otherwise. 7920 /// 7921 /// FIXME: what to do about extended qualifiers? 7922 bool 7923 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7924 const Qualifiers &VisibleQuals) { 7925 7926 // Insert this type. 7927 if (!PointerTypes.insert(Ty)) 7928 return false; 7929 7930 QualType PointeeTy; 7931 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7932 bool buildObjCPtr = false; 7933 if (!PointerTy) { 7934 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7935 PointeeTy = PTy->getPointeeType(); 7936 buildObjCPtr = true; 7937 } else { 7938 PointeeTy = PointerTy->getPointeeType(); 7939 } 7940 7941 // Don't add qualified variants of arrays. For one, they're not allowed 7942 // (the qualifier would sink to the element type), and for another, the 7943 // only overload situation where it matters is subscript or pointer +- int, 7944 // and those shouldn't have qualifier variants anyway. 7945 if (PointeeTy->isArrayType()) 7946 return true; 7947 7948 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7949 bool hasVolatile = VisibleQuals.hasVolatile(); 7950 bool hasRestrict = VisibleQuals.hasRestrict(); 7951 7952 // Iterate through all strict supersets of BaseCVR. 7953 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7954 if ((CVR | BaseCVR) != CVR) continue; 7955 // Skip over volatile if no volatile found anywhere in the types. 7956 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7957 7958 // Skip over restrict if no restrict found anywhere in the types, or if 7959 // the type cannot be restrict-qualified. 7960 if ((CVR & Qualifiers::Restrict) && 7961 (!hasRestrict || 7962 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7963 continue; 7964 7965 // Build qualified pointee type. 7966 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7967 7968 // Build qualified pointer type. 7969 QualType QPointerTy; 7970 if (!buildObjCPtr) 7971 QPointerTy = Context.getPointerType(QPointeeTy); 7972 else 7973 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7974 7975 // Insert qualified pointer type. 7976 PointerTypes.insert(QPointerTy); 7977 } 7978 7979 return true; 7980 } 7981 7982 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7983 /// to the set of pointer types along with any more-qualified variants of 7984 /// that type. For example, if @p Ty is "int const *", this routine 7985 /// will add "int const *", "int const volatile *", "int const 7986 /// restrict *", and "int const volatile restrict *" to the set of 7987 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7988 /// false otherwise. 7989 /// 7990 /// FIXME: what to do about extended qualifiers? 7991 bool 7992 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7993 QualType Ty) { 7994 // Insert this type. 7995 if (!MemberPointerTypes.insert(Ty)) 7996 return false; 7997 7998 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7999 assert(PointerTy && "type was not a member pointer type!"); 8000 8001 QualType PointeeTy = PointerTy->getPointeeType(); 8002 // Don't add qualified variants of arrays. For one, they're not allowed 8003 // (the qualifier would sink to the element type), and for another, the 8004 // only overload situation where it matters is subscript or pointer +- int, 8005 // and those shouldn't have qualifier variants anyway. 8006 if (PointeeTy->isArrayType()) 8007 return true; 8008 const Type *ClassTy = PointerTy->getClass(); 8009 8010 // Iterate through all strict supersets of the pointee type's CVR 8011 // qualifiers. 8012 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8013 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8014 if ((CVR | BaseCVR) != CVR) continue; 8015 8016 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8017 MemberPointerTypes.insert( 8018 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8019 } 8020 8021 return true; 8022 } 8023 8024 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8025 /// Ty can be implicit converted to the given set of @p Types. We're 8026 /// primarily interested in pointer types and enumeration types. We also 8027 /// take member pointer types, for the conditional operator. 8028 /// AllowUserConversions is true if we should look at the conversion 8029 /// functions of a class type, and AllowExplicitConversions if we 8030 /// should also include the explicit conversion functions of a class 8031 /// type. 8032 void 8033 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8034 SourceLocation Loc, 8035 bool AllowUserConversions, 8036 bool AllowExplicitConversions, 8037 const Qualifiers &VisibleQuals) { 8038 // Only deal with canonical types. 8039 Ty = Context.getCanonicalType(Ty); 8040 8041 // Look through reference types; they aren't part of the type of an 8042 // expression for the purposes of conversions. 8043 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8044 Ty = RefTy->getPointeeType(); 8045 8046 // If we're dealing with an array type, decay to the pointer. 8047 if (Ty->isArrayType()) 8048 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8049 8050 // Otherwise, we don't care about qualifiers on the type. 8051 Ty = Ty.getLocalUnqualifiedType(); 8052 8053 // Flag if we ever add a non-record type. 8054 const RecordType *TyRec = Ty->getAs<RecordType>(); 8055 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8056 8057 // Flag if we encounter an arithmetic type. 8058 HasArithmeticOrEnumeralTypes = 8059 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8060 8061 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8062 PointerTypes.insert(Ty); 8063 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8064 // Insert our type, and its more-qualified variants, into the set 8065 // of types. 8066 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8067 return; 8068 } else if (Ty->isMemberPointerType()) { 8069 // Member pointers are far easier, since the pointee can't be converted. 8070 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8071 return; 8072 } else if (Ty->isEnumeralType()) { 8073 HasArithmeticOrEnumeralTypes = true; 8074 EnumerationTypes.insert(Ty); 8075 } else if (Ty->isVectorType()) { 8076 // We treat vector types as arithmetic types in many contexts as an 8077 // extension. 8078 HasArithmeticOrEnumeralTypes = true; 8079 VectorTypes.insert(Ty); 8080 } else if (Ty->isMatrixType()) { 8081 // Similar to vector types, we treat vector types as arithmetic types in 8082 // many contexts as an extension. 8083 HasArithmeticOrEnumeralTypes = true; 8084 MatrixTypes.insert(Ty); 8085 } else if (Ty->isNullPtrType()) { 8086 HasNullPtrType = true; 8087 } else if (AllowUserConversions && TyRec) { 8088 // No conversion functions in incomplete types. 8089 if (!SemaRef.isCompleteType(Loc, Ty)) 8090 return; 8091 8092 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8093 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8094 if (isa<UsingShadowDecl>(D)) 8095 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8096 8097 // Skip conversion function templates; they don't tell us anything 8098 // about which builtin types we can convert to. 8099 if (isa<FunctionTemplateDecl>(D)) 8100 continue; 8101 8102 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8103 if (AllowExplicitConversions || !Conv->isExplicit()) { 8104 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8105 VisibleQuals); 8106 } 8107 } 8108 } 8109 } 8110 /// Helper function for adjusting address spaces for the pointer or reference 8111 /// operands of builtin operators depending on the argument. 8112 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8113 Expr *Arg) { 8114 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8115 } 8116 8117 /// Helper function for AddBuiltinOperatorCandidates() that adds 8118 /// the volatile- and non-volatile-qualified assignment operators for the 8119 /// given type to the candidate set. 8120 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8121 QualType T, 8122 ArrayRef<Expr *> Args, 8123 OverloadCandidateSet &CandidateSet) { 8124 QualType ParamTypes[2]; 8125 8126 // T& operator=(T&, T) 8127 ParamTypes[0] = S.Context.getLValueReferenceType( 8128 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8129 ParamTypes[1] = T; 8130 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8131 /*IsAssignmentOperator=*/true); 8132 8133 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8134 // volatile T& operator=(volatile T&, T) 8135 ParamTypes[0] = S.Context.getLValueReferenceType( 8136 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8137 Args[0])); 8138 ParamTypes[1] = T; 8139 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8140 /*IsAssignmentOperator=*/true); 8141 } 8142 } 8143 8144 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8145 /// if any, found in visible type conversion functions found in ArgExpr's type. 8146 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8147 Qualifiers VRQuals; 8148 const RecordType *TyRec; 8149 if (const MemberPointerType *RHSMPType = 8150 ArgExpr->getType()->getAs<MemberPointerType>()) 8151 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8152 else 8153 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8154 if (!TyRec) { 8155 // Just to be safe, assume the worst case. 8156 VRQuals.addVolatile(); 8157 VRQuals.addRestrict(); 8158 return VRQuals; 8159 } 8160 8161 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8162 if (!ClassDecl->hasDefinition()) 8163 return VRQuals; 8164 8165 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8166 if (isa<UsingShadowDecl>(D)) 8167 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8168 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8169 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8170 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8171 CanTy = ResTypeRef->getPointeeType(); 8172 // Need to go down the pointer/mempointer chain and add qualifiers 8173 // as see them. 8174 bool done = false; 8175 while (!done) { 8176 if (CanTy.isRestrictQualified()) 8177 VRQuals.addRestrict(); 8178 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8179 CanTy = ResTypePtr->getPointeeType(); 8180 else if (const MemberPointerType *ResTypeMPtr = 8181 CanTy->getAs<MemberPointerType>()) 8182 CanTy = ResTypeMPtr->getPointeeType(); 8183 else 8184 done = true; 8185 if (CanTy.isVolatileQualified()) 8186 VRQuals.addVolatile(); 8187 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8188 return VRQuals; 8189 } 8190 } 8191 } 8192 return VRQuals; 8193 } 8194 8195 namespace { 8196 8197 /// Helper class to manage the addition of builtin operator overload 8198 /// candidates. It provides shared state and utility methods used throughout 8199 /// the process, as well as a helper method to add each group of builtin 8200 /// operator overloads from the standard to a candidate set. 8201 class BuiltinOperatorOverloadBuilder { 8202 // Common instance state available to all overload candidate addition methods. 8203 Sema &S; 8204 ArrayRef<Expr *> Args; 8205 Qualifiers VisibleTypeConversionsQuals; 8206 bool HasArithmeticOrEnumeralCandidateType; 8207 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8208 OverloadCandidateSet &CandidateSet; 8209 8210 static constexpr int ArithmeticTypesCap = 24; 8211 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8212 8213 // Define some indices used to iterate over the arithmetic types in 8214 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8215 // types are that preserved by promotion (C++ [over.built]p2). 8216 unsigned FirstIntegralType, 8217 LastIntegralType; 8218 unsigned FirstPromotedIntegralType, 8219 LastPromotedIntegralType; 8220 unsigned FirstPromotedArithmeticType, 8221 LastPromotedArithmeticType; 8222 unsigned NumArithmeticTypes; 8223 8224 void InitArithmeticTypes() { 8225 // Start of promoted types. 8226 FirstPromotedArithmeticType = 0; 8227 ArithmeticTypes.push_back(S.Context.FloatTy); 8228 ArithmeticTypes.push_back(S.Context.DoubleTy); 8229 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8230 if (S.Context.getTargetInfo().hasFloat128Type()) 8231 ArithmeticTypes.push_back(S.Context.Float128Ty); 8232 if (S.Context.getTargetInfo().hasIbm128Type()) 8233 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8234 8235 // Start of integral types. 8236 FirstIntegralType = ArithmeticTypes.size(); 8237 FirstPromotedIntegralType = ArithmeticTypes.size(); 8238 ArithmeticTypes.push_back(S.Context.IntTy); 8239 ArithmeticTypes.push_back(S.Context.LongTy); 8240 ArithmeticTypes.push_back(S.Context.LongLongTy); 8241 if (S.Context.getTargetInfo().hasInt128Type() || 8242 (S.Context.getAuxTargetInfo() && 8243 S.Context.getAuxTargetInfo()->hasInt128Type())) 8244 ArithmeticTypes.push_back(S.Context.Int128Ty); 8245 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8246 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8247 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8248 if (S.Context.getTargetInfo().hasInt128Type() || 8249 (S.Context.getAuxTargetInfo() && 8250 S.Context.getAuxTargetInfo()->hasInt128Type())) 8251 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8252 LastPromotedIntegralType = ArithmeticTypes.size(); 8253 LastPromotedArithmeticType = ArithmeticTypes.size(); 8254 // End of promoted types. 8255 8256 ArithmeticTypes.push_back(S.Context.BoolTy); 8257 ArithmeticTypes.push_back(S.Context.CharTy); 8258 ArithmeticTypes.push_back(S.Context.WCharTy); 8259 if (S.Context.getLangOpts().Char8) 8260 ArithmeticTypes.push_back(S.Context.Char8Ty); 8261 ArithmeticTypes.push_back(S.Context.Char16Ty); 8262 ArithmeticTypes.push_back(S.Context.Char32Ty); 8263 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8264 ArithmeticTypes.push_back(S.Context.ShortTy); 8265 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8266 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8267 LastIntegralType = ArithmeticTypes.size(); 8268 NumArithmeticTypes = ArithmeticTypes.size(); 8269 // End of integral types. 8270 // FIXME: What about complex? What about half? 8271 8272 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8273 "Enough inline storage for all arithmetic types."); 8274 } 8275 8276 /// Helper method to factor out the common pattern of adding overloads 8277 /// for '++' and '--' builtin operators. 8278 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8279 bool HasVolatile, 8280 bool HasRestrict) { 8281 QualType ParamTypes[2] = { 8282 S.Context.getLValueReferenceType(CandidateTy), 8283 S.Context.IntTy 8284 }; 8285 8286 // Non-volatile version. 8287 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8288 8289 // Use a heuristic to reduce number of builtin candidates in the set: 8290 // add volatile version only if there are conversions to a volatile type. 8291 if (HasVolatile) { 8292 ParamTypes[0] = 8293 S.Context.getLValueReferenceType( 8294 S.Context.getVolatileType(CandidateTy)); 8295 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8296 } 8297 8298 // Add restrict version only if there are conversions to a restrict type 8299 // and our candidate type is a non-restrict-qualified pointer. 8300 if (HasRestrict && CandidateTy->isAnyPointerType() && 8301 !CandidateTy.isRestrictQualified()) { 8302 ParamTypes[0] 8303 = S.Context.getLValueReferenceType( 8304 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8305 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8306 8307 if (HasVolatile) { 8308 ParamTypes[0] 8309 = S.Context.getLValueReferenceType( 8310 S.Context.getCVRQualifiedType(CandidateTy, 8311 (Qualifiers::Volatile | 8312 Qualifiers::Restrict))); 8313 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8314 } 8315 } 8316 8317 } 8318 8319 /// Helper to add an overload candidate for a binary builtin with types \p L 8320 /// and \p R. 8321 void AddCandidate(QualType L, QualType R) { 8322 QualType LandR[2] = {L, R}; 8323 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8324 } 8325 8326 public: 8327 BuiltinOperatorOverloadBuilder( 8328 Sema &S, ArrayRef<Expr *> Args, 8329 Qualifiers VisibleTypeConversionsQuals, 8330 bool HasArithmeticOrEnumeralCandidateType, 8331 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8332 OverloadCandidateSet &CandidateSet) 8333 : S(S), Args(Args), 8334 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8335 HasArithmeticOrEnumeralCandidateType( 8336 HasArithmeticOrEnumeralCandidateType), 8337 CandidateTypes(CandidateTypes), 8338 CandidateSet(CandidateSet) { 8339 8340 InitArithmeticTypes(); 8341 } 8342 8343 // Increment is deprecated for bool since C++17. 8344 // 8345 // C++ [over.built]p3: 8346 // 8347 // For every pair (T, VQ), where T is an arithmetic type other 8348 // than bool, and VQ is either volatile or empty, there exist 8349 // candidate operator functions of the form 8350 // 8351 // VQ T& operator++(VQ T&); 8352 // T operator++(VQ T&, int); 8353 // 8354 // C++ [over.built]p4: 8355 // 8356 // For every pair (T, VQ), where T is an arithmetic type other 8357 // than bool, and VQ is either volatile or empty, there exist 8358 // candidate operator functions of the form 8359 // 8360 // VQ T& operator--(VQ T&); 8361 // T operator--(VQ T&, int); 8362 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8363 if (!HasArithmeticOrEnumeralCandidateType) 8364 return; 8365 8366 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8367 const auto TypeOfT = ArithmeticTypes[Arith]; 8368 if (TypeOfT == S.Context.BoolTy) { 8369 if (Op == OO_MinusMinus) 8370 continue; 8371 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8372 continue; 8373 } 8374 addPlusPlusMinusMinusStyleOverloads( 8375 TypeOfT, 8376 VisibleTypeConversionsQuals.hasVolatile(), 8377 VisibleTypeConversionsQuals.hasRestrict()); 8378 } 8379 } 8380 8381 // C++ [over.built]p5: 8382 // 8383 // For every pair (T, VQ), where T is a cv-qualified or 8384 // cv-unqualified object type, and VQ is either volatile or 8385 // empty, there exist candidate operator functions of the form 8386 // 8387 // T*VQ& operator++(T*VQ&); 8388 // T*VQ& operator--(T*VQ&); 8389 // T* operator++(T*VQ&, int); 8390 // T* operator--(T*VQ&, int); 8391 void addPlusPlusMinusMinusPointerOverloads() { 8392 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8393 // Skip pointer types that aren't pointers to object types. 8394 if (!PtrTy->getPointeeType()->isObjectType()) 8395 continue; 8396 8397 addPlusPlusMinusMinusStyleOverloads( 8398 PtrTy, 8399 (!PtrTy.isVolatileQualified() && 8400 VisibleTypeConversionsQuals.hasVolatile()), 8401 (!PtrTy.isRestrictQualified() && 8402 VisibleTypeConversionsQuals.hasRestrict())); 8403 } 8404 } 8405 8406 // C++ [over.built]p6: 8407 // For every cv-qualified or cv-unqualified object type T, there 8408 // exist candidate operator functions of the form 8409 // 8410 // T& operator*(T*); 8411 // 8412 // C++ [over.built]p7: 8413 // For every function type T that does not have cv-qualifiers or a 8414 // ref-qualifier, there exist candidate operator functions of the form 8415 // T& operator*(T*); 8416 void addUnaryStarPointerOverloads() { 8417 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8418 QualType PointeeTy = ParamTy->getPointeeType(); 8419 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8420 continue; 8421 8422 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8423 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8424 continue; 8425 8426 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8427 } 8428 } 8429 8430 // C++ [over.built]p9: 8431 // For every promoted arithmetic type T, there exist candidate 8432 // operator functions of the form 8433 // 8434 // T operator+(T); 8435 // T operator-(T); 8436 void addUnaryPlusOrMinusArithmeticOverloads() { 8437 if (!HasArithmeticOrEnumeralCandidateType) 8438 return; 8439 8440 for (unsigned Arith = FirstPromotedArithmeticType; 8441 Arith < LastPromotedArithmeticType; ++Arith) { 8442 QualType ArithTy = ArithmeticTypes[Arith]; 8443 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8444 } 8445 8446 // Extension: We also add these operators for vector types. 8447 for (QualType VecTy : CandidateTypes[0].vector_types()) 8448 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8449 } 8450 8451 // C++ [over.built]p8: 8452 // For every type T, there exist candidate operator functions of 8453 // the form 8454 // 8455 // T* operator+(T*); 8456 void addUnaryPlusPointerOverloads() { 8457 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8458 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8459 } 8460 8461 // C++ [over.built]p10: 8462 // For every promoted integral type T, there exist candidate 8463 // operator functions of the form 8464 // 8465 // T operator~(T); 8466 void addUnaryTildePromotedIntegralOverloads() { 8467 if (!HasArithmeticOrEnumeralCandidateType) 8468 return; 8469 8470 for (unsigned Int = FirstPromotedIntegralType; 8471 Int < LastPromotedIntegralType; ++Int) { 8472 QualType IntTy = ArithmeticTypes[Int]; 8473 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8474 } 8475 8476 // Extension: We also add this operator for vector types. 8477 for (QualType VecTy : CandidateTypes[0].vector_types()) 8478 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8479 } 8480 8481 // C++ [over.match.oper]p16: 8482 // For every pointer to member type T or type std::nullptr_t, there 8483 // exist candidate operator functions of the form 8484 // 8485 // bool operator==(T,T); 8486 // bool operator!=(T,T); 8487 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8488 /// Set of (canonical) types that we've already handled. 8489 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8490 8491 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8492 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8493 // Don't add the same builtin candidate twice. 8494 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8495 continue; 8496 8497 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8498 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8499 } 8500 8501 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8502 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8503 if (AddedTypes.insert(NullPtrTy).second) { 8504 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8505 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8506 } 8507 } 8508 } 8509 } 8510 8511 // C++ [over.built]p15: 8512 // 8513 // For every T, where T is an enumeration type or a pointer type, 8514 // there exist candidate operator functions of the form 8515 // 8516 // bool operator<(T, T); 8517 // bool operator>(T, T); 8518 // bool operator<=(T, T); 8519 // bool operator>=(T, T); 8520 // bool operator==(T, T); 8521 // bool operator!=(T, T); 8522 // R operator<=>(T, T) 8523 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 8524 // C++ [over.match.oper]p3: 8525 // [...]the built-in candidates include all of the candidate operator 8526 // functions defined in 13.6 that, compared to the given operator, [...] 8527 // do not have the same parameter-type-list as any non-template non-member 8528 // candidate. 8529 // 8530 // Note that in practice, this only affects enumeration types because there 8531 // aren't any built-in candidates of record type, and a user-defined operator 8532 // must have an operand of record or enumeration type. Also, the only other 8533 // overloaded operator with enumeration arguments, operator=, 8534 // cannot be overloaded for enumeration types, so this is the only place 8535 // where we must suppress candidates like this. 8536 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8537 UserDefinedBinaryOperators; 8538 8539 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8540 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8541 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8542 CEnd = CandidateSet.end(); 8543 C != CEnd; ++C) { 8544 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8545 continue; 8546 8547 if (C->Function->isFunctionTemplateSpecialization()) 8548 continue; 8549 8550 // We interpret "same parameter-type-list" as applying to the 8551 // "synthesized candidate, with the order of the two parameters 8552 // reversed", not to the original function. 8553 bool Reversed = C->isReversed(); 8554 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8555 ->getType() 8556 .getUnqualifiedType(); 8557 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8558 ->getType() 8559 .getUnqualifiedType(); 8560 8561 // Skip if either parameter isn't of enumeral type. 8562 if (!FirstParamType->isEnumeralType() || 8563 !SecondParamType->isEnumeralType()) 8564 continue; 8565 8566 // Add this operator to the set of known user-defined operators. 8567 UserDefinedBinaryOperators.insert( 8568 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8569 S.Context.getCanonicalType(SecondParamType))); 8570 } 8571 } 8572 } 8573 8574 /// Set of (canonical) types that we've already handled. 8575 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8576 8577 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8578 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8579 // Don't add the same builtin candidate twice. 8580 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8581 continue; 8582 if (IsSpaceship && PtrTy->isFunctionPointerType()) 8583 continue; 8584 8585 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8586 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8587 } 8588 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8589 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8590 8591 // Don't add the same builtin candidate twice, or if a user defined 8592 // candidate exists. 8593 if (!AddedTypes.insert(CanonType).second || 8594 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8595 CanonType))) 8596 continue; 8597 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8598 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8599 } 8600 } 8601 } 8602 8603 // C++ [over.built]p13: 8604 // 8605 // For every cv-qualified or cv-unqualified object type T 8606 // there exist candidate operator functions of the form 8607 // 8608 // T* operator+(T*, ptrdiff_t); 8609 // T& operator[](T*, ptrdiff_t); [BELOW] 8610 // T* operator-(T*, ptrdiff_t); 8611 // T* operator+(ptrdiff_t, T*); 8612 // T& operator[](ptrdiff_t, T*); [BELOW] 8613 // 8614 // C++ [over.built]p14: 8615 // 8616 // For every T, where T is a pointer to object type, there 8617 // exist candidate operator functions of the form 8618 // 8619 // ptrdiff_t operator-(T, T); 8620 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8621 /// Set of (canonical) types that we've already handled. 8622 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8623 8624 for (int Arg = 0; Arg < 2; ++Arg) { 8625 QualType AsymmetricParamTypes[2] = { 8626 S.Context.getPointerDiffType(), 8627 S.Context.getPointerDiffType(), 8628 }; 8629 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8630 QualType PointeeTy = PtrTy->getPointeeType(); 8631 if (!PointeeTy->isObjectType()) 8632 continue; 8633 8634 AsymmetricParamTypes[Arg] = PtrTy; 8635 if (Arg == 0 || Op == OO_Plus) { 8636 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8637 // T* operator+(ptrdiff_t, T*); 8638 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8639 } 8640 if (Op == OO_Minus) { 8641 // ptrdiff_t operator-(T, T); 8642 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8643 continue; 8644 8645 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8646 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8647 } 8648 } 8649 } 8650 } 8651 8652 // C++ [over.built]p12: 8653 // 8654 // For every pair of promoted arithmetic types L and R, there 8655 // exist candidate operator functions of the form 8656 // 8657 // LR operator*(L, R); 8658 // LR operator/(L, R); 8659 // LR operator+(L, R); 8660 // LR operator-(L, R); 8661 // bool operator<(L, R); 8662 // bool operator>(L, R); 8663 // bool operator<=(L, R); 8664 // bool operator>=(L, R); 8665 // bool operator==(L, R); 8666 // bool operator!=(L, R); 8667 // 8668 // where LR is the result of the usual arithmetic conversions 8669 // between types L and R. 8670 // 8671 // C++ [over.built]p24: 8672 // 8673 // For every pair of promoted arithmetic types L and R, there exist 8674 // candidate operator functions of the form 8675 // 8676 // LR operator?(bool, L, R); 8677 // 8678 // where LR is the result of the usual arithmetic conversions 8679 // between types L and R. 8680 // Our candidates ignore the first parameter. 8681 void addGenericBinaryArithmeticOverloads() { 8682 if (!HasArithmeticOrEnumeralCandidateType) 8683 return; 8684 8685 for (unsigned Left = FirstPromotedArithmeticType; 8686 Left < LastPromotedArithmeticType; ++Left) { 8687 for (unsigned Right = FirstPromotedArithmeticType; 8688 Right < LastPromotedArithmeticType; ++Right) { 8689 QualType LandR[2] = { ArithmeticTypes[Left], 8690 ArithmeticTypes[Right] }; 8691 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8692 } 8693 } 8694 8695 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8696 // conditional operator for vector types. 8697 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8698 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8699 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8700 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8701 } 8702 } 8703 8704 /// Add binary operator overloads for each candidate matrix type M1, M2: 8705 /// * (M1, M1) -> M1 8706 /// * (M1, M1.getElementType()) -> M1 8707 /// * (M2.getElementType(), M2) -> M2 8708 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8709 void addMatrixBinaryArithmeticOverloads() { 8710 if (!HasArithmeticOrEnumeralCandidateType) 8711 return; 8712 8713 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8714 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8715 AddCandidate(M1, M1); 8716 } 8717 8718 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8719 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8720 if (!CandidateTypes[0].containsMatrixType(M2)) 8721 AddCandidate(M2, M2); 8722 } 8723 } 8724 8725 // C++2a [over.built]p14: 8726 // 8727 // For every integral type T there exists a candidate operator function 8728 // of the form 8729 // 8730 // std::strong_ordering operator<=>(T, T) 8731 // 8732 // C++2a [over.built]p15: 8733 // 8734 // For every pair of floating-point types L and R, there exists a candidate 8735 // operator function of the form 8736 // 8737 // std::partial_ordering operator<=>(L, R); 8738 // 8739 // FIXME: The current specification for integral types doesn't play nice with 8740 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8741 // comparisons. Under the current spec this can lead to ambiguity during 8742 // overload resolution. For example: 8743 // 8744 // enum A : int {a}; 8745 // auto x = (a <=> (long)42); 8746 // 8747 // error: call is ambiguous for arguments 'A' and 'long'. 8748 // note: candidate operator<=>(int, int) 8749 // note: candidate operator<=>(long, long) 8750 // 8751 // To avoid this error, this function deviates from the specification and adds 8752 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8753 // arithmetic types (the same as the generic relational overloads). 8754 // 8755 // For now this function acts as a placeholder. 8756 void addThreeWayArithmeticOverloads() { 8757 addGenericBinaryArithmeticOverloads(); 8758 } 8759 8760 // C++ [over.built]p17: 8761 // 8762 // For every pair of promoted integral types L and R, there 8763 // exist candidate operator functions of the form 8764 // 8765 // LR operator%(L, R); 8766 // LR operator&(L, R); 8767 // LR operator^(L, R); 8768 // LR operator|(L, R); 8769 // L operator<<(L, R); 8770 // L operator>>(L, R); 8771 // 8772 // where LR is the result of the usual arithmetic conversions 8773 // between types L and R. 8774 void addBinaryBitwiseArithmeticOverloads() { 8775 if (!HasArithmeticOrEnumeralCandidateType) 8776 return; 8777 8778 for (unsigned Left = FirstPromotedIntegralType; 8779 Left < LastPromotedIntegralType; ++Left) { 8780 for (unsigned Right = FirstPromotedIntegralType; 8781 Right < LastPromotedIntegralType; ++Right) { 8782 QualType LandR[2] = { ArithmeticTypes[Left], 8783 ArithmeticTypes[Right] }; 8784 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8785 } 8786 } 8787 } 8788 8789 // C++ [over.built]p20: 8790 // 8791 // For every pair (T, VQ), where T is an enumeration or 8792 // pointer to member type and VQ is either volatile or 8793 // empty, there exist candidate operator functions of the form 8794 // 8795 // VQ T& operator=(VQ T&, T); 8796 void addAssignmentMemberPointerOrEnumeralOverloads() { 8797 /// Set of (canonical) types that we've already handled. 8798 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8799 8800 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8801 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8802 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8803 continue; 8804 8805 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8806 } 8807 8808 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8809 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8810 continue; 8811 8812 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8813 } 8814 } 8815 } 8816 8817 // C++ [over.built]p19: 8818 // 8819 // For every pair (T, VQ), where T is any type and VQ is either 8820 // volatile or empty, there exist candidate operator functions 8821 // of the form 8822 // 8823 // T*VQ& operator=(T*VQ&, T*); 8824 // 8825 // C++ [over.built]p21: 8826 // 8827 // For every pair (T, VQ), where T is a cv-qualified or 8828 // cv-unqualified object type and VQ is either volatile or 8829 // empty, there exist candidate operator functions of the form 8830 // 8831 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8832 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8833 void addAssignmentPointerOverloads(bool isEqualOp) { 8834 /// Set of (canonical) types that we've already handled. 8835 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8836 8837 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8838 // If this is operator=, keep track of the builtin candidates we added. 8839 if (isEqualOp) 8840 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8841 else if (!PtrTy->getPointeeType()->isObjectType()) 8842 continue; 8843 8844 // non-volatile version 8845 QualType ParamTypes[2] = { 8846 S.Context.getLValueReferenceType(PtrTy), 8847 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8848 }; 8849 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8850 /*IsAssignmentOperator=*/ isEqualOp); 8851 8852 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8853 VisibleTypeConversionsQuals.hasVolatile(); 8854 if (NeedVolatile) { 8855 // volatile version 8856 ParamTypes[0] = 8857 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8858 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8859 /*IsAssignmentOperator=*/isEqualOp); 8860 } 8861 8862 if (!PtrTy.isRestrictQualified() && 8863 VisibleTypeConversionsQuals.hasRestrict()) { 8864 // restrict version 8865 ParamTypes[0] = 8866 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8867 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8868 /*IsAssignmentOperator=*/isEqualOp); 8869 8870 if (NeedVolatile) { 8871 // volatile restrict version 8872 ParamTypes[0] = 8873 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8874 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8875 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8876 /*IsAssignmentOperator=*/isEqualOp); 8877 } 8878 } 8879 } 8880 8881 if (isEqualOp) { 8882 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8883 // Make sure we don't add the same candidate twice. 8884 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8885 continue; 8886 8887 QualType ParamTypes[2] = { 8888 S.Context.getLValueReferenceType(PtrTy), 8889 PtrTy, 8890 }; 8891 8892 // non-volatile version 8893 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8894 /*IsAssignmentOperator=*/true); 8895 8896 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8897 VisibleTypeConversionsQuals.hasVolatile(); 8898 if (NeedVolatile) { 8899 // volatile version 8900 ParamTypes[0] = S.Context.getLValueReferenceType( 8901 S.Context.getVolatileType(PtrTy)); 8902 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8903 /*IsAssignmentOperator=*/true); 8904 } 8905 8906 if (!PtrTy.isRestrictQualified() && 8907 VisibleTypeConversionsQuals.hasRestrict()) { 8908 // restrict version 8909 ParamTypes[0] = S.Context.getLValueReferenceType( 8910 S.Context.getRestrictType(PtrTy)); 8911 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8912 /*IsAssignmentOperator=*/true); 8913 8914 if (NeedVolatile) { 8915 // volatile restrict version 8916 ParamTypes[0] = 8917 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8918 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8919 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8920 /*IsAssignmentOperator=*/true); 8921 } 8922 } 8923 } 8924 } 8925 } 8926 8927 // C++ [over.built]p18: 8928 // 8929 // For every triple (L, VQ, R), where L is an arithmetic type, 8930 // VQ is either volatile or empty, and R is a promoted 8931 // arithmetic type, there exist candidate operator functions of 8932 // the form 8933 // 8934 // VQ L& operator=(VQ L&, R); 8935 // VQ L& operator*=(VQ L&, R); 8936 // VQ L& operator/=(VQ L&, R); 8937 // VQ L& operator+=(VQ L&, R); 8938 // VQ L& operator-=(VQ L&, R); 8939 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8940 if (!HasArithmeticOrEnumeralCandidateType) 8941 return; 8942 8943 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8944 for (unsigned Right = FirstPromotedArithmeticType; 8945 Right < LastPromotedArithmeticType; ++Right) { 8946 QualType ParamTypes[2]; 8947 ParamTypes[1] = ArithmeticTypes[Right]; 8948 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8949 S, ArithmeticTypes[Left], Args[0]); 8950 // Add this built-in operator as a candidate (VQ is empty). 8951 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8952 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8953 /*IsAssignmentOperator=*/isEqualOp); 8954 8955 // Add this built-in operator as a candidate (VQ is 'volatile'). 8956 if (VisibleTypeConversionsQuals.hasVolatile()) { 8957 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8958 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8959 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8960 /*IsAssignmentOperator=*/isEqualOp); 8961 } 8962 } 8963 } 8964 8965 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8966 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8967 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8968 QualType ParamTypes[2]; 8969 ParamTypes[1] = Vec2Ty; 8970 // Add this built-in operator as a candidate (VQ is empty). 8971 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8972 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8973 /*IsAssignmentOperator=*/isEqualOp); 8974 8975 // Add this built-in operator as a candidate (VQ is 'volatile'). 8976 if (VisibleTypeConversionsQuals.hasVolatile()) { 8977 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8978 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8979 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8980 /*IsAssignmentOperator=*/isEqualOp); 8981 } 8982 } 8983 } 8984 8985 // C++ [over.built]p22: 8986 // 8987 // For every triple (L, VQ, R), where L is an integral type, VQ 8988 // is either volatile or empty, and R is a promoted integral 8989 // type, there exist candidate operator functions of the form 8990 // 8991 // VQ L& operator%=(VQ L&, R); 8992 // VQ L& operator<<=(VQ L&, R); 8993 // VQ L& operator>>=(VQ L&, R); 8994 // VQ L& operator&=(VQ L&, R); 8995 // VQ L& operator^=(VQ L&, R); 8996 // VQ L& operator|=(VQ L&, R); 8997 void addAssignmentIntegralOverloads() { 8998 if (!HasArithmeticOrEnumeralCandidateType) 8999 return; 9000 9001 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9002 for (unsigned Right = FirstPromotedIntegralType; 9003 Right < LastPromotedIntegralType; ++Right) { 9004 QualType ParamTypes[2]; 9005 ParamTypes[1] = ArithmeticTypes[Right]; 9006 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9007 S, ArithmeticTypes[Left], Args[0]); 9008 // Add this built-in operator as a candidate (VQ is empty). 9009 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 9010 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9011 if (VisibleTypeConversionsQuals.hasVolatile()) { 9012 // Add this built-in operator as a candidate (VQ is 'volatile'). 9013 ParamTypes[0] = LeftBaseTy; 9014 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 9015 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9016 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9017 } 9018 } 9019 } 9020 } 9021 9022 // C++ [over.operator]p23: 9023 // 9024 // There also exist candidate operator functions of the form 9025 // 9026 // bool operator!(bool); 9027 // bool operator&&(bool, bool); 9028 // bool operator||(bool, bool); 9029 void addExclaimOverload() { 9030 QualType ParamTy = S.Context.BoolTy; 9031 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9032 /*IsAssignmentOperator=*/false, 9033 /*NumContextualBoolArguments=*/1); 9034 } 9035 void addAmpAmpOrPipePipeOverload() { 9036 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9037 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9038 /*IsAssignmentOperator=*/false, 9039 /*NumContextualBoolArguments=*/2); 9040 } 9041 9042 // C++ [over.built]p13: 9043 // 9044 // For every cv-qualified or cv-unqualified object type T there 9045 // exist candidate operator functions of the form 9046 // 9047 // T* operator+(T*, ptrdiff_t); [ABOVE] 9048 // T& operator[](T*, ptrdiff_t); 9049 // T* operator-(T*, ptrdiff_t); [ABOVE] 9050 // T* operator+(ptrdiff_t, T*); [ABOVE] 9051 // T& operator[](ptrdiff_t, T*); 9052 void addSubscriptOverloads() { 9053 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9054 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9055 QualType PointeeType = PtrTy->getPointeeType(); 9056 if (!PointeeType->isObjectType()) 9057 continue; 9058 9059 // T& operator[](T*, ptrdiff_t) 9060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9061 } 9062 9063 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9064 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9065 QualType PointeeType = PtrTy->getPointeeType(); 9066 if (!PointeeType->isObjectType()) 9067 continue; 9068 9069 // T& operator[](ptrdiff_t, T*) 9070 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9071 } 9072 } 9073 9074 // C++ [over.built]p11: 9075 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9076 // C1 is the same type as C2 or is a derived class of C2, T is an object 9077 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9078 // there exist candidate operator functions of the form 9079 // 9080 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9081 // 9082 // where CV12 is the union of CV1 and CV2. 9083 void addArrowStarOverloads() { 9084 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9085 QualType C1Ty = PtrTy; 9086 QualType C1; 9087 QualifierCollector Q1; 9088 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9089 if (!isa<RecordType>(C1)) 9090 continue; 9091 // heuristic to reduce number of builtin candidates in the set. 9092 // Add volatile/restrict version only if there are conversions to a 9093 // volatile/restrict type. 9094 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9095 continue; 9096 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9097 continue; 9098 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9099 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9100 QualType C2 = QualType(mptr->getClass(), 0); 9101 C2 = C2.getUnqualifiedType(); 9102 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9103 break; 9104 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9105 // build CV12 T& 9106 QualType T = mptr->getPointeeType(); 9107 if (!VisibleTypeConversionsQuals.hasVolatile() && 9108 T.isVolatileQualified()) 9109 continue; 9110 if (!VisibleTypeConversionsQuals.hasRestrict() && 9111 T.isRestrictQualified()) 9112 continue; 9113 T = Q1.apply(S.Context, T); 9114 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9115 } 9116 } 9117 } 9118 9119 // Note that we don't consider the first argument, since it has been 9120 // contextually converted to bool long ago. The candidates below are 9121 // therefore added as binary. 9122 // 9123 // C++ [over.built]p25: 9124 // For every type T, where T is a pointer, pointer-to-member, or scoped 9125 // enumeration type, there exist candidate operator functions of the form 9126 // 9127 // T operator?(bool, T, T); 9128 // 9129 void addConditionalOperatorOverloads() { 9130 /// Set of (canonical) types that we've already handled. 9131 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9132 9133 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9134 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9135 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9136 continue; 9137 9138 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9139 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9140 } 9141 9142 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9143 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9144 continue; 9145 9146 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9148 } 9149 9150 if (S.getLangOpts().CPlusPlus11) { 9151 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9152 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9153 continue; 9154 9155 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9156 continue; 9157 9158 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9159 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9160 } 9161 } 9162 } 9163 } 9164 }; 9165 9166 } // end anonymous namespace 9167 9168 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9169 /// operator overloads to the candidate set (C++ [over.built]), based 9170 /// on the operator @p Op and the arguments given. For example, if the 9171 /// operator is a binary '+', this routine might add "int 9172 /// operator+(int, int)" to cover integer addition. 9173 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9174 SourceLocation OpLoc, 9175 ArrayRef<Expr *> Args, 9176 OverloadCandidateSet &CandidateSet) { 9177 // Find all of the types that the arguments can convert to, but only 9178 // if the operator we're looking at has built-in operator candidates 9179 // that make use of these types. Also record whether we encounter non-record 9180 // candidate types or either arithmetic or enumeral candidate types. 9181 Qualifiers VisibleTypeConversionsQuals; 9182 VisibleTypeConversionsQuals.addConst(); 9183 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9184 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9185 9186 bool HasNonRecordCandidateType = false; 9187 bool HasArithmeticOrEnumeralCandidateType = false; 9188 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9189 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9190 CandidateTypes.emplace_back(*this); 9191 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9192 OpLoc, 9193 true, 9194 (Op == OO_Exclaim || 9195 Op == OO_AmpAmp || 9196 Op == OO_PipePipe), 9197 VisibleTypeConversionsQuals); 9198 HasNonRecordCandidateType = HasNonRecordCandidateType || 9199 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9200 HasArithmeticOrEnumeralCandidateType = 9201 HasArithmeticOrEnumeralCandidateType || 9202 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9203 } 9204 9205 // Exit early when no non-record types have been added to the candidate set 9206 // for any of the arguments to the operator. 9207 // 9208 // We can't exit early for !, ||, or &&, since there we have always have 9209 // 'bool' overloads. 9210 if (!HasNonRecordCandidateType && 9211 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9212 return; 9213 9214 // Setup an object to manage the common state for building overloads. 9215 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9216 VisibleTypeConversionsQuals, 9217 HasArithmeticOrEnumeralCandidateType, 9218 CandidateTypes, CandidateSet); 9219 9220 // Dispatch over the operation to add in only those overloads which apply. 9221 switch (Op) { 9222 case OO_None: 9223 case NUM_OVERLOADED_OPERATORS: 9224 llvm_unreachable("Expected an overloaded operator"); 9225 9226 case OO_New: 9227 case OO_Delete: 9228 case OO_Array_New: 9229 case OO_Array_Delete: 9230 case OO_Call: 9231 llvm_unreachable( 9232 "Special operators don't use AddBuiltinOperatorCandidates"); 9233 9234 case OO_Comma: 9235 case OO_Arrow: 9236 case OO_Coawait: 9237 // C++ [over.match.oper]p3: 9238 // -- For the operator ',', the unary operator '&', the 9239 // operator '->', or the operator 'co_await', the 9240 // built-in candidates set is empty. 9241 break; 9242 9243 case OO_Plus: // '+' is either unary or binary 9244 if (Args.size() == 1) 9245 OpBuilder.addUnaryPlusPointerOverloads(); 9246 LLVM_FALLTHROUGH; 9247 9248 case OO_Minus: // '-' is either unary or binary 9249 if (Args.size() == 1) { 9250 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9251 } else { 9252 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9253 OpBuilder.addGenericBinaryArithmeticOverloads(); 9254 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9255 } 9256 break; 9257 9258 case OO_Star: // '*' is either unary or binary 9259 if (Args.size() == 1) 9260 OpBuilder.addUnaryStarPointerOverloads(); 9261 else { 9262 OpBuilder.addGenericBinaryArithmeticOverloads(); 9263 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9264 } 9265 break; 9266 9267 case OO_Slash: 9268 OpBuilder.addGenericBinaryArithmeticOverloads(); 9269 break; 9270 9271 case OO_PlusPlus: 9272 case OO_MinusMinus: 9273 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9274 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9275 break; 9276 9277 case OO_EqualEqual: 9278 case OO_ExclaimEqual: 9279 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9280 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9281 OpBuilder.addGenericBinaryArithmeticOverloads(); 9282 break; 9283 9284 case OO_Less: 9285 case OO_Greater: 9286 case OO_LessEqual: 9287 case OO_GreaterEqual: 9288 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9289 OpBuilder.addGenericBinaryArithmeticOverloads(); 9290 break; 9291 9292 case OO_Spaceship: 9293 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9294 OpBuilder.addThreeWayArithmeticOverloads(); 9295 break; 9296 9297 case OO_Percent: 9298 case OO_Caret: 9299 case OO_Pipe: 9300 case OO_LessLess: 9301 case OO_GreaterGreater: 9302 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9303 break; 9304 9305 case OO_Amp: // '&' is either unary or binary 9306 if (Args.size() == 1) 9307 // C++ [over.match.oper]p3: 9308 // -- For the operator ',', the unary operator '&', or the 9309 // operator '->', the built-in candidates set is empty. 9310 break; 9311 9312 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9313 break; 9314 9315 case OO_Tilde: 9316 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9317 break; 9318 9319 case OO_Equal: 9320 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9321 LLVM_FALLTHROUGH; 9322 9323 case OO_PlusEqual: 9324 case OO_MinusEqual: 9325 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9326 LLVM_FALLTHROUGH; 9327 9328 case OO_StarEqual: 9329 case OO_SlashEqual: 9330 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9331 break; 9332 9333 case OO_PercentEqual: 9334 case OO_LessLessEqual: 9335 case OO_GreaterGreaterEqual: 9336 case OO_AmpEqual: 9337 case OO_CaretEqual: 9338 case OO_PipeEqual: 9339 OpBuilder.addAssignmentIntegralOverloads(); 9340 break; 9341 9342 case OO_Exclaim: 9343 OpBuilder.addExclaimOverload(); 9344 break; 9345 9346 case OO_AmpAmp: 9347 case OO_PipePipe: 9348 OpBuilder.addAmpAmpOrPipePipeOverload(); 9349 break; 9350 9351 case OO_Subscript: 9352 if (Args.size() == 2) 9353 OpBuilder.addSubscriptOverloads(); 9354 break; 9355 9356 case OO_ArrowStar: 9357 OpBuilder.addArrowStarOverloads(); 9358 break; 9359 9360 case OO_Conditional: 9361 OpBuilder.addConditionalOperatorOverloads(); 9362 OpBuilder.addGenericBinaryArithmeticOverloads(); 9363 break; 9364 } 9365 } 9366 9367 /// Add function candidates found via argument-dependent lookup 9368 /// to the set of overloading candidates. 9369 /// 9370 /// This routine performs argument-dependent name lookup based on the 9371 /// given function name (which may also be an operator name) and adds 9372 /// all of the overload candidates found by ADL to the overload 9373 /// candidate set (C++ [basic.lookup.argdep]). 9374 void 9375 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9376 SourceLocation Loc, 9377 ArrayRef<Expr *> Args, 9378 TemplateArgumentListInfo *ExplicitTemplateArgs, 9379 OverloadCandidateSet& CandidateSet, 9380 bool PartialOverloading) { 9381 ADLResult Fns; 9382 9383 // FIXME: This approach for uniquing ADL results (and removing 9384 // redundant candidates from the set) relies on pointer-equality, 9385 // which means we need to key off the canonical decl. However, 9386 // always going back to the canonical decl might not get us the 9387 // right set of default arguments. What default arguments are 9388 // we supposed to consider on ADL candidates, anyway? 9389 9390 // FIXME: Pass in the explicit template arguments? 9391 ArgumentDependentLookup(Name, Loc, Args, Fns); 9392 9393 // Erase all of the candidates we already knew about. 9394 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9395 CandEnd = CandidateSet.end(); 9396 Cand != CandEnd; ++Cand) 9397 if (Cand->Function) { 9398 Fns.erase(Cand->Function); 9399 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9400 Fns.erase(FunTmpl); 9401 } 9402 9403 // For each of the ADL candidates we found, add it to the overload 9404 // set. 9405 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9406 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9407 9408 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9409 if (ExplicitTemplateArgs) 9410 continue; 9411 9412 AddOverloadCandidate( 9413 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9414 PartialOverloading, /*AllowExplicit=*/true, 9415 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9416 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9417 AddOverloadCandidate( 9418 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9419 /*SuppressUserConversions=*/false, PartialOverloading, 9420 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9421 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9422 } 9423 } else { 9424 auto *FTD = cast<FunctionTemplateDecl>(*I); 9425 AddTemplateOverloadCandidate( 9426 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9427 /*SuppressUserConversions=*/false, PartialOverloading, 9428 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9429 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9430 Context, FTD->getTemplatedDecl())) { 9431 AddTemplateOverloadCandidate( 9432 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9433 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9434 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9435 OverloadCandidateParamOrder::Reversed); 9436 } 9437 } 9438 } 9439 } 9440 9441 namespace { 9442 enum class Comparison { Equal, Better, Worse }; 9443 } 9444 9445 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9446 /// overload resolution. 9447 /// 9448 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9449 /// Cand1's first N enable_if attributes have precisely the same conditions as 9450 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9451 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9452 /// 9453 /// Note that you can have a pair of candidates such that Cand1's enable_if 9454 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9455 /// worse than Cand1's. 9456 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9457 const FunctionDecl *Cand2) { 9458 // Common case: One (or both) decls don't have enable_if attrs. 9459 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9460 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9461 if (!Cand1Attr || !Cand2Attr) { 9462 if (Cand1Attr == Cand2Attr) 9463 return Comparison::Equal; 9464 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9465 } 9466 9467 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9468 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9469 9470 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9471 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9472 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9473 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9474 9475 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9476 // has fewer enable_if attributes than Cand2, and vice versa. 9477 if (!Cand1A) 9478 return Comparison::Worse; 9479 if (!Cand2A) 9480 return Comparison::Better; 9481 9482 Cand1ID.clear(); 9483 Cand2ID.clear(); 9484 9485 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9486 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9487 if (Cand1ID != Cand2ID) 9488 return Comparison::Worse; 9489 } 9490 9491 return Comparison::Equal; 9492 } 9493 9494 static Comparison 9495 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9496 const OverloadCandidate &Cand2) { 9497 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9498 !Cand2.Function->isMultiVersion()) 9499 return Comparison::Equal; 9500 9501 // If both are invalid, they are equal. If one of them is invalid, the other 9502 // is better. 9503 if (Cand1.Function->isInvalidDecl()) { 9504 if (Cand2.Function->isInvalidDecl()) 9505 return Comparison::Equal; 9506 return Comparison::Worse; 9507 } 9508 if (Cand2.Function->isInvalidDecl()) 9509 return Comparison::Better; 9510 9511 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9512 // cpu_dispatch, else arbitrarily based on the identifiers. 9513 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9514 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9515 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9516 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9517 9518 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9519 return Comparison::Equal; 9520 9521 if (Cand1CPUDisp && !Cand2CPUDisp) 9522 return Comparison::Better; 9523 if (Cand2CPUDisp && !Cand1CPUDisp) 9524 return Comparison::Worse; 9525 9526 if (Cand1CPUSpec && Cand2CPUSpec) { 9527 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9528 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9529 ? Comparison::Better 9530 : Comparison::Worse; 9531 9532 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9533 FirstDiff = std::mismatch( 9534 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9535 Cand2CPUSpec->cpus_begin(), 9536 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9537 return LHS->getName() == RHS->getName(); 9538 }); 9539 9540 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9541 "Two different cpu-specific versions should not have the same " 9542 "identifier list, otherwise they'd be the same decl!"); 9543 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9544 ? Comparison::Better 9545 : Comparison::Worse; 9546 } 9547 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9548 } 9549 9550 /// Compute the type of the implicit object parameter for the given function, 9551 /// if any. Returns None if there is no implicit object parameter, and a null 9552 /// QualType if there is a 'matches anything' implicit object parameter. 9553 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9554 const FunctionDecl *F) { 9555 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9556 return llvm::None; 9557 9558 auto *M = cast<CXXMethodDecl>(F); 9559 // Static member functions' object parameters match all types. 9560 if (M->isStatic()) 9561 return QualType(); 9562 9563 QualType T = M->getThisObjectType(); 9564 if (M->getRefQualifier() == RQ_RValue) 9565 return Context.getRValueReferenceType(T); 9566 return Context.getLValueReferenceType(T); 9567 } 9568 9569 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9570 const FunctionDecl *F2, unsigned NumParams) { 9571 if (declaresSameEntity(F1, F2)) 9572 return true; 9573 9574 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9575 if (First) { 9576 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9577 return *T; 9578 } 9579 assert(I < F->getNumParams()); 9580 return F->getParamDecl(I++)->getType(); 9581 }; 9582 9583 unsigned I1 = 0, I2 = 0; 9584 for (unsigned I = 0; I != NumParams; ++I) { 9585 QualType T1 = NextParam(F1, I1, I == 0); 9586 QualType T2 = NextParam(F2, I2, I == 0); 9587 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 9588 if (!Context.hasSameUnqualifiedType(T1, T2)) 9589 return false; 9590 } 9591 return true; 9592 } 9593 9594 /// isBetterOverloadCandidate - Determines whether the first overload 9595 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9596 bool clang::isBetterOverloadCandidate( 9597 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9598 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9599 // Define viable functions to be better candidates than non-viable 9600 // functions. 9601 if (!Cand2.Viable) 9602 return Cand1.Viable; 9603 else if (!Cand1.Viable) 9604 return false; 9605 9606 // [CUDA] A function with 'never' preference is marked not viable, therefore 9607 // is never shown up here. The worst preference shown up here is 'wrong side', 9608 // e.g. an H function called by a HD function in device compilation. This is 9609 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9610 // function which is called only by an H function. A deferred diagnostic will 9611 // be triggered if it is emitted. However a wrong-sided function is still 9612 // a viable candidate here. 9613 // 9614 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9615 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9616 // can be emitted, Cand1 is not better than Cand2. This rule should have 9617 // precedence over other rules. 9618 // 9619 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9620 // other rules should be used to determine which is better. This is because 9621 // host/device based overloading resolution is mostly for determining 9622 // viability of a function. If two functions are both viable, other factors 9623 // should take precedence in preference, e.g. the standard-defined preferences 9624 // like argument conversion ranks or enable_if partial-ordering. The 9625 // preference for pass-object-size parameters is probably most similar to a 9626 // type-based-overloading decision and so should take priority. 9627 // 9628 // If other rules cannot determine which is better, CUDA preference will be 9629 // used again to determine which is better. 9630 // 9631 // TODO: Currently IdentifyCUDAPreference does not return correct values 9632 // for functions called in global variable initializers due to missing 9633 // correct context about device/host. Therefore we can only enforce this 9634 // rule when there is a caller. We should enforce this rule for functions 9635 // in global variable initializers once proper context is added. 9636 // 9637 // TODO: We can only enable the hostness based overloading resolution when 9638 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9639 // overloading resolution diagnostics. 9640 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9641 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9642 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9643 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9644 bool IsCand1ImplicitHD = 9645 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9646 bool IsCand2ImplicitHD = 9647 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9648 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9649 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9650 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9651 // The implicit HD function may be a function in a system header which 9652 // is forced by pragma. In device compilation, if we prefer HD candidates 9653 // over wrong-sided candidates, overloading resolution may change, which 9654 // may result in non-deferrable diagnostics. As a workaround, we let 9655 // implicit HD candidates take equal preference as wrong-sided candidates. 9656 // This will preserve the overloading resolution. 9657 // TODO: We still need special handling of implicit HD functions since 9658 // they may incur other diagnostics to be deferred. We should make all 9659 // host/device related diagnostics deferrable and remove special handling 9660 // of implicit HD functions. 9661 auto EmitThreshold = 9662 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9663 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9664 ? Sema::CFP_Never 9665 : Sema::CFP_WrongSide; 9666 auto Cand1Emittable = P1 > EmitThreshold; 9667 auto Cand2Emittable = P2 > EmitThreshold; 9668 if (Cand1Emittable && !Cand2Emittable) 9669 return true; 9670 if (!Cand1Emittable && Cand2Emittable) 9671 return false; 9672 } 9673 } 9674 9675 // C++ [over.match.best]p1: 9676 // 9677 // -- if F is a static member function, ICS1(F) is defined such 9678 // that ICS1(F) is neither better nor worse than ICS1(G) for 9679 // any function G, and, symmetrically, ICS1(G) is neither 9680 // better nor worse than ICS1(F). 9681 unsigned StartArg = 0; 9682 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9683 StartArg = 1; 9684 9685 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9686 // We don't allow incompatible pointer conversions in C++. 9687 if (!S.getLangOpts().CPlusPlus) 9688 return ICS.isStandard() && 9689 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9690 9691 // The only ill-formed conversion we allow in C++ is the string literal to 9692 // char* conversion, which is only considered ill-formed after C++11. 9693 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9694 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9695 }; 9696 9697 // Define functions that don't require ill-formed conversions for a given 9698 // argument to be better candidates than functions that do. 9699 unsigned NumArgs = Cand1.Conversions.size(); 9700 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9701 bool HasBetterConversion = false; 9702 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9703 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9704 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9705 if (Cand1Bad != Cand2Bad) { 9706 if (Cand1Bad) 9707 return false; 9708 HasBetterConversion = true; 9709 } 9710 } 9711 9712 if (HasBetterConversion) 9713 return true; 9714 9715 // C++ [over.match.best]p1: 9716 // A viable function F1 is defined to be a better function than another 9717 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9718 // conversion sequence than ICSi(F2), and then... 9719 bool HasWorseConversion = false; 9720 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9721 switch (CompareImplicitConversionSequences(S, Loc, 9722 Cand1.Conversions[ArgIdx], 9723 Cand2.Conversions[ArgIdx])) { 9724 case ImplicitConversionSequence::Better: 9725 // Cand1 has a better conversion sequence. 9726 HasBetterConversion = true; 9727 break; 9728 9729 case ImplicitConversionSequence::Worse: 9730 if (Cand1.Function && Cand2.Function && 9731 Cand1.isReversed() != Cand2.isReversed() && 9732 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9733 NumArgs)) { 9734 // Work around large-scale breakage caused by considering reversed 9735 // forms of operator== in C++20: 9736 // 9737 // When comparing a function against a reversed function with the same 9738 // parameter types, if we have a better conversion for one argument and 9739 // a worse conversion for the other, the implicit conversion sequences 9740 // are treated as being equally good. 9741 // 9742 // This prevents a comparison function from being considered ambiguous 9743 // with a reversed form that is written in the same way. 9744 // 9745 // We diagnose this as an extension from CreateOverloadedBinOp. 9746 HasWorseConversion = true; 9747 break; 9748 } 9749 9750 // Cand1 can't be better than Cand2. 9751 return false; 9752 9753 case ImplicitConversionSequence::Indistinguishable: 9754 // Do nothing. 9755 break; 9756 } 9757 } 9758 9759 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9760 // ICSj(F2), or, if not that, 9761 if (HasBetterConversion && !HasWorseConversion) 9762 return true; 9763 9764 // -- the context is an initialization by user-defined conversion 9765 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9766 // from the return type of F1 to the destination type (i.e., 9767 // the type of the entity being initialized) is a better 9768 // conversion sequence than the standard conversion sequence 9769 // from the return type of F2 to the destination type. 9770 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9771 Cand1.Function && Cand2.Function && 9772 isa<CXXConversionDecl>(Cand1.Function) && 9773 isa<CXXConversionDecl>(Cand2.Function)) { 9774 // First check whether we prefer one of the conversion functions over the 9775 // other. This only distinguishes the results in non-standard, extension 9776 // cases such as the conversion from a lambda closure type to a function 9777 // pointer or block. 9778 ImplicitConversionSequence::CompareKind Result = 9779 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9780 if (Result == ImplicitConversionSequence::Indistinguishable) 9781 Result = CompareStandardConversionSequences(S, Loc, 9782 Cand1.FinalConversion, 9783 Cand2.FinalConversion); 9784 9785 if (Result != ImplicitConversionSequence::Indistinguishable) 9786 return Result == ImplicitConversionSequence::Better; 9787 9788 // FIXME: Compare kind of reference binding if conversion functions 9789 // convert to a reference type used in direct reference binding, per 9790 // C++14 [over.match.best]p1 section 2 bullet 3. 9791 } 9792 9793 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9794 // as combined with the resolution to CWG issue 243. 9795 // 9796 // When the context is initialization by constructor ([over.match.ctor] or 9797 // either phase of [over.match.list]), a constructor is preferred over 9798 // a conversion function. 9799 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9800 Cand1.Function && Cand2.Function && 9801 isa<CXXConstructorDecl>(Cand1.Function) != 9802 isa<CXXConstructorDecl>(Cand2.Function)) 9803 return isa<CXXConstructorDecl>(Cand1.Function); 9804 9805 // -- F1 is a non-template function and F2 is a function template 9806 // specialization, or, if not that, 9807 bool Cand1IsSpecialization = Cand1.Function && 9808 Cand1.Function->getPrimaryTemplate(); 9809 bool Cand2IsSpecialization = Cand2.Function && 9810 Cand2.Function->getPrimaryTemplate(); 9811 if (Cand1IsSpecialization != Cand2IsSpecialization) 9812 return Cand2IsSpecialization; 9813 9814 // -- F1 and F2 are function template specializations, and the function 9815 // template for F1 is more specialized than the template for F2 9816 // according to the partial ordering rules described in 14.5.5.2, or, 9817 // if not that, 9818 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9819 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9820 Cand1.Function->getPrimaryTemplate(), 9821 Cand2.Function->getPrimaryTemplate(), Loc, 9822 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9823 : TPOC_Call, 9824 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9825 Cand1.isReversed() ^ Cand2.isReversed())) 9826 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9827 } 9828 9829 // -— F1 and F2 are non-template functions with the same 9830 // parameter-type-lists, and F1 is more constrained than F2 [...], 9831 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9832 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9833 Cand2.Function->hasPrototype()) { 9834 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9835 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9836 if (PT1->getNumParams() == PT2->getNumParams() && 9837 PT1->isVariadic() == PT2->isVariadic() && 9838 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9839 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9840 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9841 if (RC1 && RC2) { 9842 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9843 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9844 {RC2}, AtLeastAsConstrained1) || 9845 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9846 {RC1}, AtLeastAsConstrained2)) 9847 return false; 9848 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9849 return AtLeastAsConstrained1; 9850 } else if (RC1 || RC2) { 9851 return RC1 != nullptr; 9852 } 9853 } 9854 } 9855 9856 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9857 // class B of D, and for all arguments the corresponding parameters of 9858 // F1 and F2 have the same type. 9859 // FIXME: Implement the "all parameters have the same type" check. 9860 bool Cand1IsInherited = 9861 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9862 bool Cand2IsInherited = 9863 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9864 if (Cand1IsInherited != Cand2IsInherited) 9865 return Cand2IsInherited; 9866 else if (Cand1IsInherited) { 9867 assert(Cand2IsInherited); 9868 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9869 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9870 if (Cand1Class->isDerivedFrom(Cand2Class)) 9871 return true; 9872 if (Cand2Class->isDerivedFrom(Cand1Class)) 9873 return false; 9874 // Inherited from sibling base classes: still ambiguous. 9875 } 9876 9877 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9878 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9879 // with reversed order of parameters and F1 is not 9880 // 9881 // We rank reversed + different operator as worse than just reversed, but 9882 // that comparison can never happen, because we only consider reversing for 9883 // the maximally-rewritten operator (== or <=>). 9884 if (Cand1.RewriteKind != Cand2.RewriteKind) 9885 return Cand1.RewriteKind < Cand2.RewriteKind; 9886 9887 // Check C++17 tie-breakers for deduction guides. 9888 { 9889 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9890 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9891 if (Guide1 && Guide2) { 9892 // -- F1 is generated from a deduction-guide and F2 is not 9893 if (Guide1->isImplicit() != Guide2->isImplicit()) 9894 return Guide2->isImplicit(); 9895 9896 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9897 if (Guide1->isCopyDeductionCandidate()) 9898 return true; 9899 } 9900 } 9901 9902 // Check for enable_if value-based overload resolution. 9903 if (Cand1.Function && Cand2.Function) { 9904 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9905 if (Cmp != Comparison::Equal) 9906 return Cmp == Comparison::Better; 9907 } 9908 9909 bool HasPS1 = Cand1.Function != nullptr && 9910 functionHasPassObjectSizeParams(Cand1.Function); 9911 bool HasPS2 = Cand2.Function != nullptr && 9912 functionHasPassObjectSizeParams(Cand2.Function); 9913 if (HasPS1 != HasPS2 && HasPS1) 9914 return true; 9915 9916 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9917 if (MV == Comparison::Better) 9918 return true; 9919 if (MV == Comparison::Worse) 9920 return false; 9921 9922 // If other rules cannot determine which is better, CUDA preference is used 9923 // to determine which is better. 9924 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9925 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9926 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9927 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9928 } 9929 9930 // General member function overloading is handled above, so this only handles 9931 // constructors with address spaces. 9932 // This only handles address spaces since C++ has no other 9933 // qualifier that can be used with constructors. 9934 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 9935 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 9936 if (CD1 && CD2) { 9937 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 9938 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 9939 if (AS1 != AS2) { 9940 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 9941 return true; 9942 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 9943 return false; 9944 } 9945 } 9946 9947 return false; 9948 } 9949 9950 /// Determine whether two declarations are "equivalent" for the purposes of 9951 /// name lookup and overload resolution. This applies when the same internal/no 9952 /// linkage entity is defined by two modules (probably by textually including 9953 /// the same header). In such a case, we don't consider the declarations to 9954 /// declare the same entity, but we also don't want lookups with both 9955 /// declarations visible to be ambiguous in some cases (this happens when using 9956 /// a modularized libstdc++). 9957 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9958 const NamedDecl *B) { 9959 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9960 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9961 if (!VA || !VB) 9962 return false; 9963 9964 // The declarations must be declaring the same name as an internal linkage 9965 // entity in different modules. 9966 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9967 VB->getDeclContext()->getRedeclContext()) || 9968 getOwningModule(VA) == getOwningModule(VB) || 9969 VA->isExternallyVisible() || VB->isExternallyVisible()) 9970 return false; 9971 9972 // Check that the declarations appear to be equivalent. 9973 // 9974 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9975 // For constants and functions, we should check the initializer or body is 9976 // the same. For non-constant variables, we shouldn't allow it at all. 9977 if (Context.hasSameType(VA->getType(), VB->getType())) 9978 return true; 9979 9980 // Enum constants within unnamed enumerations will have different types, but 9981 // may still be similar enough to be interchangeable for our purposes. 9982 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9983 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9984 // Only handle anonymous enums. If the enumerations were named and 9985 // equivalent, they would have been merged to the same type. 9986 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9987 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9988 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9989 !Context.hasSameType(EnumA->getIntegerType(), 9990 EnumB->getIntegerType())) 9991 return false; 9992 // Allow this only if the value is the same for both enumerators. 9993 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9994 } 9995 } 9996 9997 // Nothing else is sufficiently similar. 9998 return false; 9999 } 10000 10001 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10002 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10003 assert(D && "Unknown declaration"); 10004 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10005 10006 Module *M = getOwningModule(D); 10007 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10008 << !M << (M ? M->getFullModuleName() : ""); 10009 10010 for (auto *E : Equiv) { 10011 Module *M = getOwningModule(E); 10012 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10013 << !M << (M ? M->getFullModuleName() : ""); 10014 } 10015 } 10016 10017 /// Computes the best viable function (C++ 13.3.3) 10018 /// within an overload candidate set. 10019 /// 10020 /// \param Loc The location of the function name (or operator symbol) for 10021 /// which overload resolution occurs. 10022 /// 10023 /// \param Best If overload resolution was successful or found a deleted 10024 /// function, \p Best points to the candidate function found. 10025 /// 10026 /// \returns The result of overload resolution. 10027 OverloadingResult 10028 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10029 iterator &Best) { 10030 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10031 std::transform(begin(), end(), std::back_inserter(Candidates), 10032 [](OverloadCandidate &Cand) { return &Cand; }); 10033 10034 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10035 // are accepted by both clang and NVCC. However, during a particular 10036 // compilation mode only one call variant is viable. We need to 10037 // exclude non-viable overload candidates from consideration based 10038 // only on their host/device attributes. Specifically, if one 10039 // candidate call is WrongSide and the other is SameSide, we ignore 10040 // the WrongSide candidate. 10041 // We only need to remove wrong-sided candidates here if 10042 // -fgpu-exclude-wrong-side-overloads is off. When 10043 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10044 // uniformly in isBetterOverloadCandidate. 10045 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10046 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 10047 bool ContainsSameSideCandidate = 10048 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10049 // Check viable function only. 10050 return Cand->Viable && Cand->Function && 10051 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10052 Sema::CFP_SameSide; 10053 }); 10054 if (ContainsSameSideCandidate) { 10055 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10056 // Check viable function only to avoid unnecessary data copying/moving. 10057 return Cand->Viable && Cand->Function && 10058 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10059 Sema::CFP_WrongSide; 10060 }; 10061 llvm::erase_if(Candidates, IsWrongSideCandidate); 10062 } 10063 } 10064 10065 // Find the best viable function. 10066 Best = end(); 10067 for (auto *Cand : Candidates) { 10068 Cand->Best = false; 10069 if (Cand->Viable) 10070 if (Best == end() || 10071 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10072 Best = Cand; 10073 } 10074 10075 // If we didn't find any viable functions, abort. 10076 if (Best == end()) 10077 return OR_No_Viable_Function; 10078 10079 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10080 10081 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10082 PendingBest.push_back(&*Best); 10083 Best->Best = true; 10084 10085 // Make sure that this function is better than every other viable 10086 // function. If not, we have an ambiguity. 10087 while (!PendingBest.empty()) { 10088 auto *Curr = PendingBest.pop_back_val(); 10089 for (auto *Cand : Candidates) { 10090 if (Cand->Viable && !Cand->Best && 10091 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10092 PendingBest.push_back(Cand); 10093 Cand->Best = true; 10094 10095 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10096 Curr->Function)) 10097 EquivalentCands.push_back(Cand->Function); 10098 else 10099 Best = end(); 10100 } 10101 } 10102 } 10103 10104 // If we found more than one best candidate, this is ambiguous. 10105 if (Best == end()) 10106 return OR_Ambiguous; 10107 10108 // Best is the best viable function. 10109 if (Best->Function && Best->Function->isDeleted()) 10110 return OR_Deleted; 10111 10112 if (!EquivalentCands.empty()) 10113 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10114 EquivalentCands); 10115 10116 return OR_Success; 10117 } 10118 10119 namespace { 10120 10121 enum OverloadCandidateKind { 10122 oc_function, 10123 oc_method, 10124 oc_reversed_binary_operator, 10125 oc_constructor, 10126 oc_implicit_default_constructor, 10127 oc_implicit_copy_constructor, 10128 oc_implicit_move_constructor, 10129 oc_implicit_copy_assignment, 10130 oc_implicit_move_assignment, 10131 oc_implicit_equality_comparison, 10132 oc_inherited_constructor 10133 }; 10134 10135 enum OverloadCandidateSelect { 10136 ocs_non_template, 10137 ocs_template, 10138 ocs_described_template, 10139 }; 10140 10141 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10142 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10143 OverloadCandidateRewriteKind CRK, 10144 std::string &Description) { 10145 10146 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10147 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10148 isTemplate = true; 10149 Description = S.getTemplateArgumentBindingsText( 10150 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10151 } 10152 10153 OverloadCandidateSelect Select = [&]() { 10154 if (!Description.empty()) 10155 return ocs_described_template; 10156 return isTemplate ? ocs_template : ocs_non_template; 10157 }(); 10158 10159 OverloadCandidateKind Kind = [&]() { 10160 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10161 return oc_implicit_equality_comparison; 10162 10163 if (CRK & CRK_Reversed) 10164 return oc_reversed_binary_operator; 10165 10166 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10167 if (!Ctor->isImplicit()) { 10168 if (isa<ConstructorUsingShadowDecl>(Found)) 10169 return oc_inherited_constructor; 10170 else 10171 return oc_constructor; 10172 } 10173 10174 if (Ctor->isDefaultConstructor()) 10175 return oc_implicit_default_constructor; 10176 10177 if (Ctor->isMoveConstructor()) 10178 return oc_implicit_move_constructor; 10179 10180 assert(Ctor->isCopyConstructor() && 10181 "unexpected sort of implicit constructor"); 10182 return oc_implicit_copy_constructor; 10183 } 10184 10185 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10186 // This actually gets spelled 'candidate function' for now, but 10187 // it doesn't hurt to split it out. 10188 if (!Meth->isImplicit()) 10189 return oc_method; 10190 10191 if (Meth->isMoveAssignmentOperator()) 10192 return oc_implicit_move_assignment; 10193 10194 if (Meth->isCopyAssignmentOperator()) 10195 return oc_implicit_copy_assignment; 10196 10197 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10198 return oc_method; 10199 } 10200 10201 return oc_function; 10202 }(); 10203 10204 return std::make_pair(Kind, Select); 10205 } 10206 10207 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10208 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10209 // set. 10210 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10211 S.Diag(FoundDecl->getLocation(), 10212 diag::note_ovl_candidate_inherited_constructor) 10213 << Shadow->getNominatedBaseClass(); 10214 } 10215 10216 } // end anonymous namespace 10217 10218 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10219 const FunctionDecl *FD) { 10220 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10221 bool AlwaysTrue; 10222 if (EnableIf->getCond()->isValueDependent() || 10223 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10224 return false; 10225 if (!AlwaysTrue) 10226 return false; 10227 } 10228 return true; 10229 } 10230 10231 /// Returns true if we can take the address of the function. 10232 /// 10233 /// \param Complain - If true, we'll emit a diagnostic 10234 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10235 /// we in overload resolution? 10236 /// \param Loc - The location of the statement we're complaining about. Ignored 10237 /// if we're not complaining, or if we're in overload resolution. 10238 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10239 bool Complain, 10240 bool InOverloadResolution, 10241 SourceLocation Loc) { 10242 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10243 if (Complain) { 10244 if (InOverloadResolution) 10245 S.Diag(FD->getBeginLoc(), 10246 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10247 else 10248 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10249 } 10250 return false; 10251 } 10252 10253 if (FD->getTrailingRequiresClause()) { 10254 ConstraintSatisfaction Satisfaction; 10255 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10256 return false; 10257 if (!Satisfaction.IsSatisfied) { 10258 if (Complain) { 10259 if (InOverloadResolution) { 10260 SmallString<128> TemplateArgString; 10261 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 10262 TemplateArgString += " "; 10263 TemplateArgString += S.getTemplateArgumentBindingsText( 10264 FunTmpl->getTemplateParameters(), 10265 *FD->getTemplateSpecializationArgs()); 10266 } 10267 10268 S.Diag(FD->getBeginLoc(), 10269 diag::note_ovl_candidate_unsatisfied_constraints) 10270 << TemplateArgString; 10271 } else 10272 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10273 << FD; 10274 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10275 } 10276 return false; 10277 } 10278 } 10279 10280 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10281 return P->hasAttr<PassObjectSizeAttr>(); 10282 }); 10283 if (I == FD->param_end()) 10284 return true; 10285 10286 if (Complain) { 10287 // Add one to ParamNo because it's user-facing 10288 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10289 if (InOverloadResolution) 10290 S.Diag(FD->getLocation(), 10291 diag::note_ovl_candidate_has_pass_object_size_params) 10292 << ParamNo; 10293 else 10294 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10295 << FD << ParamNo; 10296 } 10297 return false; 10298 } 10299 10300 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10301 const FunctionDecl *FD) { 10302 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10303 /*InOverloadResolution=*/true, 10304 /*Loc=*/SourceLocation()); 10305 } 10306 10307 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10308 bool Complain, 10309 SourceLocation Loc) { 10310 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10311 /*InOverloadResolution=*/false, 10312 Loc); 10313 } 10314 10315 // Don't print candidates other than the one that matches the calling 10316 // convention of the call operator, since that is guaranteed to exist. 10317 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10318 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10319 10320 if (!ConvD) 10321 return false; 10322 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10323 if (!RD->isLambda()) 10324 return false; 10325 10326 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10327 CallingConv CallOpCC = 10328 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10329 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10330 CallingConv ConvToCC = 10331 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10332 10333 return ConvToCC != CallOpCC; 10334 } 10335 10336 // Notes the location of an overload candidate. 10337 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10338 OverloadCandidateRewriteKind RewriteKind, 10339 QualType DestType, bool TakingAddress) { 10340 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10341 return; 10342 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10343 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10344 return; 10345 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10346 return; 10347 10348 std::string FnDesc; 10349 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10350 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10351 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10352 << (unsigned)KSPair.first << (unsigned)KSPair.second 10353 << Fn << FnDesc; 10354 10355 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10356 Diag(Fn->getLocation(), PD); 10357 MaybeEmitInheritedConstructorNote(*this, Found); 10358 } 10359 10360 static void 10361 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10362 // Perhaps the ambiguity was caused by two atomic constraints that are 10363 // 'identical' but not equivalent: 10364 // 10365 // void foo() requires (sizeof(T) > 4) { } // #1 10366 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10367 // 10368 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10369 // #2 to subsume #1, but these constraint are not considered equivalent 10370 // according to the subsumption rules because they are not the same 10371 // source-level construct. This behavior is quite confusing and we should try 10372 // to help the user figure out what happened. 10373 10374 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10375 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10376 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10377 if (!I->Function) 10378 continue; 10379 SmallVector<const Expr *, 3> AC; 10380 if (auto *Template = I->Function->getPrimaryTemplate()) 10381 Template->getAssociatedConstraints(AC); 10382 else 10383 I->Function->getAssociatedConstraints(AC); 10384 if (AC.empty()) 10385 continue; 10386 if (FirstCand == nullptr) { 10387 FirstCand = I->Function; 10388 FirstAC = AC; 10389 } else if (SecondCand == nullptr) { 10390 SecondCand = I->Function; 10391 SecondAC = AC; 10392 } else { 10393 // We have more than one pair of constrained functions - this check is 10394 // expensive and we'd rather not try to diagnose it. 10395 return; 10396 } 10397 } 10398 if (!SecondCand) 10399 return; 10400 // The diagnostic can only happen if there are associated constraints on 10401 // both sides (there needs to be some identical atomic constraint). 10402 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10403 SecondCand, SecondAC)) 10404 // Just show the user one diagnostic, they'll probably figure it out 10405 // from here. 10406 return; 10407 } 10408 10409 // Notes the location of all overload candidates designated through 10410 // OverloadedExpr 10411 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10412 bool TakingAddress) { 10413 assert(OverloadedExpr->getType() == Context.OverloadTy); 10414 10415 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10416 OverloadExpr *OvlExpr = Ovl.Expression; 10417 10418 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10419 IEnd = OvlExpr->decls_end(); 10420 I != IEnd; ++I) { 10421 if (FunctionTemplateDecl *FunTmpl = 10422 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10423 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10424 TakingAddress); 10425 } else if (FunctionDecl *Fun 10426 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10427 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10428 } 10429 } 10430 } 10431 10432 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10433 /// "lead" diagnostic; it will be given two arguments, the source and 10434 /// target types of the conversion. 10435 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10436 Sema &S, 10437 SourceLocation CaretLoc, 10438 const PartialDiagnostic &PDiag) const { 10439 S.Diag(CaretLoc, PDiag) 10440 << Ambiguous.getFromType() << Ambiguous.getToType(); 10441 unsigned CandsShown = 0; 10442 AmbiguousConversionSequence::const_iterator I, E; 10443 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10444 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10445 break; 10446 ++CandsShown; 10447 S.NoteOverloadCandidate(I->first, I->second); 10448 } 10449 S.Diags.overloadCandidatesShown(CandsShown); 10450 if (I != E) 10451 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10452 } 10453 10454 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10455 unsigned I, bool TakingCandidateAddress) { 10456 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10457 assert(Conv.isBad()); 10458 assert(Cand->Function && "for now, candidate must be a function"); 10459 FunctionDecl *Fn = Cand->Function; 10460 10461 // There's a conversion slot for the object argument if this is a 10462 // non-constructor method. Note that 'I' corresponds the 10463 // conversion-slot index. 10464 bool isObjectArgument = false; 10465 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10466 if (I == 0) 10467 isObjectArgument = true; 10468 else 10469 I--; 10470 } 10471 10472 std::string FnDesc; 10473 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10474 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10475 FnDesc); 10476 10477 Expr *FromExpr = Conv.Bad.FromExpr; 10478 QualType FromTy = Conv.Bad.getFromType(); 10479 QualType ToTy = Conv.Bad.getToType(); 10480 10481 if (FromTy == S.Context.OverloadTy) { 10482 assert(FromExpr && "overload set argument came from implicit argument?"); 10483 Expr *E = FromExpr->IgnoreParens(); 10484 if (isa<UnaryOperator>(E)) 10485 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10486 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10487 10488 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10489 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10490 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10491 << Name << I + 1; 10492 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10493 return; 10494 } 10495 10496 // Do some hand-waving analysis to see if the non-viability is due 10497 // to a qualifier mismatch. 10498 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10499 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10500 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10501 CToTy = RT->getPointeeType(); 10502 else { 10503 // TODO: detect and diagnose the full richness of const mismatches. 10504 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10505 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10506 CFromTy = FromPT->getPointeeType(); 10507 CToTy = ToPT->getPointeeType(); 10508 } 10509 } 10510 10511 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10512 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10513 Qualifiers FromQs = CFromTy.getQualifiers(); 10514 Qualifiers ToQs = CToTy.getQualifiers(); 10515 10516 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10517 if (isObjectArgument) 10518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10519 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10520 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10521 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10522 else 10523 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10524 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10525 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10526 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10527 << ToTy->isReferenceType() << I + 1; 10528 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10529 return; 10530 } 10531 10532 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10533 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10534 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10535 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10536 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10537 << (unsigned)isObjectArgument << I + 1; 10538 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10539 return; 10540 } 10541 10542 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10544 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10545 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10546 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10547 << (unsigned)isObjectArgument << I + 1; 10548 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10549 return; 10550 } 10551 10552 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10553 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10554 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10555 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10556 << FromQs.hasUnaligned() << I + 1; 10557 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10558 return; 10559 } 10560 10561 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10562 assert(CVR && "expected qualifiers mismatch"); 10563 10564 if (isObjectArgument) { 10565 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10566 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10567 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10568 << (CVR - 1); 10569 } else { 10570 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10571 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10572 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10573 << (CVR - 1) << I + 1; 10574 } 10575 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10576 return; 10577 } 10578 10579 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10580 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10582 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10583 << (unsigned)isObjectArgument << I + 1 10584 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10585 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10586 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10587 return; 10588 } 10589 10590 // Special diagnostic for failure to convert an initializer list, since 10591 // telling the user that it has type void is not useful. 10592 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10593 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10594 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10595 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10596 << ToTy << (unsigned)isObjectArgument << I + 1 10597 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 10598 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 10599 ? 2 10600 : 0); 10601 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10602 return; 10603 } 10604 10605 // Diagnose references or pointers to incomplete types differently, 10606 // since it's far from impossible that the incompleteness triggered 10607 // the failure. 10608 QualType TempFromTy = FromTy.getNonReferenceType(); 10609 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10610 TempFromTy = PTy->getPointeeType(); 10611 if (TempFromTy->isIncompleteType()) { 10612 // Emit the generic diagnostic and, optionally, add the hints to it. 10613 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10614 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10615 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10616 << ToTy << (unsigned)isObjectArgument << I + 1 10617 << (unsigned)(Cand->Fix.Kind); 10618 10619 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10620 return; 10621 } 10622 10623 // Diagnose base -> derived pointer conversions. 10624 unsigned BaseToDerivedConversion = 0; 10625 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10626 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10627 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10628 FromPtrTy->getPointeeType()) && 10629 !FromPtrTy->getPointeeType()->isIncompleteType() && 10630 !ToPtrTy->getPointeeType()->isIncompleteType() && 10631 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10632 FromPtrTy->getPointeeType())) 10633 BaseToDerivedConversion = 1; 10634 } 10635 } else if (const ObjCObjectPointerType *FromPtrTy 10636 = FromTy->getAs<ObjCObjectPointerType>()) { 10637 if (const ObjCObjectPointerType *ToPtrTy 10638 = ToTy->getAs<ObjCObjectPointerType>()) 10639 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10640 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10641 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10642 FromPtrTy->getPointeeType()) && 10643 FromIface->isSuperClassOf(ToIface)) 10644 BaseToDerivedConversion = 2; 10645 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10646 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10647 !FromTy->isIncompleteType() && 10648 !ToRefTy->getPointeeType()->isIncompleteType() && 10649 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10650 BaseToDerivedConversion = 3; 10651 } 10652 } 10653 10654 if (BaseToDerivedConversion) { 10655 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10656 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10657 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10658 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10659 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10660 return; 10661 } 10662 10663 if (isa<ObjCObjectPointerType>(CFromTy) && 10664 isa<PointerType>(CToTy)) { 10665 Qualifiers FromQs = CFromTy.getQualifiers(); 10666 Qualifiers ToQs = CToTy.getQualifiers(); 10667 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10669 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10670 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10671 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10672 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10673 return; 10674 } 10675 } 10676 10677 if (TakingCandidateAddress && 10678 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10679 return; 10680 10681 // Emit the generic diagnostic and, optionally, add the hints to it. 10682 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10683 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10684 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10685 << ToTy << (unsigned)isObjectArgument << I + 1 10686 << (unsigned)(Cand->Fix.Kind); 10687 10688 // If we can fix the conversion, suggest the FixIts. 10689 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10690 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10691 FDiag << *HI; 10692 S.Diag(Fn->getLocation(), FDiag); 10693 10694 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10695 } 10696 10697 /// Additional arity mismatch diagnosis specific to a function overload 10698 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10699 /// over a candidate in any candidate set. 10700 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10701 unsigned NumArgs) { 10702 FunctionDecl *Fn = Cand->Function; 10703 unsigned MinParams = Fn->getMinRequiredArguments(); 10704 10705 // With invalid overloaded operators, it's possible that we think we 10706 // have an arity mismatch when in fact it looks like we have the 10707 // right number of arguments, because only overloaded operators have 10708 // the weird behavior of overloading member and non-member functions. 10709 // Just don't report anything. 10710 if (Fn->isInvalidDecl() && 10711 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10712 return true; 10713 10714 if (NumArgs < MinParams) { 10715 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10716 (Cand->FailureKind == ovl_fail_bad_deduction && 10717 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10718 } else { 10719 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10720 (Cand->FailureKind == ovl_fail_bad_deduction && 10721 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10722 } 10723 10724 return false; 10725 } 10726 10727 /// General arity mismatch diagnosis over a candidate in a candidate set. 10728 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10729 unsigned NumFormalArgs) { 10730 assert(isa<FunctionDecl>(D) && 10731 "The templated declaration should at least be a function" 10732 " when diagnosing bad template argument deduction due to too many" 10733 " or too few arguments"); 10734 10735 FunctionDecl *Fn = cast<FunctionDecl>(D); 10736 10737 // TODO: treat calls to a missing default constructor as a special case 10738 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10739 unsigned MinParams = Fn->getMinRequiredArguments(); 10740 10741 // at least / at most / exactly 10742 unsigned mode, modeCount; 10743 if (NumFormalArgs < MinParams) { 10744 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10745 FnTy->isTemplateVariadic()) 10746 mode = 0; // "at least" 10747 else 10748 mode = 2; // "exactly" 10749 modeCount = MinParams; 10750 } else { 10751 if (MinParams != FnTy->getNumParams()) 10752 mode = 1; // "at most" 10753 else 10754 mode = 2; // "exactly" 10755 modeCount = FnTy->getNumParams(); 10756 } 10757 10758 std::string Description; 10759 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10760 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10761 10762 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10764 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10765 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10766 else 10767 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10768 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10769 << Description << mode << modeCount << NumFormalArgs; 10770 10771 MaybeEmitInheritedConstructorNote(S, Found); 10772 } 10773 10774 /// Arity mismatch diagnosis specific to a function overload candidate. 10775 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10776 unsigned NumFormalArgs) { 10777 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10778 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10779 } 10780 10781 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10782 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10783 return TD; 10784 llvm_unreachable("Unsupported: Getting the described template declaration" 10785 " for bad deduction diagnosis"); 10786 } 10787 10788 /// Diagnose a failed template-argument deduction. 10789 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10790 DeductionFailureInfo &DeductionFailure, 10791 unsigned NumArgs, 10792 bool TakingCandidateAddress) { 10793 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10794 NamedDecl *ParamD; 10795 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10796 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10797 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10798 switch (DeductionFailure.Result) { 10799 case Sema::TDK_Success: 10800 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10801 10802 case Sema::TDK_Incomplete: { 10803 assert(ParamD && "no parameter found for incomplete deduction result"); 10804 S.Diag(Templated->getLocation(), 10805 diag::note_ovl_candidate_incomplete_deduction) 10806 << ParamD->getDeclName(); 10807 MaybeEmitInheritedConstructorNote(S, Found); 10808 return; 10809 } 10810 10811 case Sema::TDK_IncompletePack: { 10812 assert(ParamD && "no parameter found for incomplete deduction result"); 10813 S.Diag(Templated->getLocation(), 10814 diag::note_ovl_candidate_incomplete_deduction_pack) 10815 << ParamD->getDeclName() 10816 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10817 << *DeductionFailure.getFirstArg(); 10818 MaybeEmitInheritedConstructorNote(S, Found); 10819 return; 10820 } 10821 10822 case Sema::TDK_Underqualified: { 10823 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10824 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10825 10826 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10827 10828 // Param will have been canonicalized, but it should just be a 10829 // qualified version of ParamD, so move the qualifiers to that. 10830 QualifierCollector Qs; 10831 Qs.strip(Param); 10832 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10833 assert(S.Context.hasSameType(Param, NonCanonParam)); 10834 10835 // Arg has also been canonicalized, but there's nothing we can do 10836 // about that. It also doesn't matter as much, because it won't 10837 // have any template parameters in it (because deduction isn't 10838 // done on dependent types). 10839 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10840 10841 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10842 << ParamD->getDeclName() << Arg << NonCanonParam; 10843 MaybeEmitInheritedConstructorNote(S, Found); 10844 return; 10845 } 10846 10847 case Sema::TDK_Inconsistent: { 10848 assert(ParamD && "no parameter found for inconsistent deduction result"); 10849 int which = 0; 10850 if (isa<TemplateTypeParmDecl>(ParamD)) 10851 which = 0; 10852 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10853 // Deduction might have failed because we deduced arguments of two 10854 // different types for a non-type template parameter. 10855 // FIXME: Use a different TDK value for this. 10856 QualType T1 = 10857 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10858 QualType T2 = 10859 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10860 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10861 S.Diag(Templated->getLocation(), 10862 diag::note_ovl_candidate_inconsistent_deduction_types) 10863 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10864 << *DeductionFailure.getSecondArg() << T2; 10865 MaybeEmitInheritedConstructorNote(S, Found); 10866 return; 10867 } 10868 10869 which = 1; 10870 } else { 10871 which = 2; 10872 } 10873 10874 // Tweak the diagnostic if the problem is that we deduced packs of 10875 // different arities. We'll print the actual packs anyway in case that 10876 // includes additional useful information. 10877 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10878 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10879 DeductionFailure.getFirstArg()->pack_size() != 10880 DeductionFailure.getSecondArg()->pack_size()) { 10881 which = 3; 10882 } 10883 10884 S.Diag(Templated->getLocation(), 10885 diag::note_ovl_candidate_inconsistent_deduction) 10886 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10887 << *DeductionFailure.getSecondArg(); 10888 MaybeEmitInheritedConstructorNote(S, Found); 10889 return; 10890 } 10891 10892 case Sema::TDK_InvalidExplicitArguments: 10893 assert(ParamD && "no parameter found for invalid explicit arguments"); 10894 if (ParamD->getDeclName()) 10895 S.Diag(Templated->getLocation(), 10896 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10897 << ParamD->getDeclName(); 10898 else { 10899 int index = 0; 10900 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10901 index = TTP->getIndex(); 10902 else if (NonTypeTemplateParmDecl *NTTP 10903 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10904 index = NTTP->getIndex(); 10905 else 10906 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10907 S.Diag(Templated->getLocation(), 10908 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10909 << (index + 1); 10910 } 10911 MaybeEmitInheritedConstructorNote(S, Found); 10912 return; 10913 10914 case Sema::TDK_ConstraintsNotSatisfied: { 10915 // Format the template argument list into the argument string. 10916 SmallString<128> TemplateArgString; 10917 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10918 TemplateArgString = " "; 10919 TemplateArgString += S.getTemplateArgumentBindingsText( 10920 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10921 if (TemplateArgString.size() == 1) 10922 TemplateArgString.clear(); 10923 S.Diag(Templated->getLocation(), 10924 diag::note_ovl_candidate_unsatisfied_constraints) 10925 << TemplateArgString; 10926 10927 S.DiagnoseUnsatisfiedConstraint( 10928 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10929 return; 10930 } 10931 case Sema::TDK_TooManyArguments: 10932 case Sema::TDK_TooFewArguments: 10933 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10934 return; 10935 10936 case Sema::TDK_InstantiationDepth: 10937 S.Diag(Templated->getLocation(), 10938 diag::note_ovl_candidate_instantiation_depth); 10939 MaybeEmitInheritedConstructorNote(S, Found); 10940 return; 10941 10942 case Sema::TDK_SubstitutionFailure: { 10943 // Format the template argument list into the argument string. 10944 SmallString<128> TemplateArgString; 10945 if (TemplateArgumentList *Args = 10946 DeductionFailure.getTemplateArgumentList()) { 10947 TemplateArgString = " "; 10948 TemplateArgString += S.getTemplateArgumentBindingsText( 10949 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10950 if (TemplateArgString.size() == 1) 10951 TemplateArgString.clear(); 10952 } 10953 10954 // If this candidate was disabled by enable_if, say so. 10955 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10956 if (PDiag && PDiag->second.getDiagID() == 10957 diag::err_typename_nested_not_found_enable_if) { 10958 // FIXME: Use the source range of the condition, and the fully-qualified 10959 // name of the enable_if template. These are both present in PDiag. 10960 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10961 << "'enable_if'" << TemplateArgString; 10962 return; 10963 } 10964 10965 // We found a specific requirement that disabled the enable_if. 10966 if (PDiag && PDiag->second.getDiagID() == 10967 diag::err_typename_nested_not_found_requirement) { 10968 S.Diag(Templated->getLocation(), 10969 diag::note_ovl_candidate_disabled_by_requirement) 10970 << PDiag->second.getStringArg(0) << TemplateArgString; 10971 return; 10972 } 10973 10974 // Format the SFINAE diagnostic into the argument string. 10975 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10976 // formatted message in another diagnostic. 10977 SmallString<128> SFINAEArgString; 10978 SourceRange R; 10979 if (PDiag) { 10980 SFINAEArgString = ": "; 10981 R = SourceRange(PDiag->first, PDiag->first); 10982 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10983 } 10984 10985 S.Diag(Templated->getLocation(), 10986 diag::note_ovl_candidate_substitution_failure) 10987 << TemplateArgString << SFINAEArgString << R; 10988 MaybeEmitInheritedConstructorNote(S, Found); 10989 return; 10990 } 10991 10992 case Sema::TDK_DeducedMismatch: 10993 case Sema::TDK_DeducedMismatchNested: { 10994 // Format the template argument list into the argument string. 10995 SmallString<128> TemplateArgString; 10996 if (TemplateArgumentList *Args = 10997 DeductionFailure.getTemplateArgumentList()) { 10998 TemplateArgString = " "; 10999 TemplateArgString += S.getTemplateArgumentBindingsText( 11000 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11001 if (TemplateArgString.size() == 1) 11002 TemplateArgString.clear(); 11003 } 11004 11005 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11006 << (*DeductionFailure.getCallArgIndex() + 1) 11007 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11008 << TemplateArgString 11009 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11010 break; 11011 } 11012 11013 case Sema::TDK_NonDeducedMismatch: { 11014 // FIXME: Provide a source location to indicate what we couldn't match. 11015 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11016 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11017 if (FirstTA.getKind() == TemplateArgument::Template && 11018 SecondTA.getKind() == TemplateArgument::Template) { 11019 TemplateName FirstTN = FirstTA.getAsTemplate(); 11020 TemplateName SecondTN = SecondTA.getAsTemplate(); 11021 if (FirstTN.getKind() == TemplateName::Template && 11022 SecondTN.getKind() == TemplateName::Template) { 11023 if (FirstTN.getAsTemplateDecl()->getName() == 11024 SecondTN.getAsTemplateDecl()->getName()) { 11025 // FIXME: This fixes a bad diagnostic where both templates are named 11026 // the same. This particular case is a bit difficult since: 11027 // 1) It is passed as a string to the diagnostic printer. 11028 // 2) The diagnostic printer only attempts to find a better 11029 // name for types, not decls. 11030 // Ideally, this should folded into the diagnostic printer. 11031 S.Diag(Templated->getLocation(), 11032 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11033 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11034 return; 11035 } 11036 } 11037 } 11038 11039 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11040 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11041 return; 11042 11043 // FIXME: For generic lambda parameters, check if the function is a lambda 11044 // call operator, and if so, emit a prettier and more informative 11045 // diagnostic that mentions 'auto' and lambda in addition to 11046 // (or instead of?) the canonical template type parameters. 11047 S.Diag(Templated->getLocation(), 11048 diag::note_ovl_candidate_non_deduced_mismatch) 11049 << FirstTA << SecondTA; 11050 return; 11051 } 11052 // TODO: diagnose these individually, then kill off 11053 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11054 case Sema::TDK_MiscellaneousDeductionFailure: 11055 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11056 MaybeEmitInheritedConstructorNote(S, Found); 11057 return; 11058 case Sema::TDK_CUDATargetMismatch: 11059 S.Diag(Templated->getLocation(), 11060 diag::note_cuda_ovl_candidate_target_mismatch); 11061 return; 11062 } 11063 } 11064 11065 /// Diagnose a failed template-argument deduction, for function calls. 11066 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11067 unsigned NumArgs, 11068 bool TakingCandidateAddress) { 11069 unsigned TDK = Cand->DeductionFailure.Result; 11070 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11071 if (CheckArityMismatch(S, Cand, NumArgs)) 11072 return; 11073 } 11074 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11075 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11076 } 11077 11078 /// CUDA: diagnose an invalid call across targets. 11079 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11080 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 11081 FunctionDecl *Callee = Cand->Function; 11082 11083 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11084 CalleeTarget = S.IdentifyCUDATarget(Callee); 11085 11086 std::string FnDesc; 11087 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11088 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11089 Cand->getRewriteKind(), FnDesc); 11090 11091 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11092 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11093 << FnDesc /* Ignored */ 11094 << CalleeTarget << CallerTarget; 11095 11096 // This could be an implicit constructor for which we could not infer the 11097 // target due to a collsion. Diagnose that case. 11098 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11099 if (Meth != nullptr && Meth->isImplicit()) { 11100 CXXRecordDecl *ParentClass = Meth->getParent(); 11101 Sema::CXXSpecialMember CSM; 11102 11103 switch (FnKindPair.first) { 11104 default: 11105 return; 11106 case oc_implicit_default_constructor: 11107 CSM = Sema::CXXDefaultConstructor; 11108 break; 11109 case oc_implicit_copy_constructor: 11110 CSM = Sema::CXXCopyConstructor; 11111 break; 11112 case oc_implicit_move_constructor: 11113 CSM = Sema::CXXMoveConstructor; 11114 break; 11115 case oc_implicit_copy_assignment: 11116 CSM = Sema::CXXCopyAssignment; 11117 break; 11118 case oc_implicit_move_assignment: 11119 CSM = Sema::CXXMoveAssignment; 11120 break; 11121 }; 11122 11123 bool ConstRHS = false; 11124 if (Meth->getNumParams()) { 11125 if (const ReferenceType *RT = 11126 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11127 ConstRHS = RT->getPointeeType().isConstQualified(); 11128 } 11129 } 11130 11131 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11132 /* ConstRHS */ ConstRHS, 11133 /* Diagnose */ true); 11134 } 11135 } 11136 11137 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11138 FunctionDecl *Callee = Cand->Function; 11139 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11140 11141 S.Diag(Callee->getLocation(), 11142 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11143 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11144 } 11145 11146 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11147 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11148 assert(ES.isExplicit() && "not an explicit candidate"); 11149 11150 unsigned Kind; 11151 switch (Cand->Function->getDeclKind()) { 11152 case Decl::Kind::CXXConstructor: 11153 Kind = 0; 11154 break; 11155 case Decl::Kind::CXXConversion: 11156 Kind = 1; 11157 break; 11158 case Decl::Kind::CXXDeductionGuide: 11159 Kind = Cand->Function->isImplicit() ? 0 : 2; 11160 break; 11161 default: 11162 llvm_unreachable("invalid Decl"); 11163 } 11164 11165 // Note the location of the first (in-class) declaration; a redeclaration 11166 // (particularly an out-of-class definition) will typically lack the 11167 // 'explicit' specifier. 11168 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11169 FunctionDecl *First = Cand->Function->getFirstDecl(); 11170 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11171 First = Pattern->getFirstDecl(); 11172 11173 S.Diag(First->getLocation(), 11174 diag::note_ovl_candidate_explicit) 11175 << Kind << (ES.getExpr() ? 1 : 0) 11176 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11177 } 11178 11179 /// Generates a 'note' diagnostic for an overload candidate. We've 11180 /// already generated a primary error at the call site. 11181 /// 11182 /// It really does need to be a single diagnostic with its caret 11183 /// pointed at the candidate declaration. Yes, this creates some 11184 /// major challenges of technical writing. Yes, this makes pointing 11185 /// out problems with specific arguments quite awkward. It's still 11186 /// better than generating twenty screens of text for every failed 11187 /// overload. 11188 /// 11189 /// It would be great to be able to express per-candidate problems 11190 /// more richly for those diagnostic clients that cared, but we'd 11191 /// still have to be just as careful with the default diagnostics. 11192 /// \param CtorDestAS Addr space of object being constructed (for ctor 11193 /// candidates only). 11194 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11195 unsigned NumArgs, 11196 bool TakingCandidateAddress, 11197 LangAS CtorDestAS = LangAS::Default) { 11198 FunctionDecl *Fn = Cand->Function; 11199 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11200 return; 11201 11202 // Note deleted candidates, but only if they're viable. 11203 if (Cand->Viable) { 11204 if (Fn->isDeleted()) { 11205 std::string FnDesc; 11206 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11207 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11208 Cand->getRewriteKind(), FnDesc); 11209 11210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11211 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11212 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11214 return; 11215 } 11216 11217 // We don't really have anything else to say about viable candidates. 11218 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11219 return; 11220 } 11221 11222 switch (Cand->FailureKind) { 11223 case ovl_fail_too_many_arguments: 11224 case ovl_fail_too_few_arguments: 11225 return DiagnoseArityMismatch(S, Cand, NumArgs); 11226 11227 case ovl_fail_bad_deduction: 11228 return DiagnoseBadDeduction(S, Cand, NumArgs, 11229 TakingCandidateAddress); 11230 11231 case ovl_fail_illegal_constructor: { 11232 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11233 << (Fn->getPrimaryTemplate() ? 1 : 0); 11234 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11235 return; 11236 } 11237 11238 case ovl_fail_object_addrspace_mismatch: { 11239 Qualifiers QualsForPrinting; 11240 QualsForPrinting.setAddressSpace(CtorDestAS); 11241 S.Diag(Fn->getLocation(), 11242 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11243 << QualsForPrinting; 11244 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11245 return; 11246 } 11247 11248 case ovl_fail_trivial_conversion: 11249 case ovl_fail_bad_final_conversion: 11250 case ovl_fail_final_conversion_not_exact: 11251 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11252 11253 case ovl_fail_bad_conversion: { 11254 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11255 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11256 if (Cand->Conversions[I].isBad()) 11257 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11258 11259 // FIXME: this currently happens when we're called from SemaInit 11260 // when user-conversion overload fails. Figure out how to handle 11261 // those conditions and diagnose them well. 11262 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11263 } 11264 11265 case ovl_fail_bad_target: 11266 return DiagnoseBadTarget(S, Cand); 11267 11268 case ovl_fail_enable_if: 11269 return DiagnoseFailedEnableIfAttr(S, Cand); 11270 11271 case ovl_fail_explicit: 11272 return DiagnoseFailedExplicitSpec(S, Cand); 11273 11274 case ovl_fail_inhctor_slice: 11275 // It's generally not interesting to note copy/move constructors here. 11276 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11277 return; 11278 S.Diag(Fn->getLocation(), 11279 diag::note_ovl_candidate_inherited_constructor_slice) 11280 << (Fn->getPrimaryTemplate() ? 1 : 0) 11281 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11282 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11283 return; 11284 11285 case ovl_fail_addr_not_available: { 11286 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11287 (void)Available; 11288 assert(!Available); 11289 break; 11290 } 11291 case ovl_non_default_multiversion_function: 11292 // Do nothing, these should simply be ignored. 11293 break; 11294 11295 case ovl_fail_constraints_not_satisfied: { 11296 std::string FnDesc; 11297 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11298 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11299 Cand->getRewriteKind(), FnDesc); 11300 11301 S.Diag(Fn->getLocation(), 11302 diag::note_ovl_candidate_constraints_not_satisfied) 11303 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11304 << FnDesc /* Ignored */; 11305 ConstraintSatisfaction Satisfaction; 11306 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11307 break; 11308 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11309 } 11310 } 11311 } 11312 11313 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11314 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11315 return; 11316 11317 // Desugar the type of the surrogate down to a function type, 11318 // retaining as many typedefs as possible while still showing 11319 // the function type (and, therefore, its parameter types). 11320 QualType FnType = Cand->Surrogate->getConversionType(); 11321 bool isLValueReference = false; 11322 bool isRValueReference = false; 11323 bool isPointer = false; 11324 if (const LValueReferenceType *FnTypeRef = 11325 FnType->getAs<LValueReferenceType>()) { 11326 FnType = FnTypeRef->getPointeeType(); 11327 isLValueReference = true; 11328 } else if (const RValueReferenceType *FnTypeRef = 11329 FnType->getAs<RValueReferenceType>()) { 11330 FnType = FnTypeRef->getPointeeType(); 11331 isRValueReference = true; 11332 } 11333 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11334 FnType = FnTypePtr->getPointeeType(); 11335 isPointer = true; 11336 } 11337 // Desugar down to a function type. 11338 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11339 // Reconstruct the pointer/reference as appropriate. 11340 if (isPointer) FnType = S.Context.getPointerType(FnType); 11341 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11342 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11343 11344 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11345 << FnType; 11346 } 11347 11348 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11349 SourceLocation OpLoc, 11350 OverloadCandidate *Cand) { 11351 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11352 std::string TypeStr("operator"); 11353 TypeStr += Opc; 11354 TypeStr += "("; 11355 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11356 if (Cand->Conversions.size() == 1) { 11357 TypeStr += ")"; 11358 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11359 } else { 11360 TypeStr += ", "; 11361 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11362 TypeStr += ")"; 11363 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11364 } 11365 } 11366 11367 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11368 OverloadCandidate *Cand) { 11369 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11370 if (ICS.isBad()) break; // all meaningless after first invalid 11371 if (!ICS.isAmbiguous()) continue; 11372 11373 ICS.DiagnoseAmbiguousConversion( 11374 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11375 } 11376 } 11377 11378 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11379 if (Cand->Function) 11380 return Cand->Function->getLocation(); 11381 if (Cand->IsSurrogate) 11382 return Cand->Surrogate->getLocation(); 11383 return SourceLocation(); 11384 } 11385 11386 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11387 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11388 case Sema::TDK_Success: 11389 case Sema::TDK_NonDependentConversionFailure: 11390 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11391 11392 case Sema::TDK_Invalid: 11393 case Sema::TDK_Incomplete: 11394 case Sema::TDK_IncompletePack: 11395 return 1; 11396 11397 case Sema::TDK_Underqualified: 11398 case Sema::TDK_Inconsistent: 11399 return 2; 11400 11401 case Sema::TDK_SubstitutionFailure: 11402 case Sema::TDK_DeducedMismatch: 11403 case Sema::TDK_ConstraintsNotSatisfied: 11404 case Sema::TDK_DeducedMismatchNested: 11405 case Sema::TDK_NonDeducedMismatch: 11406 case Sema::TDK_MiscellaneousDeductionFailure: 11407 case Sema::TDK_CUDATargetMismatch: 11408 return 3; 11409 11410 case Sema::TDK_InstantiationDepth: 11411 return 4; 11412 11413 case Sema::TDK_InvalidExplicitArguments: 11414 return 5; 11415 11416 case Sema::TDK_TooManyArguments: 11417 case Sema::TDK_TooFewArguments: 11418 return 6; 11419 } 11420 llvm_unreachable("Unhandled deduction result"); 11421 } 11422 11423 namespace { 11424 struct CompareOverloadCandidatesForDisplay { 11425 Sema &S; 11426 SourceLocation Loc; 11427 size_t NumArgs; 11428 OverloadCandidateSet::CandidateSetKind CSK; 11429 11430 CompareOverloadCandidatesForDisplay( 11431 Sema &S, SourceLocation Loc, size_t NArgs, 11432 OverloadCandidateSet::CandidateSetKind CSK) 11433 : S(S), NumArgs(NArgs), CSK(CSK) {} 11434 11435 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11436 // If there are too many or too few arguments, that's the high-order bit we 11437 // want to sort by, even if the immediate failure kind was something else. 11438 if (C->FailureKind == ovl_fail_too_many_arguments || 11439 C->FailureKind == ovl_fail_too_few_arguments) 11440 return static_cast<OverloadFailureKind>(C->FailureKind); 11441 11442 if (C->Function) { 11443 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11444 return ovl_fail_too_many_arguments; 11445 if (NumArgs < C->Function->getMinRequiredArguments()) 11446 return ovl_fail_too_few_arguments; 11447 } 11448 11449 return static_cast<OverloadFailureKind>(C->FailureKind); 11450 } 11451 11452 bool operator()(const OverloadCandidate *L, 11453 const OverloadCandidate *R) { 11454 // Fast-path this check. 11455 if (L == R) return false; 11456 11457 // Order first by viability. 11458 if (L->Viable) { 11459 if (!R->Viable) return true; 11460 11461 // TODO: introduce a tri-valued comparison for overload 11462 // candidates. Would be more worthwhile if we had a sort 11463 // that could exploit it. 11464 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11465 return true; 11466 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11467 return false; 11468 } else if (R->Viable) 11469 return false; 11470 11471 assert(L->Viable == R->Viable); 11472 11473 // Criteria by which we can sort non-viable candidates: 11474 if (!L->Viable) { 11475 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11476 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11477 11478 // 1. Arity mismatches come after other candidates. 11479 if (LFailureKind == ovl_fail_too_many_arguments || 11480 LFailureKind == ovl_fail_too_few_arguments) { 11481 if (RFailureKind == ovl_fail_too_many_arguments || 11482 RFailureKind == ovl_fail_too_few_arguments) { 11483 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11484 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11485 if (LDist == RDist) { 11486 if (LFailureKind == RFailureKind) 11487 // Sort non-surrogates before surrogates. 11488 return !L->IsSurrogate && R->IsSurrogate; 11489 // Sort candidates requiring fewer parameters than there were 11490 // arguments given after candidates requiring more parameters 11491 // than there were arguments given. 11492 return LFailureKind == ovl_fail_too_many_arguments; 11493 } 11494 return LDist < RDist; 11495 } 11496 return false; 11497 } 11498 if (RFailureKind == ovl_fail_too_many_arguments || 11499 RFailureKind == ovl_fail_too_few_arguments) 11500 return true; 11501 11502 // 2. Bad conversions come first and are ordered by the number 11503 // of bad conversions and quality of good conversions. 11504 if (LFailureKind == ovl_fail_bad_conversion) { 11505 if (RFailureKind != ovl_fail_bad_conversion) 11506 return true; 11507 11508 // The conversion that can be fixed with a smaller number of changes, 11509 // comes first. 11510 unsigned numLFixes = L->Fix.NumConversionsFixed; 11511 unsigned numRFixes = R->Fix.NumConversionsFixed; 11512 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11513 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11514 if (numLFixes != numRFixes) { 11515 return numLFixes < numRFixes; 11516 } 11517 11518 // If there's any ordering between the defined conversions... 11519 // FIXME: this might not be transitive. 11520 assert(L->Conversions.size() == R->Conversions.size()); 11521 11522 int leftBetter = 0; 11523 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11524 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11525 switch (CompareImplicitConversionSequences(S, Loc, 11526 L->Conversions[I], 11527 R->Conversions[I])) { 11528 case ImplicitConversionSequence::Better: 11529 leftBetter++; 11530 break; 11531 11532 case ImplicitConversionSequence::Worse: 11533 leftBetter--; 11534 break; 11535 11536 case ImplicitConversionSequence::Indistinguishable: 11537 break; 11538 } 11539 } 11540 if (leftBetter > 0) return true; 11541 if (leftBetter < 0) return false; 11542 11543 } else if (RFailureKind == ovl_fail_bad_conversion) 11544 return false; 11545 11546 if (LFailureKind == ovl_fail_bad_deduction) { 11547 if (RFailureKind != ovl_fail_bad_deduction) 11548 return true; 11549 11550 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11551 return RankDeductionFailure(L->DeductionFailure) 11552 < RankDeductionFailure(R->DeductionFailure); 11553 } else if (RFailureKind == ovl_fail_bad_deduction) 11554 return false; 11555 11556 // TODO: others? 11557 } 11558 11559 // Sort everything else by location. 11560 SourceLocation LLoc = GetLocationForCandidate(L); 11561 SourceLocation RLoc = GetLocationForCandidate(R); 11562 11563 // Put candidates without locations (e.g. builtins) at the end. 11564 if (LLoc.isInvalid()) return false; 11565 if (RLoc.isInvalid()) return true; 11566 11567 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11568 } 11569 }; 11570 } 11571 11572 /// CompleteNonViableCandidate - Normally, overload resolution only 11573 /// computes up to the first bad conversion. Produces the FixIt set if 11574 /// possible. 11575 static void 11576 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11577 ArrayRef<Expr *> Args, 11578 OverloadCandidateSet::CandidateSetKind CSK) { 11579 assert(!Cand->Viable); 11580 11581 // Don't do anything on failures other than bad conversion. 11582 if (Cand->FailureKind != ovl_fail_bad_conversion) 11583 return; 11584 11585 // We only want the FixIts if all the arguments can be corrected. 11586 bool Unfixable = false; 11587 // Use a implicit copy initialization to check conversion fixes. 11588 Cand->Fix.setConversionChecker(TryCopyInitialization); 11589 11590 // Attempt to fix the bad conversion. 11591 unsigned ConvCount = Cand->Conversions.size(); 11592 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11593 ++ConvIdx) { 11594 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11595 if (Cand->Conversions[ConvIdx].isInitialized() && 11596 Cand->Conversions[ConvIdx].isBad()) { 11597 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11598 break; 11599 } 11600 } 11601 11602 // FIXME: this should probably be preserved from the overload 11603 // operation somehow. 11604 bool SuppressUserConversions = false; 11605 11606 unsigned ConvIdx = 0; 11607 unsigned ArgIdx = 0; 11608 ArrayRef<QualType> ParamTypes; 11609 bool Reversed = Cand->isReversed(); 11610 11611 if (Cand->IsSurrogate) { 11612 QualType ConvType 11613 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11614 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11615 ConvType = ConvPtrType->getPointeeType(); 11616 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11617 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11618 ConvIdx = 1; 11619 } else if (Cand->Function) { 11620 ParamTypes = 11621 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11622 if (isa<CXXMethodDecl>(Cand->Function) && 11623 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11624 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11625 ConvIdx = 1; 11626 if (CSK == OverloadCandidateSet::CSK_Operator && 11627 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 11628 Cand->Function->getDeclName().getCXXOverloadedOperator() != 11629 OO_Subscript) 11630 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11631 ArgIdx = 1; 11632 } 11633 } else { 11634 // Builtin operator. 11635 assert(ConvCount <= 3); 11636 ParamTypes = Cand->BuiltinParamTypes; 11637 } 11638 11639 // Fill in the rest of the conversions. 11640 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11641 ConvIdx != ConvCount; 11642 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11643 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11644 if (Cand->Conversions[ConvIdx].isInitialized()) { 11645 // We've already checked this conversion. 11646 } else if (ParamIdx < ParamTypes.size()) { 11647 if (ParamTypes[ParamIdx]->isDependentType()) 11648 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11649 Args[ArgIdx]->getType()); 11650 else { 11651 Cand->Conversions[ConvIdx] = 11652 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11653 SuppressUserConversions, 11654 /*InOverloadResolution=*/true, 11655 /*AllowObjCWritebackConversion=*/ 11656 S.getLangOpts().ObjCAutoRefCount); 11657 // Store the FixIt in the candidate if it exists. 11658 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11659 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11660 } 11661 } else 11662 Cand->Conversions[ConvIdx].setEllipsis(); 11663 } 11664 } 11665 11666 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11667 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11668 SourceLocation OpLoc, 11669 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11670 // Sort the candidates by viability and position. Sorting directly would 11671 // be prohibitive, so we make a set of pointers and sort those. 11672 SmallVector<OverloadCandidate*, 32> Cands; 11673 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11674 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11675 if (!Filter(*Cand)) 11676 continue; 11677 switch (OCD) { 11678 case OCD_AllCandidates: 11679 if (!Cand->Viable) { 11680 if (!Cand->Function && !Cand->IsSurrogate) { 11681 // This a non-viable builtin candidate. We do not, in general, 11682 // want to list every possible builtin candidate. 11683 continue; 11684 } 11685 CompleteNonViableCandidate(S, Cand, Args, Kind); 11686 } 11687 break; 11688 11689 case OCD_ViableCandidates: 11690 if (!Cand->Viable) 11691 continue; 11692 break; 11693 11694 case OCD_AmbiguousCandidates: 11695 if (!Cand->Best) 11696 continue; 11697 break; 11698 } 11699 11700 Cands.push_back(Cand); 11701 } 11702 11703 llvm::stable_sort( 11704 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11705 11706 return Cands; 11707 } 11708 11709 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11710 SourceLocation OpLoc) { 11711 bool DeferHint = false; 11712 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11713 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11714 // host device candidates. 11715 auto WrongSidedCands = 11716 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11717 return (Cand.Viable == false && 11718 Cand.FailureKind == ovl_fail_bad_target) || 11719 (Cand.Function && 11720 Cand.Function->template hasAttr<CUDAHostAttr>() && 11721 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11722 }); 11723 DeferHint = !WrongSidedCands.empty(); 11724 } 11725 return DeferHint; 11726 } 11727 11728 /// When overload resolution fails, prints diagnostic messages containing the 11729 /// candidates in the candidate set. 11730 void OverloadCandidateSet::NoteCandidates( 11731 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11732 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11733 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11734 11735 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11736 11737 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11738 11739 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11740 11741 if (OCD == OCD_AmbiguousCandidates) 11742 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11743 } 11744 11745 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11746 ArrayRef<OverloadCandidate *> Cands, 11747 StringRef Opc, SourceLocation OpLoc) { 11748 bool ReportedAmbiguousConversions = false; 11749 11750 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11751 unsigned CandsShown = 0; 11752 auto I = Cands.begin(), E = Cands.end(); 11753 for (; I != E; ++I) { 11754 OverloadCandidate *Cand = *I; 11755 11756 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11757 ShowOverloads == Ovl_Best) { 11758 break; 11759 } 11760 ++CandsShown; 11761 11762 if (Cand->Function) 11763 NoteFunctionCandidate(S, Cand, Args.size(), 11764 /*TakingCandidateAddress=*/false, DestAS); 11765 else if (Cand->IsSurrogate) 11766 NoteSurrogateCandidate(S, Cand); 11767 else { 11768 assert(Cand->Viable && 11769 "Non-viable built-in candidates are not added to Cands."); 11770 // Generally we only see ambiguities including viable builtin 11771 // operators if overload resolution got screwed up by an 11772 // ambiguous user-defined conversion. 11773 // 11774 // FIXME: It's quite possible for different conversions to see 11775 // different ambiguities, though. 11776 if (!ReportedAmbiguousConversions) { 11777 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11778 ReportedAmbiguousConversions = true; 11779 } 11780 11781 // If this is a viable builtin, print it. 11782 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11783 } 11784 } 11785 11786 // Inform S.Diags that we've shown an overload set with N elements. This may 11787 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11788 S.Diags.overloadCandidatesShown(CandsShown); 11789 11790 if (I != E) 11791 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11792 shouldDeferDiags(S, Args, OpLoc)) 11793 << int(E - I); 11794 } 11795 11796 static SourceLocation 11797 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11798 return Cand->Specialization ? Cand->Specialization->getLocation() 11799 : SourceLocation(); 11800 } 11801 11802 namespace { 11803 struct CompareTemplateSpecCandidatesForDisplay { 11804 Sema &S; 11805 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11806 11807 bool operator()(const TemplateSpecCandidate *L, 11808 const TemplateSpecCandidate *R) { 11809 // Fast-path this check. 11810 if (L == R) 11811 return false; 11812 11813 // Assuming that both candidates are not matches... 11814 11815 // Sort by the ranking of deduction failures. 11816 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11817 return RankDeductionFailure(L->DeductionFailure) < 11818 RankDeductionFailure(R->DeductionFailure); 11819 11820 // Sort everything else by location. 11821 SourceLocation LLoc = GetLocationForCandidate(L); 11822 SourceLocation RLoc = GetLocationForCandidate(R); 11823 11824 // Put candidates without locations (e.g. builtins) at the end. 11825 if (LLoc.isInvalid()) 11826 return false; 11827 if (RLoc.isInvalid()) 11828 return true; 11829 11830 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11831 } 11832 }; 11833 } 11834 11835 /// Diagnose a template argument deduction failure. 11836 /// We are treating these failures as overload failures due to bad 11837 /// deductions. 11838 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11839 bool ForTakingAddress) { 11840 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11841 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11842 } 11843 11844 void TemplateSpecCandidateSet::destroyCandidates() { 11845 for (iterator i = begin(), e = end(); i != e; ++i) { 11846 i->DeductionFailure.Destroy(); 11847 } 11848 } 11849 11850 void TemplateSpecCandidateSet::clear() { 11851 destroyCandidates(); 11852 Candidates.clear(); 11853 } 11854 11855 /// NoteCandidates - When no template specialization match is found, prints 11856 /// diagnostic messages containing the non-matching specializations that form 11857 /// the candidate set. 11858 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11859 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11860 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11861 // Sort the candidates by position (assuming no candidate is a match). 11862 // Sorting directly would be prohibitive, so we make a set of pointers 11863 // and sort those. 11864 SmallVector<TemplateSpecCandidate *, 32> Cands; 11865 Cands.reserve(size()); 11866 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11867 if (Cand->Specialization) 11868 Cands.push_back(Cand); 11869 // Otherwise, this is a non-matching builtin candidate. We do not, 11870 // in general, want to list every possible builtin candidate. 11871 } 11872 11873 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11874 11875 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11876 // for generalization purposes (?). 11877 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11878 11879 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11880 unsigned CandsShown = 0; 11881 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11882 TemplateSpecCandidate *Cand = *I; 11883 11884 // Set an arbitrary limit on the number of candidates we'll spam 11885 // the user with. FIXME: This limit should depend on details of the 11886 // candidate list. 11887 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11888 break; 11889 ++CandsShown; 11890 11891 assert(Cand->Specialization && 11892 "Non-matching built-in candidates are not added to Cands."); 11893 Cand->NoteDeductionFailure(S, ForTakingAddress); 11894 } 11895 11896 if (I != E) 11897 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11898 } 11899 11900 // [PossiblyAFunctionType] --> [Return] 11901 // NonFunctionType --> NonFunctionType 11902 // R (A) --> R(A) 11903 // R (*)(A) --> R (A) 11904 // R (&)(A) --> R (A) 11905 // R (S::*)(A) --> R (A) 11906 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11907 QualType Ret = PossiblyAFunctionType; 11908 if (const PointerType *ToTypePtr = 11909 PossiblyAFunctionType->getAs<PointerType>()) 11910 Ret = ToTypePtr->getPointeeType(); 11911 else if (const ReferenceType *ToTypeRef = 11912 PossiblyAFunctionType->getAs<ReferenceType>()) 11913 Ret = ToTypeRef->getPointeeType(); 11914 else if (const MemberPointerType *MemTypePtr = 11915 PossiblyAFunctionType->getAs<MemberPointerType>()) 11916 Ret = MemTypePtr->getPointeeType(); 11917 Ret = 11918 Context.getCanonicalType(Ret).getUnqualifiedType(); 11919 return Ret; 11920 } 11921 11922 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11923 bool Complain = true) { 11924 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11925 S.DeduceReturnType(FD, Loc, Complain)) 11926 return true; 11927 11928 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11929 if (S.getLangOpts().CPlusPlus17 && 11930 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11931 !S.ResolveExceptionSpec(Loc, FPT)) 11932 return true; 11933 11934 return false; 11935 } 11936 11937 namespace { 11938 // A helper class to help with address of function resolution 11939 // - allows us to avoid passing around all those ugly parameters 11940 class AddressOfFunctionResolver { 11941 Sema& S; 11942 Expr* SourceExpr; 11943 const QualType& TargetType; 11944 QualType TargetFunctionType; // Extracted function type from target type 11945 11946 bool Complain; 11947 //DeclAccessPair& ResultFunctionAccessPair; 11948 ASTContext& Context; 11949 11950 bool TargetTypeIsNonStaticMemberFunction; 11951 bool FoundNonTemplateFunction; 11952 bool StaticMemberFunctionFromBoundPointer; 11953 bool HasComplained; 11954 11955 OverloadExpr::FindResult OvlExprInfo; 11956 OverloadExpr *OvlExpr; 11957 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11958 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11959 TemplateSpecCandidateSet FailedCandidates; 11960 11961 public: 11962 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11963 const QualType &TargetType, bool Complain) 11964 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11965 Complain(Complain), Context(S.getASTContext()), 11966 TargetTypeIsNonStaticMemberFunction( 11967 !!TargetType->getAs<MemberPointerType>()), 11968 FoundNonTemplateFunction(false), 11969 StaticMemberFunctionFromBoundPointer(false), 11970 HasComplained(false), 11971 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11972 OvlExpr(OvlExprInfo.Expression), 11973 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11974 ExtractUnqualifiedFunctionTypeFromTargetType(); 11975 11976 if (TargetFunctionType->isFunctionType()) { 11977 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11978 if (!UME->isImplicitAccess() && 11979 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11980 StaticMemberFunctionFromBoundPointer = true; 11981 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11982 DeclAccessPair dap; 11983 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11984 OvlExpr, false, &dap)) { 11985 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11986 if (!Method->isStatic()) { 11987 // If the target type is a non-function type and the function found 11988 // is a non-static member function, pretend as if that was the 11989 // target, it's the only possible type to end up with. 11990 TargetTypeIsNonStaticMemberFunction = true; 11991 11992 // And skip adding the function if its not in the proper form. 11993 // We'll diagnose this due to an empty set of functions. 11994 if (!OvlExprInfo.HasFormOfMemberPointer) 11995 return; 11996 } 11997 11998 Matches.push_back(std::make_pair(dap, Fn)); 11999 } 12000 return; 12001 } 12002 12003 if (OvlExpr->hasExplicitTemplateArgs()) 12004 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 12005 12006 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 12007 // C++ [over.over]p4: 12008 // If more than one function is selected, [...] 12009 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12010 if (FoundNonTemplateFunction) 12011 EliminateAllTemplateMatches(); 12012 else 12013 EliminateAllExceptMostSpecializedTemplate(); 12014 } 12015 } 12016 12017 if (S.getLangOpts().CUDA && Matches.size() > 1) 12018 EliminateSuboptimalCudaMatches(); 12019 } 12020 12021 bool hasComplained() const { return HasComplained; } 12022 12023 private: 12024 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12025 QualType Discard; 12026 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12027 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12028 } 12029 12030 /// \return true if A is considered a better overload candidate for the 12031 /// desired type than B. 12032 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12033 // If A doesn't have exactly the correct type, we don't want to classify it 12034 // as "better" than anything else. This way, the user is required to 12035 // disambiguate for us if there are multiple candidates and no exact match. 12036 return candidateHasExactlyCorrectType(A) && 12037 (!candidateHasExactlyCorrectType(B) || 12038 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12039 } 12040 12041 /// \return true if we were able to eliminate all but one overload candidate, 12042 /// false otherwise. 12043 bool eliminiateSuboptimalOverloadCandidates() { 12044 // Same algorithm as overload resolution -- one pass to pick the "best", 12045 // another pass to be sure that nothing is better than the best. 12046 auto Best = Matches.begin(); 12047 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12048 if (isBetterCandidate(I->second, Best->second)) 12049 Best = I; 12050 12051 const FunctionDecl *BestFn = Best->second; 12052 auto IsBestOrInferiorToBest = [this, BestFn]( 12053 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12054 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12055 }; 12056 12057 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12058 // option, so we can potentially give the user a better error 12059 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12060 return false; 12061 Matches[0] = *Best; 12062 Matches.resize(1); 12063 return true; 12064 } 12065 12066 bool isTargetTypeAFunction() const { 12067 return TargetFunctionType->isFunctionType(); 12068 } 12069 12070 // [ToType] [Return] 12071 12072 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12073 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12074 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12075 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12076 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12077 } 12078 12079 // return true if any matching specializations were found 12080 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12081 const DeclAccessPair& CurAccessFunPair) { 12082 if (CXXMethodDecl *Method 12083 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12084 // Skip non-static function templates when converting to pointer, and 12085 // static when converting to member pointer. 12086 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12087 return false; 12088 } 12089 else if (TargetTypeIsNonStaticMemberFunction) 12090 return false; 12091 12092 // C++ [over.over]p2: 12093 // If the name is a function template, template argument deduction is 12094 // done (14.8.2.2), and if the argument deduction succeeds, the 12095 // resulting template argument list is used to generate a single 12096 // function template specialization, which is added to the set of 12097 // overloaded functions considered. 12098 FunctionDecl *Specialization = nullptr; 12099 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12100 if (Sema::TemplateDeductionResult Result 12101 = S.DeduceTemplateArguments(FunctionTemplate, 12102 &OvlExplicitTemplateArgs, 12103 TargetFunctionType, Specialization, 12104 Info, /*IsAddressOfFunction*/true)) { 12105 // Make a note of the failed deduction for diagnostics. 12106 FailedCandidates.addCandidate() 12107 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12108 MakeDeductionFailureInfo(Context, Result, Info)); 12109 return false; 12110 } 12111 12112 // Template argument deduction ensures that we have an exact match or 12113 // compatible pointer-to-function arguments that would be adjusted by ICS. 12114 // This function template specicalization works. 12115 assert(S.isSameOrCompatibleFunctionType( 12116 Context.getCanonicalType(Specialization->getType()), 12117 Context.getCanonicalType(TargetFunctionType))); 12118 12119 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12120 return false; 12121 12122 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12123 return true; 12124 } 12125 12126 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12127 const DeclAccessPair& CurAccessFunPair) { 12128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12129 // Skip non-static functions when converting to pointer, and static 12130 // when converting to member pointer. 12131 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12132 return false; 12133 } 12134 else if (TargetTypeIsNonStaticMemberFunction) 12135 return false; 12136 12137 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12138 if (S.getLangOpts().CUDA) 12139 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12140 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12141 return false; 12142 if (FunDecl->isMultiVersion()) { 12143 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12144 if (TA && !TA->isDefaultVersion()) 12145 return false; 12146 } 12147 12148 // If any candidate has a placeholder return type, trigger its deduction 12149 // now. 12150 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12151 Complain)) { 12152 HasComplained |= Complain; 12153 return false; 12154 } 12155 12156 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12157 return false; 12158 12159 // If we're in C, we need to support types that aren't exactly identical. 12160 if (!S.getLangOpts().CPlusPlus || 12161 candidateHasExactlyCorrectType(FunDecl)) { 12162 Matches.push_back(std::make_pair( 12163 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12164 FoundNonTemplateFunction = true; 12165 return true; 12166 } 12167 } 12168 12169 return false; 12170 } 12171 12172 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12173 bool Ret = false; 12174 12175 // If the overload expression doesn't have the form of a pointer to 12176 // member, don't try to convert it to a pointer-to-member type. 12177 if (IsInvalidFormOfPointerToMemberFunction()) 12178 return false; 12179 12180 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12181 E = OvlExpr->decls_end(); 12182 I != E; ++I) { 12183 // Look through any using declarations to find the underlying function. 12184 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12185 12186 // C++ [over.over]p3: 12187 // Non-member functions and static member functions match 12188 // targets of type "pointer-to-function" or "reference-to-function." 12189 // Nonstatic member functions match targets of 12190 // type "pointer-to-member-function." 12191 // Note that according to DR 247, the containing class does not matter. 12192 if (FunctionTemplateDecl *FunctionTemplate 12193 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12194 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12195 Ret = true; 12196 } 12197 // If we have explicit template arguments supplied, skip non-templates. 12198 else if (!OvlExpr->hasExplicitTemplateArgs() && 12199 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12200 Ret = true; 12201 } 12202 assert(Ret || Matches.empty()); 12203 return Ret; 12204 } 12205 12206 void EliminateAllExceptMostSpecializedTemplate() { 12207 // [...] and any given function template specialization F1 is 12208 // eliminated if the set contains a second function template 12209 // specialization whose function template is more specialized 12210 // than the function template of F1 according to the partial 12211 // ordering rules of 14.5.5.2. 12212 12213 // The algorithm specified above is quadratic. We instead use a 12214 // two-pass algorithm (similar to the one used to identify the 12215 // best viable function in an overload set) that identifies the 12216 // best function template (if it exists). 12217 12218 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12219 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12220 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12221 12222 // TODO: It looks like FailedCandidates does not serve much purpose 12223 // here, since the no_viable diagnostic has index 0. 12224 UnresolvedSetIterator Result = S.getMostSpecialized( 12225 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12226 SourceExpr->getBeginLoc(), S.PDiag(), 12227 S.PDiag(diag::err_addr_ovl_ambiguous) 12228 << Matches[0].second->getDeclName(), 12229 S.PDiag(diag::note_ovl_candidate) 12230 << (unsigned)oc_function << (unsigned)ocs_described_template, 12231 Complain, TargetFunctionType); 12232 12233 if (Result != MatchesCopy.end()) { 12234 // Make it the first and only element 12235 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12236 Matches[0].second = cast<FunctionDecl>(*Result); 12237 Matches.resize(1); 12238 } else 12239 HasComplained |= Complain; 12240 } 12241 12242 void EliminateAllTemplateMatches() { 12243 // [...] any function template specializations in the set are 12244 // eliminated if the set also contains a non-template function, [...] 12245 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12246 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12247 ++I; 12248 else { 12249 Matches[I] = Matches[--N]; 12250 Matches.resize(N); 12251 } 12252 } 12253 } 12254 12255 void EliminateSuboptimalCudaMatches() { 12256 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12257 } 12258 12259 public: 12260 void ComplainNoMatchesFound() const { 12261 assert(Matches.empty()); 12262 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12263 << OvlExpr->getName() << TargetFunctionType 12264 << OvlExpr->getSourceRange(); 12265 if (FailedCandidates.empty()) 12266 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12267 /*TakingAddress=*/true); 12268 else { 12269 // We have some deduction failure messages. Use them to diagnose 12270 // the function templates, and diagnose the non-template candidates 12271 // normally. 12272 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12273 IEnd = OvlExpr->decls_end(); 12274 I != IEnd; ++I) 12275 if (FunctionDecl *Fun = 12276 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12277 if (!functionHasPassObjectSizeParams(Fun)) 12278 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12279 /*TakingAddress=*/true); 12280 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12281 } 12282 } 12283 12284 bool IsInvalidFormOfPointerToMemberFunction() const { 12285 return TargetTypeIsNonStaticMemberFunction && 12286 !OvlExprInfo.HasFormOfMemberPointer; 12287 } 12288 12289 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12290 // TODO: Should we condition this on whether any functions might 12291 // have matched, or is it more appropriate to do that in callers? 12292 // TODO: a fixit wouldn't hurt. 12293 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12294 << TargetType << OvlExpr->getSourceRange(); 12295 } 12296 12297 bool IsStaticMemberFunctionFromBoundPointer() const { 12298 return StaticMemberFunctionFromBoundPointer; 12299 } 12300 12301 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12302 S.Diag(OvlExpr->getBeginLoc(), 12303 diag::err_invalid_form_pointer_member_function) 12304 << OvlExpr->getSourceRange(); 12305 } 12306 12307 void ComplainOfInvalidConversion() const { 12308 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12309 << OvlExpr->getName() << TargetType; 12310 } 12311 12312 void ComplainMultipleMatchesFound() const { 12313 assert(Matches.size() > 1); 12314 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12315 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12316 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12317 /*TakingAddress=*/true); 12318 } 12319 12320 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12321 12322 int getNumMatches() const { return Matches.size(); } 12323 12324 FunctionDecl* getMatchingFunctionDecl() const { 12325 if (Matches.size() != 1) return nullptr; 12326 return Matches[0].second; 12327 } 12328 12329 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12330 if (Matches.size() != 1) return nullptr; 12331 return &Matches[0].first; 12332 } 12333 }; 12334 } 12335 12336 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12337 /// an overloaded function (C++ [over.over]), where @p From is an 12338 /// expression with overloaded function type and @p ToType is the type 12339 /// we're trying to resolve to. For example: 12340 /// 12341 /// @code 12342 /// int f(double); 12343 /// int f(int); 12344 /// 12345 /// int (*pfd)(double) = f; // selects f(double) 12346 /// @endcode 12347 /// 12348 /// This routine returns the resulting FunctionDecl if it could be 12349 /// resolved, and NULL otherwise. When @p Complain is true, this 12350 /// routine will emit diagnostics if there is an error. 12351 FunctionDecl * 12352 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12353 QualType TargetType, 12354 bool Complain, 12355 DeclAccessPair &FoundResult, 12356 bool *pHadMultipleCandidates) { 12357 assert(AddressOfExpr->getType() == Context.OverloadTy); 12358 12359 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12360 Complain); 12361 int NumMatches = Resolver.getNumMatches(); 12362 FunctionDecl *Fn = nullptr; 12363 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12364 if (NumMatches == 0 && ShouldComplain) { 12365 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12366 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12367 else 12368 Resolver.ComplainNoMatchesFound(); 12369 } 12370 else if (NumMatches > 1 && ShouldComplain) 12371 Resolver.ComplainMultipleMatchesFound(); 12372 else if (NumMatches == 1) { 12373 Fn = Resolver.getMatchingFunctionDecl(); 12374 assert(Fn); 12375 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12376 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12377 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12378 if (Complain) { 12379 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12380 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12381 else 12382 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12383 } 12384 } 12385 12386 if (pHadMultipleCandidates) 12387 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12388 return Fn; 12389 } 12390 12391 /// Given an expression that refers to an overloaded function, try to 12392 /// resolve that function to a single function that can have its address taken. 12393 /// This will modify `Pair` iff it returns non-null. 12394 /// 12395 /// This routine can only succeed if from all of the candidates in the overload 12396 /// set for SrcExpr that can have their addresses taken, there is one candidate 12397 /// that is more constrained than the rest. 12398 FunctionDecl * 12399 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12400 OverloadExpr::FindResult R = OverloadExpr::find(E); 12401 OverloadExpr *Ovl = R.Expression; 12402 bool IsResultAmbiguous = false; 12403 FunctionDecl *Result = nullptr; 12404 DeclAccessPair DAP; 12405 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12406 12407 auto CheckMoreConstrained = 12408 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12409 SmallVector<const Expr *, 1> AC1, AC2; 12410 FD1->getAssociatedConstraints(AC1); 12411 FD2->getAssociatedConstraints(AC2); 12412 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12413 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12414 return None; 12415 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12416 return None; 12417 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12418 return None; 12419 return AtLeastAsConstrained1; 12420 }; 12421 12422 // Don't use the AddressOfResolver because we're specifically looking for 12423 // cases where we have one overload candidate that lacks 12424 // enable_if/pass_object_size/... 12425 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12426 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12427 if (!FD) 12428 return nullptr; 12429 12430 if (!checkAddressOfFunctionIsAvailable(FD)) 12431 continue; 12432 12433 // We have more than one result - see if it is more constrained than the 12434 // previous one. 12435 if (Result) { 12436 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12437 Result); 12438 if (!MoreConstrainedThanPrevious) { 12439 IsResultAmbiguous = true; 12440 AmbiguousDecls.push_back(FD); 12441 continue; 12442 } 12443 if (!*MoreConstrainedThanPrevious) 12444 continue; 12445 // FD is more constrained - replace Result with it. 12446 } 12447 IsResultAmbiguous = false; 12448 DAP = I.getPair(); 12449 Result = FD; 12450 } 12451 12452 if (IsResultAmbiguous) 12453 return nullptr; 12454 12455 if (Result) { 12456 SmallVector<const Expr *, 1> ResultAC; 12457 // We skipped over some ambiguous declarations which might be ambiguous with 12458 // the selected result. 12459 for (FunctionDecl *Skipped : AmbiguousDecls) 12460 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12461 return nullptr; 12462 Pair = DAP; 12463 } 12464 return Result; 12465 } 12466 12467 /// Given an overloaded function, tries to turn it into a non-overloaded 12468 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12469 /// will perform access checks, diagnose the use of the resultant decl, and, if 12470 /// requested, potentially perform a function-to-pointer decay. 12471 /// 12472 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12473 /// Otherwise, returns true. This may emit diagnostics and return true. 12474 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12475 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12476 Expr *E = SrcExpr.get(); 12477 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12478 12479 DeclAccessPair DAP; 12480 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12481 if (!Found || Found->isCPUDispatchMultiVersion() || 12482 Found->isCPUSpecificMultiVersion()) 12483 return false; 12484 12485 // Emitting multiple diagnostics for a function that is both inaccessible and 12486 // unavailable is consistent with our behavior elsewhere. So, always check 12487 // for both. 12488 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12489 CheckAddressOfMemberAccess(E, DAP); 12490 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12491 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12492 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12493 else 12494 SrcExpr = Fixed; 12495 return true; 12496 } 12497 12498 /// Given an expression that refers to an overloaded function, try to 12499 /// resolve that overloaded function expression down to a single function. 12500 /// 12501 /// This routine can only resolve template-ids that refer to a single function 12502 /// template, where that template-id refers to a single template whose template 12503 /// arguments are either provided by the template-id or have defaults, 12504 /// as described in C++0x [temp.arg.explicit]p3. 12505 /// 12506 /// If no template-ids are found, no diagnostics are emitted and NULL is 12507 /// returned. 12508 FunctionDecl * 12509 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12510 bool Complain, 12511 DeclAccessPair *FoundResult) { 12512 // C++ [over.over]p1: 12513 // [...] [Note: any redundant set of parentheses surrounding the 12514 // overloaded function name is ignored (5.1). ] 12515 // C++ [over.over]p1: 12516 // [...] The overloaded function name can be preceded by the & 12517 // operator. 12518 12519 // If we didn't actually find any template-ids, we're done. 12520 if (!ovl->hasExplicitTemplateArgs()) 12521 return nullptr; 12522 12523 TemplateArgumentListInfo ExplicitTemplateArgs; 12524 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12525 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12526 12527 // Look through all of the overloaded functions, searching for one 12528 // whose type matches exactly. 12529 FunctionDecl *Matched = nullptr; 12530 for (UnresolvedSetIterator I = ovl->decls_begin(), 12531 E = ovl->decls_end(); I != E; ++I) { 12532 // C++0x [temp.arg.explicit]p3: 12533 // [...] In contexts where deduction is done and fails, or in contexts 12534 // where deduction is not done, if a template argument list is 12535 // specified and it, along with any default template arguments, 12536 // identifies a single function template specialization, then the 12537 // template-id is an lvalue for the function template specialization. 12538 FunctionTemplateDecl *FunctionTemplate 12539 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12540 12541 // C++ [over.over]p2: 12542 // If the name is a function template, template argument deduction is 12543 // done (14.8.2.2), and if the argument deduction succeeds, the 12544 // resulting template argument list is used to generate a single 12545 // function template specialization, which is added to the set of 12546 // overloaded functions considered. 12547 FunctionDecl *Specialization = nullptr; 12548 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12549 if (TemplateDeductionResult Result 12550 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12551 Specialization, Info, 12552 /*IsAddressOfFunction*/true)) { 12553 // Make a note of the failed deduction for diagnostics. 12554 // TODO: Actually use the failed-deduction info? 12555 FailedCandidates.addCandidate() 12556 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12557 MakeDeductionFailureInfo(Context, Result, Info)); 12558 continue; 12559 } 12560 12561 assert(Specialization && "no specialization and no error?"); 12562 12563 // Multiple matches; we can't resolve to a single declaration. 12564 if (Matched) { 12565 if (Complain) { 12566 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12567 << ovl->getName(); 12568 NoteAllOverloadCandidates(ovl); 12569 } 12570 return nullptr; 12571 } 12572 12573 Matched = Specialization; 12574 if (FoundResult) *FoundResult = I.getPair(); 12575 } 12576 12577 if (Matched && 12578 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12579 return nullptr; 12580 12581 return Matched; 12582 } 12583 12584 // Resolve and fix an overloaded expression that can be resolved 12585 // because it identifies a single function template specialization. 12586 // 12587 // Last three arguments should only be supplied if Complain = true 12588 // 12589 // Return true if it was logically possible to so resolve the 12590 // expression, regardless of whether or not it succeeded. Always 12591 // returns true if 'complain' is set. 12592 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12593 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12594 bool complain, SourceRange OpRangeForComplaining, 12595 QualType DestTypeForComplaining, 12596 unsigned DiagIDForComplaining) { 12597 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12598 12599 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12600 12601 DeclAccessPair found; 12602 ExprResult SingleFunctionExpression; 12603 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12604 ovl.Expression, /*complain*/ false, &found)) { 12605 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12606 SrcExpr = ExprError(); 12607 return true; 12608 } 12609 12610 // It is only correct to resolve to an instance method if we're 12611 // resolving a form that's permitted to be a pointer to member. 12612 // Otherwise we'll end up making a bound member expression, which 12613 // is illegal in all the contexts we resolve like this. 12614 if (!ovl.HasFormOfMemberPointer && 12615 isa<CXXMethodDecl>(fn) && 12616 cast<CXXMethodDecl>(fn)->isInstance()) { 12617 if (!complain) return false; 12618 12619 Diag(ovl.Expression->getExprLoc(), 12620 diag::err_bound_member_function) 12621 << 0 << ovl.Expression->getSourceRange(); 12622 12623 // TODO: I believe we only end up here if there's a mix of 12624 // static and non-static candidates (otherwise the expression 12625 // would have 'bound member' type, not 'overload' type). 12626 // Ideally we would note which candidate was chosen and why 12627 // the static candidates were rejected. 12628 SrcExpr = ExprError(); 12629 return true; 12630 } 12631 12632 // Fix the expression to refer to 'fn'. 12633 SingleFunctionExpression = 12634 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12635 12636 // If desired, do function-to-pointer decay. 12637 if (doFunctionPointerConverion) { 12638 SingleFunctionExpression = 12639 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12640 if (SingleFunctionExpression.isInvalid()) { 12641 SrcExpr = ExprError(); 12642 return true; 12643 } 12644 } 12645 } 12646 12647 if (!SingleFunctionExpression.isUsable()) { 12648 if (complain) { 12649 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12650 << ovl.Expression->getName() 12651 << DestTypeForComplaining 12652 << OpRangeForComplaining 12653 << ovl.Expression->getQualifierLoc().getSourceRange(); 12654 NoteAllOverloadCandidates(SrcExpr.get()); 12655 12656 SrcExpr = ExprError(); 12657 return true; 12658 } 12659 12660 return false; 12661 } 12662 12663 SrcExpr = SingleFunctionExpression; 12664 return true; 12665 } 12666 12667 /// Add a single candidate to the overload set. 12668 static void AddOverloadedCallCandidate(Sema &S, 12669 DeclAccessPair FoundDecl, 12670 TemplateArgumentListInfo *ExplicitTemplateArgs, 12671 ArrayRef<Expr *> Args, 12672 OverloadCandidateSet &CandidateSet, 12673 bool PartialOverloading, 12674 bool KnownValid) { 12675 NamedDecl *Callee = FoundDecl.getDecl(); 12676 if (isa<UsingShadowDecl>(Callee)) 12677 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12678 12679 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12680 if (ExplicitTemplateArgs) { 12681 assert(!KnownValid && "Explicit template arguments?"); 12682 return; 12683 } 12684 // Prevent ill-formed function decls to be added as overload candidates. 12685 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12686 return; 12687 12688 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12689 /*SuppressUserConversions=*/false, 12690 PartialOverloading); 12691 return; 12692 } 12693 12694 if (FunctionTemplateDecl *FuncTemplate 12695 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12696 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12697 ExplicitTemplateArgs, Args, CandidateSet, 12698 /*SuppressUserConversions=*/false, 12699 PartialOverloading); 12700 return; 12701 } 12702 12703 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12704 } 12705 12706 /// Add the overload candidates named by callee and/or found by argument 12707 /// dependent lookup to the given overload set. 12708 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12709 ArrayRef<Expr *> Args, 12710 OverloadCandidateSet &CandidateSet, 12711 bool PartialOverloading) { 12712 12713 #ifndef NDEBUG 12714 // Verify that ArgumentDependentLookup is consistent with the rules 12715 // in C++0x [basic.lookup.argdep]p3: 12716 // 12717 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12718 // and let Y be the lookup set produced by argument dependent 12719 // lookup (defined as follows). If X contains 12720 // 12721 // -- a declaration of a class member, or 12722 // 12723 // -- a block-scope function declaration that is not a 12724 // using-declaration, or 12725 // 12726 // -- a declaration that is neither a function or a function 12727 // template 12728 // 12729 // then Y is empty. 12730 12731 if (ULE->requiresADL()) { 12732 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12733 E = ULE->decls_end(); I != E; ++I) { 12734 assert(!(*I)->getDeclContext()->isRecord()); 12735 assert(isa<UsingShadowDecl>(*I) || 12736 !(*I)->getDeclContext()->isFunctionOrMethod()); 12737 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12738 } 12739 } 12740 #endif 12741 12742 // It would be nice to avoid this copy. 12743 TemplateArgumentListInfo TABuffer; 12744 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12745 if (ULE->hasExplicitTemplateArgs()) { 12746 ULE->copyTemplateArgumentsInto(TABuffer); 12747 ExplicitTemplateArgs = &TABuffer; 12748 } 12749 12750 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12751 E = ULE->decls_end(); I != E; ++I) 12752 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12753 CandidateSet, PartialOverloading, 12754 /*KnownValid*/ true); 12755 12756 if (ULE->requiresADL()) 12757 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12758 Args, ExplicitTemplateArgs, 12759 CandidateSet, PartialOverloading); 12760 } 12761 12762 /// Add the call candidates from the given set of lookup results to the given 12763 /// overload set. Non-function lookup results are ignored. 12764 void Sema::AddOverloadedCallCandidates( 12765 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12766 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12767 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12768 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12769 CandidateSet, false, /*KnownValid*/ false); 12770 } 12771 12772 /// Determine whether a declaration with the specified name could be moved into 12773 /// a different namespace. 12774 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12775 switch (Name.getCXXOverloadedOperator()) { 12776 case OO_New: case OO_Array_New: 12777 case OO_Delete: case OO_Array_Delete: 12778 return false; 12779 12780 default: 12781 return true; 12782 } 12783 } 12784 12785 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12786 /// template, where the non-dependent name was declared after the template 12787 /// was defined. This is common in code written for a compilers which do not 12788 /// correctly implement two-stage name lookup. 12789 /// 12790 /// Returns true if a viable candidate was found and a diagnostic was issued. 12791 static bool DiagnoseTwoPhaseLookup( 12792 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12793 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12794 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12795 CXXRecordDecl **FoundInClass = nullptr) { 12796 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12797 return false; 12798 12799 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12800 if (DC->isTransparentContext()) 12801 continue; 12802 12803 SemaRef.LookupQualifiedName(R, DC); 12804 12805 if (!R.empty()) { 12806 R.suppressDiagnostics(); 12807 12808 OverloadCandidateSet Candidates(FnLoc, CSK); 12809 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12810 Candidates); 12811 12812 OverloadCandidateSet::iterator Best; 12813 OverloadingResult OR = 12814 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12815 12816 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12817 // We either found non-function declarations or a best viable function 12818 // at class scope. A class-scope lookup result disables ADL. Don't 12819 // look past this, but let the caller know that we found something that 12820 // either is, or might be, usable in this class. 12821 if (FoundInClass) { 12822 *FoundInClass = RD; 12823 if (OR == OR_Success) { 12824 R.clear(); 12825 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12826 R.resolveKind(); 12827 } 12828 } 12829 return false; 12830 } 12831 12832 if (OR != OR_Success) { 12833 // There wasn't a unique best function or function template. 12834 return false; 12835 } 12836 12837 // Find the namespaces where ADL would have looked, and suggest 12838 // declaring the function there instead. 12839 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12840 Sema::AssociatedClassSet AssociatedClasses; 12841 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12842 AssociatedNamespaces, 12843 AssociatedClasses); 12844 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12845 if (canBeDeclaredInNamespace(R.getLookupName())) { 12846 DeclContext *Std = SemaRef.getStdNamespace(); 12847 for (Sema::AssociatedNamespaceSet::iterator 12848 it = AssociatedNamespaces.begin(), 12849 end = AssociatedNamespaces.end(); it != end; ++it) { 12850 // Never suggest declaring a function within namespace 'std'. 12851 if (Std && Std->Encloses(*it)) 12852 continue; 12853 12854 // Never suggest declaring a function within a namespace with a 12855 // reserved name, like __gnu_cxx. 12856 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12857 if (NS && 12858 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12859 continue; 12860 12861 SuggestedNamespaces.insert(*it); 12862 } 12863 } 12864 12865 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12866 << R.getLookupName(); 12867 if (SuggestedNamespaces.empty()) { 12868 SemaRef.Diag(Best->Function->getLocation(), 12869 diag::note_not_found_by_two_phase_lookup) 12870 << R.getLookupName() << 0; 12871 } else if (SuggestedNamespaces.size() == 1) { 12872 SemaRef.Diag(Best->Function->getLocation(), 12873 diag::note_not_found_by_two_phase_lookup) 12874 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12875 } else { 12876 // FIXME: It would be useful to list the associated namespaces here, 12877 // but the diagnostics infrastructure doesn't provide a way to produce 12878 // a localized representation of a list of items. 12879 SemaRef.Diag(Best->Function->getLocation(), 12880 diag::note_not_found_by_two_phase_lookup) 12881 << R.getLookupName() << 2; 12882 } 12883 12884 // Try to recover by calling this function. 12885 return true; 12886 } 12887 12888 R.clear(); 12889 } 12890 12891 return false; 12892 } 12893 12894 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12895 /// template, where the non-dependent operator was declared after the template 12896 /// was defined. 12897 /// 12898 /// Returns true if a viable candidate was found and a diagnostic was issued. 12899 static bool 12900 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12901 SourceLocation OpLoc, 12902 ArrayRef<Expr *> Args) { 12903 DeclarationName OpName = 12904 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12905 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12906 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12907 OverloadCandidateSet::CSK_Operator, 12908 /*ExplicitTemplateArgs=*/nullptr, Args); 12909 } 12910 12911 namespace { 12912 class BuildRecoveryCallExprRAII { 12913 Sema &SemaRef; 12914 public: 12915 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12916 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12917 SemaRef.IsBuildingRecoveryCallExpr = true; 12918 } 12919 12920 ~BuildRecoveryCallExprRAII() { 12921 SemaRef.IsBuildingRecoveryCallExpr = false; 12922 } 12923 }; 12924 12925 } 12926 12927 /// Attempts to recover from a call where no functions were found. 12928 /// 12929 /// This function will do one of three things: 12930 /// * Diagnose, recover, and return a recovery expression. 12931 /// * Diagnose, fail to recover, and return ExprError(). 12932 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 12933 /// expected to diagnose as appropriate. 12934 static ExprResult 12935 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12936 UnresolvedLookupExpr *ULE, 12937 SourceLocation LParenLoc, 12938 MutableArrayRef<Expr *> Args, 12939 SourceLocation RParenLoc, 12940 bool EmptyLookup, bool AllowTypoCorrection) { 12941 // Do not try to recover if it is already building a recovery call. 12942 // This stops infinite loops for template instantiations like 12943 // 12944 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12945 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12946 if (SemaRef.IsBuildingRecoveryCallExpr) 12947 return ExprResult(); 12948 BuildRecoveryCallExprRAII RCE(SemaRef); 12949 12950 CXXScopeSpec SS; 12951 SS.Adopt(ULE->getQualifierLoc()); 12952 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12953 12954 TemplateArgumentListInfo TABuffer; 12955 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12956 if (ULE->hasExplicitTemplateArgs()) { 12957 ULE->copyTemplateArgumentsInto(TABuffer); 12958 ExplicitTemplateArgs = &TABuffer; 12959 } 12960 12961 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12962 Sema::LookupOrdinaryName); 12963 CXXRecordDecl *FoundInClass = nullptr; 12964 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 12965 OverloadCandidateSet::CSK_Normal, 12966 ExplicitTemplateArgs, Args, &FoundInClass)) { 12967 // OK, diagnosed a two-phase lookup issue. 12968 } else if (EmptyLookup) { 12969 // Try to recover from an empty lookup with typo correction. 12970 R.clear(); 12971 NoTypoCorrectionCCC NoTypoValidator{}; 12972 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12973 ExplicitTemplateArgs != nullptr, 12974 dyn_cast<MemberExpr>(Fn)); 12975 CorrectionCandidateCallback &Validator = 12976 AllowTypoCorrection 12977 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12978 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12979 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12980 Args)) 12981 return ExprError(); 12982 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 12983 // We found a usable declaration of the name in a dependent base of some 12984 // enclosing class. 12985 // FIXME: We should also explain why the candidates found by name lookup 12986 // were not viable. 12987 if (SemaRef.DiagnoseDependentMemberLookup(R)) 12988 return ExprError(); 12989 } else { 12990 // We had viable candidates and couldn't recover; let the caller diagnose 12991 // this. 12992 return ExprResult(); 12993 } 12994 12995 // If we get here, we should have issued a diagnostic and formed a recovery 12996 // lookup result. 12997 assert(!R.empty() && "lookup results empty despite recovery"); 12998 12999 // If recovery created an ambiguity, just bail out. 13000 if (R.isAmbiguous()) { 13001 R.suppressDiagnostics(); 13002 return ExprError(); 13003 } 13004 13005 // Build an implicit member call if appropriate. Just drop the 13006 // casts and such from the call, we don't really care. 13007 ExprResult NewFn = ExprError(); 13008 if ((*R.begin())->isCXXClassMember()) 13009 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13010 ExplicitTemplateArgs, S); 13011 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13012 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13013 ExplicitTemplateArgs); 13014 else 13015 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13016 13017 if (NewFn.isInvalid()) 13018 return ExprError(); 13019 13020 // This shouldn't cause an infinite loop because we're giving it 13021 // an expression with viable lookup results, which should never 13022 // end up here. 13023 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13024 MultiExprArg(Args.data(), Args.size()), 13025 RParenLoc); 13026 } 13027 13028 /// Constructs and populates an OverloadedCandidateSet from 13029 /// the given function. 13030 /// \returns true when an the ExprResult output parameter has been set. 13031 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13032 UnresolvedLookupExpr *ULE, 13033 MultiExprArg Args, 13034 SourceLocation RParenLoc, 13035 OverloadCandidateSet *CandidateSet, 13036 ExprResult *Result) { 13037 #ifndef NDEBUG 13038 if (ULE->requiresADL()) { 13039 // To do ADL, we must have found an unqualified name. 13040 assert(!ULE->getQualifier() && "qualified name with ADL"); 13041 13042 // We don't perform ADL for implicit declarations of builtins. 13043 // Verify that this was correctly set up. 13044 FunctionDecl *F; 13045 if (ULE->decls_begin() != ULE->decls_end() && 13046 ULE->decls_begin() + 1 == ULE->decls_end() && 13047 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13048 F->getBuiltinID() && F->isImplicit()) 13049 llvm_unreachable("performing ADL for builtin"); 13050 13051 // We don't perform ADL in C. 13052 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13053 } 13054 #endif 13055 13056 UnbridgedCastsSet UnbridgedCasts; 13057 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13058 *Result = ExprError(); 13059 return true; 13060 } 13061 13062 // Add the functions denoted by the callee to the set of candidate 13063 // functions, including those from argument-dependent lookup. 13064 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13065 13066 if (getLangOpts().MSVCCompat && 13067 CurContext->isDependentContext() && !isSFINAEContext() && 13068 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13069 13070 OverloadCandidateSet::iterator Best; 13071 if (CandidateSet->empty() || 13072 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13073 OR_No_Viable_Function) { 13074 // In Microsoft mode, if we are inside a template class member function 13075 // then create a type dependent CallExpr. The goal is to postpone name 13076 // lookup to instantiation time to be able to search into type dependent 13077 // base classes. 13078 CallExpr *CE = 13079 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13080 RParenLoc, CurFPFeatureOverrides()); 13081 CE->markDependentForPostponedNameLookup(); 13082 *Result = CE; 13083 return true; 13084 } 13085 } 13086 13087 if (CandidateSet->empty()) 13088 return false; 13089 13090 UnbridgedCasts.restore(); 13091 return false; 13092 } 13093 13094 // Guess at what the return type for an unresolvable overload should be. 13095 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13096 OverloadCandidateSet::iterator *Best) { 13097 llvm::Optional<QualType> Result; 13098 // Adjust Type after seeing a candidate. 13099 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13100 if (!Candidate.Function) 13101 return; 13102 if (Candidate.Function->isInvalidDecl()) 13103 return; 13104 QualType T = Candidate.Function->getReturnType(); 13105 if (T.isNull()) 13106 return; 13107 if (!Result) 13108 Result = T; 13109 else if (Result != T) 13110 Result = QualType(); 13111 }; 13112 13113 // Look for an unambiguous type from a progressively larger subset. 13114 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13115 // 13116 // First, consider only the best candidate. 13117 if (Best && *Best != CS.end()) 13118 ConsiderCandidate(**Best); 13119 // Next, consider only viable candidates. 13120 if (!Result) 13121 for (const auto &C : CS) 13122 if (C.Viable) 13123 ConsiderCandidate(C); 13124 // Finally, consider all candidates. 13125 if (!Result) 13126 for (const auto &C : CS) 13127 ConsiderCandidate(C); 13128 13129 if (!Result) 13130 return QualType(); 13131 auto Value = Result.getValue(); 13132 if (Value.isNull() || Value->isUndeducedType()) 13133 return QualType(); 13134 return Value; 13135 } 13136 13137 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13138 /// the completed call expression. If overload resolution fails, emits 13139 /// diagnostics and returns ExprError() 13140 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13141 UnresolvedLookupExpr *ULE, 13142 SourceLocation LParenLoc, 13143 MultiExprArg Args, 13144 SourceLocation RParenLoc, 13145 Expr *ExecConfig, 13146 OverloadCandidateSet *CandidateSet, 13147 OverloadCandidateSet::iterator *Best, 13148 OverloadingResult OverloadResult, 13149 bool AllowTypoCorrection) { 13150 switch (OverloadResult) { 13151 case OR_Success: { 13152 FunctionDecl *FDecl = (*Best)->Function; 13153 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13154 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13155 return ExprError(); 13156 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13157 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13158 ExecConfig, /*IsExecConfig=*/false, 13159 (*Best)->IsADLCandidate); 13160 } 13161 13162 case OR_No_Viable_Function: { 13163 // Try to recover by looking for viable functions which the user might 13164 // have meant to call. 13165 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13166 Args, RParenLoc, 13167 CandidateSet->empty(), 13168 AllowTypoCorrection); 13169 if (Recovery.isInvalid() || Recovery.isUsable()) 13170 return Recovery; 13171 13172 // If the user passes in a function that we can't take the address of, we 13173 // generally end up emitting really bad error messages. Here, we attempt to 13174 // emit better ones. 13175 for (const Expr *Arg : Args) { 13176 if (!Arg->getType()->isFunctionType()) 13177 continue; 13178 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13179 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13180 if (FD && 13181 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13182 Arg->getExprLoc())) 13183 return ExprError(); 13184 } 13185 } 13186 13187 CandidateSet->NoteCandidates( 13188 PartialDiagnosticAt( 13189 Fn->getBeginLoc(), 13190 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13191 << ULE->getName() << Fn->getSourceRange()), 13192 SemaRef, OCD_AllCandidates, Args); 13193 break; 13194 } 13195 13196 case OR_Ambiguous: 13197 CandidateSet->NoteCandidates( 13198 PartialDiagnosticAt(Fn->getBeginLoc(), 13199 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13200 << ULE->getName() << Fn->getSourceRange()), 13201 SemaRef, OCD_AmbiguousCandidates, Args); 13202 break; 13203 13204 case OR_Deleted: { 13205 CandidateSet->NoteCandidates( 13206 PartialDiagnosticAt(Fn->getBeginLoc(), 13207 SemaRef.PDiag(diag::err_ovl_deleted_call) 13208 << ULE->getName() << Fn->getSourceRange()), 13209 SemaRef, OCD_AllCandidates, Args); 13210 13211 // We emitted an error for the unavailable/deleted function call but keep 13212 // the call in the AST. 13213 FunctionDecl *FDecl = (*Best)->Function; 13214 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13215 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13216 ExecConfig, /*IsExecConfig=*/false, 13217 (*Best)->IsADLCandidate); 13218 } 13219 } 13220 13221 // Overload resolution failed, try to recover. 13222 SmallVector<Expr *, 8> SubExprs = {Fn}; 13223 SubExprs.append(Args.begin(), Args.end()); 13224 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13225 chooseRecoveryType(*CandidateSet, Best)); 13226 } 13227 13228 static void markUnaddressableCandidatesUnviable(Sema &S, 13229 OverloadCandidateSet &CS) { 13230 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13231 if (I->Viable && 13232 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13233 I->Viable = false; 13234 I->FailureKind = ovl_fail_addr_not_available; 13235 } 13236 } 13237 } 13238 13239 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13240 /// (which eventually refers to the declaration Func) and the call 13241 /// arguments Args/NumArgs, attempt to resolve the function call down 13242 /// to a specific function. If overload resolution succeeds, returns 13243 /// the call expression produced by overload resolution. 13244 /// Otherwise, emits diagnostics and returns ExprError. 13245 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13246 UnresolvedLookupExpr *ULE, 13247 SourceLocation LParenLoc, 13248 MultiExprArg Args, 13249 SourceLocation RParenLoc, 13250 Expr *ExecConfig, 13251 bool AllowTypoCorrection, 13252 bool CalleesAddressIsTaken) { 13253 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13254 OverloadCandidateSet::CSK_Normal); 13255 ExprResult result; 13256 13257 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13258 &result)) 13259 return result; 13260 13261 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13262 // functions that aren't addressible are considered unviable. 13263 if (CalleesAddressIsTaken) 13264 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13265 13266 OverloadCandidateSet::iterator Best; 13267 OverloadingResult OverloadResult = 13268 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13269 13270 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13271 ExecConfig, &CandidateSet, &Best, 13272 OverloadResult, AllowTypoCorrection); 13273 } 13274 13275 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13276 return Functions.size() > 1 || 13277 (Functions.size() == 1 && 13278 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13279 } 13280 13281 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13282 NestedNameSpecifierLoc NNSLoc, 13283 DeclarationNameInfo DNI, 13284 const UnresolvedSetImpl &Fns, 13285 bool PerformADL) { 13286 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13287 PerformADL, IsOverloaded(Fns), 13288 Fns.begin(), Fns.end()); 13289 } 13290 13291 /// Create a unary operation that may resolve to an overloaded 13292 /// operator. 13293 /// 13294 /// \param OpLoc The location of the operator itself (e.g., '*'). 13295 /// 13296 /// \param Opc The UnaryOperatorKind that describes this operator. 13297 /// 13298 /// \param Fns The set of non-member functions that will be 13299 /// considered by overload resolution. The caller needs to build this 13300 /// set based on the context using, e.g., 13301 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13302 /// set should not contain any member functions; those will be added 13303 /// by CreateOverloadedUnaryOp(). 13304 /// 13305 /// \param Input The input argument. 13306 ExprResult 13307 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13308 const UnresolvedSetImpl &Fns, 13309 Expr *Input, bool PerformADL) { 13310 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13311 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13312 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13313 // TODO: provide better source location info. 13314 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13315 13316 if (checkPlaceholderForOverload(*this, Input)) 13317 return ExprError(); 13318 13319 Expr *Args[2] = { Input, nullptr }; 13320 unsigned NumArgs = 1; 13321 13322 // For post-increment and post-decrement, add the implicit '0' as 13323 // the second argument, so that we know this is a post-increment or 13324 // post-decrement. 13325 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13326 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13327 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13328 SourceLocation()); 13329 NumArgs = 2; 13330 } 13331 13332 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13333 13334 if (Input->isTypeDependent()) { 13335 if (Fns.empty()) 13336 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13337 VK_PRValue, OK_Ordinary, OpLoc, false, 13338 CurFPFeatureOverrides()); 13339 13340 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13341 ExprResult Fn = CreateUnresolvedLookupExpr( 13342 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13343 if (Fn.isInvalid()) 13344 return ExprError(); 13345 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13346 Context.DependentTy, VK_PRValue, OpLoc, 13347 CurFPFeatureOverrides()); 13348 } 13349 13350 // Build an empty overload set. 13351 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13352 13353 // Add the candidates from the given function set. 13354 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13355 13356 // Add operator candidates that are member functions. 13357 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13358 13359 // Add candidates from ADL. 13360 if (PerformADL) { 13361 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13362 /*ExplicitTemplateArgs*/nullptr, 13363 CandidateSet); 13364 } 13365 13366 // Add builtin operator candidates. 13367 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13368 13369 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13370 13371 // Perform overload resolution. 13372 OverloadCandidateSet::iterator Best; 13373 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13374 case OR_Success: { 13375 // We found a built-in operator or an overloaded operator. 13376 FunctionDecl *FnDecl = Best->Function; 13377 13378 if (FnDecl) { 13379 Expr *Base = nullptr; 13380 // We matched an overloaded operator. Build a call to that 13381 // operator. 13382 13383 // Convert the arguments. 13384 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13385 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13386 13387 ExprResult InputRes = 13388 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13389 Best->FoundDecl, Method); 13390 if (InputRes.isInvalid()) 13391 return ExprError(); 13392 Base = Input = InputRes.get(); 13393 } else { 13394 // Convert the arguments. 13395 ExprResult InputInit 13396 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13397 Context, 13398 FnDecl->getParamDecl(0)), 13399 SourceLocation(), 13400 Input); 13401 if (InputInit.isInvalid()) 13402 return ExprError(); 13403 Input = InputInit.get(); 13404 } 13405 13406 // Build the actual expression node. 13407 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13408 Base, HadMultipleCandidates, 13409 OpLoc); 13410 if (FnExpr.isInvalid()) 13411 return ExprError(); 13412 13413 // Determine the result type. 13414 QualType ResultTy = FnDecl->getReturnType(); 13415 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13416 ResultTy = ResultTy.getNonLValueExprType(Context); 13417 13418 Args[0] = Input; 13419 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13420 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13421 CurFPFeatureOverrides(), Best->IsADLCandidate); 13422 13423 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13424 return ExprError(); 13425 13426 if (CheckFunctionCall(FnDecl, TheCall, 13427 FnDecl->getType()->castAs<FunctionProtoType>())) 13428 return ExprError(); 13429 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13430 } else { 13431 // We matched a built-in operator. Convert the arguments, then 13432 // break out so that we will build the appropriate built-in 13433 // operator node. 13434 ExprResult InputRes = PerformImplicitConversion( 13435 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13436 CCK_ForBuiltinOverloadedOp); 13437 if (InputRes.isInvalid()) 13438 return ExprError(); 13439 Input = InputRes.get(); 13440 break; 13441 } 13442 } 13443 13444 case OR_No_Viable_Function: 13445 // This is an erroneous use of an operator which can be overloaded by 13446 // a non-member function. Check for non-member operators which were 13447 // defined too late to be candidates. 13448 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13449 // FIXME: Recover by calling the found function. 13450 return ExprError(); 13451 13452 // No viable function; fall through to handling this as a 13453 // built-in operator, which will produce an error message for us. 13454 break; 13455 13456 case OR_Ambiguous: 13457 CandidateSet.NoteCandidates( 13458 PartialDiagnosticAt(OpLoc, 13459 PDiag(diag::err_ovl_ambiguous_oper_unary) 13460 << UnaryOperator::getOpcodeStr(Opc) 13461 << Input->getType() << Input->getSourceRange()), 13462 *this, OCD_AmbiguousCandidates, ArgsArray, 13463 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13464 return ExprError(); 13465 13466 case OR_Deleted: 13467 CandidateSet.NoteCandidates( 13468 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13469 << UnaryOperator::getOpcodeStr(Opc) 13470 << Input->getSourceRange()), 13471 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13472 OpLoc); 13473 return ExprError(); 13474 } 13475 13476 // Either we found no viable overloaded operator or we matched a 13477 // built-in operator. In either case, fall through to trying to 13478 // build a built-in operation. 13479 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13480 } 13481 13482 /// Perform lookup for an overloaded binary operator. 13483 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13484 OverloadedOperatorKind Op, 13485 const UnresolvedSetImpl &Fns, 13486 ArrayRef<Expr *> Args, bool PerformADL) { 13487 SourceLocation OpLoc = CandidateSet.getLocation(); 13488 13489 OverloadedOperatorKind ExtraOp = 13490 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13491 ? getRewrittenOverloadedOperator(Op) 13492 : OO_None; 13493 13494 // Add the candidates from the given function set. This also adds the 13495 // rewritten candidates using these functions if necessary. 13496 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13497 13498 // Add operator candidates that are member functions. 13499 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13500 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13501 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13502 OverloadCandidateParamOrder::Reversed); 13503 13504 // In C++20, also add any rewritten member candidates. 13505 if (ExtraOp) { 13506 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13507 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13508 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13509 CandidateSet, 13510 OverloadCandidateParamOrder::Reversed); 13511 } 13512 13513 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13514 // performed for an assignment operator (nor for operator[] nor operator->, 13515 // which don't get here). 13516 if (Op != OO_Equal && PerformADL) { 13517 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13518 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13519 /*ExplicitTemplateArgs*/ nullptr, 13520 CandidateSet); 13521 if (ExtraOp) { 13522 DeclarationName ExtraOpName = 13523 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13524 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13525 /*ExplicitTemplateArgs*/ nullptr, 13526 CandidateSet); 13527 } 13528 } 13529 13530 // Add builtin operator candidates. 13531 // 13532 // FIXME: We don't add any rewritten candidates here. This is strictly 13533 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13534 // resulting in our selecting a rewritten builtin candidate. For example: 13535 // 13536 // enum class E { e }; 13537 // bool operator!=(E, E) requires false; 13538 // bool k = E::e != E::e; 13539 // 13540 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13541 // it seems unreasonable to consider rewritten builtin candidates. A core 13542 // issue has been filed proposing to removed this requirement. 13543 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13544 } 13545 13546 /// Create a binary operation that may resolve to an overloaded 13547 /// operator. 13548 /// 13549 /// \param OpLoc The location of the operator itself (e.g., '+'). 13550 /// 13551 /// \param Opc The BinaryOperatorKind that describes this operator. 13552 /// 13553 /// \param Fns The set of non-member functions that will be 13554 /// considered by overload resolution. The caller needs to build this 13555 /// set based on the context using, e.g., 13556 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13557 /// set should not contain any member functions; those will be added 13558 /// by CreateOverloadedBinOp(). 13559 /// 13560 /// \param LHS Left-hand argument. 13561 /// \param RHS Right-hand argument. 13562 /// \param PerformADL Whether to consider operator candidates found by ADL. 13563 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13564 /// C++20 operator rewrites. 13565 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13566 /// the function in question. Such a function is never a candidate in 13567 /// our overload resolution. This also enables synthesizing a three-way 13568 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13569 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13570 BinaryOperatorKind Opc, 13571 const UnresolvedSetImpl &Fns, Expr *LHS, 13572 Expr *RHS, bool PerformADL, 13573 bool AllowRewrittenCandidates, 13574 FunctionDecl *DefaultedFn) { 13575 Expr *Args[2] = { LHS, RHS }; 13576 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13577 13578 if (!getLangOpts().CPlusPlus20) 13579 AllowRewrittenCandidates = false; 13580 13581 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13582 13583 // If either side is type-dependent, create an appropriate dependent 13584 // expression. 13585 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13586 if (Fns.empty()) { 13587 // If there are no functions to store, just build a dependent 13588 // BinaryOperator or CompoundAssignment. 13589 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13590 return CompoundAssignOperator::Create( 13591 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13592 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13593 Context.DependentTy); 13594 return BinaryOperator::Create( 13595 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 13596 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13597 } 13598 13599 // FIXME: save results of ADL from here? 13600 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13601 // TODO: provide better source location info in DNLoc component. 13602 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13603 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13604 ExprResult Fn = CreateUnresolvedLookupExpr( 13605 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13606 if (Fn.isInvalid()) 13607 return ExprError(); 13608 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13609 Context.DependentTy, VK_PRValue, OpLoc, 13610 CurFPFeatureOverrides()); 13611 } 13612 13613 // Always do placeholder-like conversions on the RHS. 13614 if (checkPlaceholderForOverload(*this, Args[1])) 13615 return ExprError(); 13616 13617 // Do placeholder-like conversion on the LHS; note that we should 13618 // not get here with a PseudoObject LHS. 13619 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13620 if (checkPlaceholderForOverload(*this, Args[0])) 13621 return ExprError(); 13622 13623 // If this is the assignment operator, we only perform overload resolution 13624 // if the left-hand side is a class or enumeration type. This is actually 13625 // a hack. The standard requires that we do overload resolution between the 13626 // various built-in candidates, but as DR507 points out, this can lead to 13627 // problems. So we do it this way, which pretty much follows what GCC does. 13628 // Note that we go the traditional code path for compound assignment forms. 13629 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13630 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13631 13632 // If this is the .* operator, which is not overloadable, just 13633 // create a built-in binary operator. 13634 if (Opc == BO_PtrMemD) 13635 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13636 13637 // Build the overload set. 13638 OverloadCandidateSet CandidateSet( 13639 OpLoc, OverloadCandidateSet::CSK_Operator, 13640 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13641 if (DefaultedFn) 13642 CandidateSet.exclude(DefaultedFn); 13643 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13644 13645 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13646 13647 // Perform overload resolution. 13648 OverloadCandidateSet::iterator Best; 13649 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13650 case OR_Success: { 13651 // We found a built-in operator or an overloaded operator. 13652 FunctionDecl *FnDecl = Best->Function; 13653 13654 bool IsReversed = Best->isReversed(); 13655 if (IsReversed) 13656 std::swap(Args[0], Args[1]); 13657 13658 if (FnDecl) { 13659 Expr *Base = nullptr; 13660 // We matched an overloaded operator. Build a call to that 13661 // operator. 13662 13663 OverloadedOperatorKind ChosenOp = 13664 FnDecl->getDeclName().getCXXOverloadedOperator(); 13665 13666 // C++2a [over.match.oper]p9: 13667 // If a rewritten operator== candidate is selected by overload 13668 // resolution for an operator@, its return type shall be cv bool 13669 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13670 !FnDecl->getReturnType()->isBooleanType()) { 13671 bool IsExtension = 13672 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13673 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13674 : diag::err_ovl_rewrite_equalequal_not_bool) 13675 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13676 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13677 Diag(FnDecl->getLocation(), diag::note_declared_at); 13678 if (!IsExtension) 13679 return ExprError(); 13680 } 13681 13682 if (AllowRewrittenCandidates && !IsReversed && 13683 CandidateSet.getRewriteInfo().isReversible()) { 13684 // We could have reversed this operator, but didn't. Check if some 13685 // reversed form was a viable candidate, and if so, if it had a 13686 // better conversion for either parameter. If so, this call is 13687 // formally ambiguous, and allowing it is an extension. 13688 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13689 for (OverloadCandidate &Cand : CandidateSet) { 13690 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13691 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13692 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13693 if (CompareImplicitConversionSequences( 13694 *this, OpLoc, Cand.Conversions[ArgIdx], 13695 Best->Conversions[ArgIdx]) == 13696 ImplicitConversionSequence::Better) { 13697 AmbiguousWith.push_back(Cand.Function); 13698 break; 13699 } 13700 } 13701 } 13702 } 13703 13704 if (!AmbiguousWith.empty()) { 13705 bool AmbiguousWithSelf = 13706 AmbiguousWith.size() == 1 && 13707 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13708 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13709 << BinaryOperator::getOpcodeStr(Opc) 13710 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13711 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13712 if (AmbiguousWithSelf) { 13713 Diag(FnDecl->getLocation(), 13714 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13715 } else { 13716 Diag(FnDecl->getLocation(), 13717 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13718 for (auto *F : AmbiguousWith) 13719 Diag(F->getLocation(), 13720 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13721 } 13722 } 13723 } 13724 13725 // Convert the arguments. 13726 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13727 // Best->Access is only meaningful for class members. 13728 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13729 13730 ExprResult Arg1 = 13731 PerformCopyInitialization( 13732 InitializedEntity::InitializeParameter(Context, 13733 FnDecl->getParamDecl(0)), 13734 SourceLocation(), Args[1]); 13735 if (Arg1.isInvalid()) 13736 return ExprError(); 13737 13738 ExprResult Arg0 = 13739 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13740 Best->FoundDecl, Method); 13741 if (Arg0.isInvalid()) 13742 return ExprError(); 13743 Base = Args[0] = Arg0.getAs<Expr>(); 13744 Args[1] = RHS = Arg1.getAs<Expr>(); 13745 } else { 13746 // Convert the arguments. 13747 ExprResult Arg0 = PerformCopyInitialization( 13748 InitializedEntity::InitializeParameter(Context, 13749 FnDecl->getParamDecl(0)), 13750 SourceLocation(), Args[0]); 13751 if (Arg0.isInvalid()) 13752 return ExprError(); 13753 13754 ExprResult Arg1 = 13755 PerformCopyInitialization( 13756 InitializedEntity::InitializeParameter(Context, 13757 FnDecl->getParamDecl(1)), 13758 SourceLocation(), Args[1]); 13759 if (Arg1.isInvalid()) 13760 return ExprError(); 13761 Args[0] = LHS = Arg0.getAs<Expr>(); 13762 Args[1] = RHS = Arg1.getAs<Expr>(); 13763 } 13764 13765 // Build the actual expression node. 13766 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13767 Best->FoundDecl, Base, 13768 HadMultipleCandidates, OpLoc); 13769 if (FnExpr.isInvalid()) 13770 return ExprError(); 13771 13772 // Determine the result type. 13773 QualType ResultTy = FnDecl->getReturnType(); 13774 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13775 ResultTy = ResultTy.getNonLValueExprType(Context); 13776 13777 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13778 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13779 CurFPFeatureOverrides(), Best->IsADLCandidate); 13780 13781 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13782 FnDecl)) 13783 return ExprError(); 13784 13785 ArrayRef<const Expr *> ArgsArray(Args, 2); 13786 const Expr *ImplicitThis = nullptr; 13787 // Cut off the implicit 'this'. 13788 if (isa<CXXMethodDecl>(FnDecl)) { 13789 ImplicitThis = ArgsArray[0]; 13790 ArgsArray = ArgsArray.slice(1); 13791 } 13792 13793 // Check for a self move. 13794 if (Op == OO_Equal) 13795 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13796 13797 if (ImplicitThis) { 13798 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13799 QualType ThisTypeFromDecl = Context.getPointerType( 13800 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13801 13802 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13803 ThisTypeFromDecl); 13804 } 13805 13806 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13807 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13808 VariadicDoesNotApply); 13809 13810 ExprResult R = MaybeBindToTemporary(TheCall); 13811 if (R.isInvalid()) 13812 return ExprError(); 13813 13814 R = CheckForImmediateInvocation(R, FnDecl); 13815 if (R.isInvalid()) 13816 return ExprError(); 13817 13818 // For a rewritten candidate, we've already reversed the arguments 13819 // if needed. Perform the rest of the rewrite now. 13820 if ((Best->RewriteKind & CRK_DifferentOperator) || 13821 (Op == OO_Spaceship && IsReversed)) { 13822 if (Op == OO_ExclaimEqual) { 13823 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13824 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13825 } else { 13826 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13827 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13828 Expr *ZeroLiteral = 13829 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13830 13831 Sema::CodeSynthesisContext Ctx; 13832 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13833 Ctx.Entity = FnDecl; 13834 pushCodeSynthesisContext(Ctx); 13835 13836 R = CreateOverloadedBinOp( 13837 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13838 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13839 /*AllowRewrittenCandidates=*/false); 13840 13841 popCodeSynthesisContext(); 13842 } 13843 if (R.isInvalid()) 13844 return ExprError(); 13845 } else { 13846 assert(ChosenOp == Op && "unexpected operator name"); 13847 } 13848 13849 // Make a note in the AST if we did any rewriting. 13850 if (Best->RewriteKind != CRK_None) 13851 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13852 13853 return R; 13854 } else { 13855 // We matched a built-in operator. Convert the arguments, then 13856 // break out so that we will build the appropriate built-in 13857 // operator node. 13858 ExprResult ArgsRes0 = PerformImplicitConversion( 13859 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13860 AA_Passing, CCK_ForBuiltinOverloadedOp); 13861 if (ArgsRes0.isInvalid()) 13862 return ExprError(); 13863 Args[0] = ArgsRes0.get(); 13864 13865 ExprResult ArgsRes1 = PerformImplicitConversion( 13866 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13867 AA_Passing, CCK_ForBuiltinOverloadedOp); 13868 if (ArgsRes1.isInvalid()) 13869 return ExprError(); 13870 Args[1] = ArgsRes1.get(); 13871 break; 13872 } 13873 } 13874 13875 case OR_No_Viable_Function: { 13876 // C++ [over.match.oper]p9: 13877 // If the operator is the operator , [...] and there are no 13878 // viable functions, then the operator is assumed to be the 13879 // built-in operator and interpreted according to clause 5. 13880 if (Opc == BO_Comma) 13881 break; 13882 13883 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13884 // compare result using '==' and '<'. 13885 if (DefaultedFn && Opc == BO_Cmp) { 13886 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13887 Args[1], DefaultedFn); 13888 if (E.isInvalid() || E.isUsable()) 13889 return E; 13890 } 13891 13892 // For class as left operand for assignment or compound assignment 13893 // operator do not fall through to handling in built-in, but report that 13894 // no overloaded assignment operator found 13895 ExprResult Result = ExprError(); 13896 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13897 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13898 Args, OpLoc); 13899 DeferDiagsRAII DDR(*this, 13900 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 13901 if (Args[0]->getType()->isRecordType() && 13902 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13903 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13904 << BinaryOperator::getOpcodeStr(Opc) 13905 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13906 if (Args[0]->getType()->isIncompleteType()) { 13907 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13908 << Args[0]->getType() 13909 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13910 } 13911 } else { 13912 // This is an erroneous use of an operator which can be overloaded by 13913 // a non-member function. Check for non-member operators which were 13914 // defined too late to be candidates. 13915 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13916 // FIXME: Recover by calling the found function. 13917 return ExprError(); 13918 13919 // No viable function; try to create a built-in operation, which will 13920 // produce an error. Then, show the non-viable candidates. 13921 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13922 } 13923 assert(Result.isInvalid() && 13924 "C++ binary operator overloading is missing candidates!"); 13925 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13926 return Result; 13927 } 13928 13929 case OR_Ambiguous: 13930 CandidateSet.NoteCandidates( 13931 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13932 << BinaryOperator::getOpcodeStr(Opc) 13933 << Args[0]->getType() 13934 << Args[1]->getType() 13935 << Args[0]->getSourceRange() 13936 << Args[1]->getSourceRange()), 13937 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13938 OpLoc); 13939 return ExprError(); 13940 13941 case OR_Deleted: 13942 if (isImplicitlyDeleted(Best->Function)) { 13943 FunctionDecl *DeletedFD = Best->Function; 13944 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13945 if (DFK.isSpecialMember()) { 13946 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13947 << Args[0]->getType() << DFK.asSpecialMember(); 13948 } else { 13949 assert(DFK.isComparison()); 13950 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13951 << Args[0]->getType() << DeletedFD; 13952 } 13953 13954 // The user probably meant to call this special member. Just 13955 // explain why it's deleted. 13956 NoteDeletedFunction(DeletedFD); 13957 return ExprError(); 13958 } 13959 CandidateSet.NoteCandidates( 13960 PartialDiagnosticAt( 13961 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13962 << getOperatorSpelling(Best->Function->getDeclName() 13963 .getCXXOverloadedOperator()) 13964 << Args[0]->getSourceRange() 13965 << Args[1]->getSourceRange()), 13966 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13967 OpLoc); 13968 return ExprError(); 13969 } 13970 13971 // We matched a built-in operator; build it. 13972 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13973 } 13974 13975 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13976 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13977 FunctionDecl *DefaultedFn) { 13978 const ComparisonCategoryInfo *Info = 13979 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13980 // If we're not producing a known comparison category type, we can't 13981 // synthesize a three-way comparison. Let the caller diagnose this. 13982 if (!Info) 13983 return ExprResult((Expr*)nullptr); 13984 13985 // If we ever want to perform this synthesis more generally, we will need to 13986 // apply the temporary materialization conversion to the operands. 13987 assert(LHS->isGLValue() && RHS->isGLValue() && 13988 "cannot use prvalue expressions more than once"); 13989 Expr *OrigLHS = LHS; 13990 Expr *OrigRHS = RHS; 13991 13992 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13993 // each of them multiple times below. 13994 LHS = new (Context) 13995 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13996 LHS->getObjectKind(), LHS); 13997 RHS = new (Context) 13998 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13999 RHS->getObjectKind(), RHS); 14000 14001 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 14002 DefaultedFn); 14003 if (Eq.isInvalid()) 14004 return ExprError(); 14005 14006 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 14007 true, DefaultedFn); 14008 if (Less.isInvalid()) 14009 return ExprError(); 14010 14011 ExprResult Greater; 14012 if (Info->isPartial()) { 14013 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14014 DefaultedFn); 14015 if (Greater.isInvalid()) 14016 return ExprError(); 14017 } 14018 14019 // Form the list of comparisons we're going to perform. 14020 struct Comparison { 14021 ExprResult Cmp; 14022 ComparisonCategoryResult Result; 14023 } Comparisons[4] = 14024 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14025 : ComparisonCategoryResult::Equivalent}, 14026 {Less, ComparisonCategoryResult::Less}, 14027 {Greater, ComparisonCategoryResult::Greater}, 14028 {ExprResult(), ComparisonCategoryResult::Unordered}, 14029 }; 14030 14031 int I = Info->isPartial() ? 3 : 2; 14032 14033 // Combine the comparisons with suitable conditional expressions. 14034 ExprResult Result; 14035 for (; I >= 0; --I) { 14036 // Build a reference to the comparison category constant. 14037 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14038 // FIXME: Missing a constant for a comparison category. Diagnose this? 14039 if (!VI) 14040 return ExprResult((Expr*)nullptr); 14041 ExprResult ThisResult = 14042 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14043 if (ThisResult.isInvalid()) 14044 return ExprError(); 14045 14046 // Build a conditional unless this is the final case. 14047 if (Result.get()) { 14048 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14049 ThisResult.get(), Result.get()); 14050 if (Result.isInvalid()) 14051 return ExprError(); 14052 } else { 14053 Result = ThisResult; 14054 } 14055 } 14056 14057 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14058 // bind the OpaqueValueExprs before they're (repeatedly) used. 14059 Expr *SyntacticForm = BinaryOperator::Create( 14060 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14061 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14062 CurFPFeatureOverrides()); 14063 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14064 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14065 } 14066 14067 static bool PrepareArgumentsForCallToObjectOfClassType( 14068 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 14069 MultiExprArg Args, SourceLocation LParenLoc) { 14070 14071 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14072 unsigned NumParams = Proto->getNumParams(); 14073 unsigned NumArgsSlots = 14074 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 14075 // Build the full argument list for the method call (the implicit object 14076 // parameter is placed at the beginning of the list). 14077 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 14078 bool IsError = false; 14079 // Initialize the implicit object parameter. 14080 // Check the argument types. 14081 for (unsigned i = 0; i != NumParams; i++) { 14082 Expr *Arg; 14083 if (i < Args.size()) { 14084 Arg = Args[i]; 14085 ExprResult InputInit = 14086 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 14087 S.Context, Method->getParamDecl(i)), 14088 SourceLocation(), Arg); 14089 IsError |= InputInit.isInvalid(); 14090 Arg = InputInit.getAs<Expr>(); 14091 } else { 14092 ExprResult DefArg = 14093 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14094 if (DefArg.isInvalid()) { 14095 IsError = true; 14096 break; 14097 } 14098 Arg = DefArg.getAs<Expr>(); 14099 } 14100 14101 MethodArgs.push_back(Arg); 14102 } 14103 return IsError; 14104 } 14105 14106 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14107 SourceLocation RLoc, 14108 Expr *Base, 14109 MultiExprArg ArgExpr) { 14110 SmallVector<Expr *, 2> Args; 14111 Args.push_back(Base); 14112 for (auto e : ArgExpr) { 14113 Args.push_back(e); 14114 } 14115 DeclarationName OpName = 14116 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14117 14118 SourceRange Range = ArgExpr.empty() 14119 ? SourceRange{} 14120 : SourceRange(ArgExpr.front()->getBeginLoc(), 14121 ArgExpr.back()->getEndLoc()); 14122 14123 // If either side is type-dependent, create an appropriate dependent 14124 // expression. 14125 if (Expr::hasAnyTypeDependentArguments(Args)) { 14126 14127 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14128 // CHECKME: no 'operator' keyword? 14129 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14130 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14131 ExprResult Fn = CreateUnresolvedLookupExpr( 14132 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14133 if (Fn.isInvalid()) 14134 return ExprError(); 14135 // Can't add any actual overloads yet 14136 14137 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14138 Context.DependentTy, VK_PRValue, RLoc, 14139 CurFPFeatureOverrides()); 14140 } 14141 14142 // Handle placeholders 14143 UnbridgedCastsSet UnbridgedCasts; 14144 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 14145 return ExprError(); 14146 } 14147 // Build an empty overload set. 14148 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14149 14150 // Subscript can only be overloaded as a member function. 14151 14152 // Add operator candidates that are member functions. 14153 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14154 14155 // Add builtin operator candidates. 14156 if (Args.size() == 2) 14157 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14158 14159 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14160 14161 // Perform overload resolution. 14162 OverloadCandidateSet::iterator Best; 14163 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14164 case OR_Success: { 14165 // We found a built-in operator or an overloaded operator. 14166 FunctionDecl *FnDecl = Best->Function; 14167 14168 if (FnDecl) { 14169 // We matched an overloaded operator. Build a call to that 14170 // operator. 14171 14172 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 14173 14174 // Convert the arguments. 14175 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14176 SmallVector<Expr *, 2> MethodArgs; 14177 ExprResult Arg0 = PerformObjectArgumentInitialization( 14178 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14179 if (Arg0.isInvalid()) 14180 return ExprError(); 14181 14182 MethodArgs.push_back(Arg0.get()); 14183 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 14184 *this, MethodArgs, Method, ArgExpr, LLoc); 14185 if (IsError) 14186 return ExprError(); 14187 14188 // Build the actual expression node. 14189 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14190 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14191 ExprResult FnExpr = CreateFunctionRefExpr( 14192 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 14193 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 14194 if (FnExpr.isInvalid()) 14195 return ExprError(); 14196 14197 // Determine the result type 14198 QualType ResultTy = FnDecl->getReturnType(); 14199 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14200 ResultTy = ResultTy.getNonLValueExprType(Context); 14201 14202 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14203 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc, 14204 CurFPFeatureOverrides()); 14205 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14206 return ExprError(); 14207 14208 if (CheckFunctionCall(Method, TheCall, 14209 Method->getType()->castAs<FunctionProtoType>())) 14210 return ExprError(); 14211 14212 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14213 FnDecl); 14214 } else { 14215 // We matched a built-in operator. Convert the arguments, then 14216 // break out so that we will build the appropriate built-in 14217 // operator node. 14218 ExprResult ArgsRes0 = PerformImplicitConversion( 14219 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14220 AA_Passing, CCK_ForBuiltinOverloadedOp); 14221 if (ArgsRes0.isInvalid()) 14222 return ExprError(); 14223 Args[0] = ArgsRes0.get(); 14224 14225 ExprResult ArgsRes1 = PerformImplicitConversion( 14226 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14227 AA_Passing, CCK_ForBuiltinOverloadedOp); 14228 if (ArgsRes1.isInvalid()) 14229 return ExprError(); 14230 Args[1] = ArgsRes1.get(); 14231 14232 break; 14233 } 14234 } 14235 14236 case OR_No_Viable_Function: { 14237 PartialDiagnostic PD = 14238 CandidateSet.empty() 14239 ? (PDiag(diag::err_ovl_no_oper) 14240 << Args[0]->getType() << /*subscript*/ 0 14241 << Args[0]->getSourceRange() << Range) 14242 : (PDiag(diag::err_ovl_no_viable_subscript) 14243 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 14244 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14245 OCD_AllCandidates, ArgExpr, "[]", LLoc); 14246 return ExprError(); 14247 } 14248 14249 case OR_Ambiguous: 14250 if (Args.size() == 2) { 14251 CandidateSet.NoteCandidates( 14252 PartialDiagnosticAt( 14253 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14254 << "[]" << Args[0]->getType() << Args[1]->getType() 14255 << Args[0]->getSourceRange() << Range), 14256 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14257 } else { 14258 CandidateSet.NoteCandidates( 14259 PartialDiagnosticAt(LLoc, 14260 PDiag(diag::err_ovl_ambiguous_subscript_call) 14261 << Args[0]->getType() 14262 << Args[0]->getSourceRange() << Range), 14263 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14264 } 14265 return ExprError(); 14266 14267 case OR_Deleted: 14268 CandidateSet.NoteCandidates( 14269 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14270 << "[]" << Args[0]->getSourceRange() 14271 << Range), 14272 *this, OCD_AllCandidates, Args, "[]", LLoc); 14273 return ExprError(); 14274 } 14275 14276 // We matched a built-in operator; build it. 14277 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14278 } 14279 14280 /// BuildCallToMemberFunction - Build a call to a member 14281 /// function. MemExpr is the expression that refers to the member 14282 /// function (and includes the object parameter), Args/NumArgs are the 14283 /// arguments to the function call (not including the object 14284 /// parameter). The caller needs to validate that the member 14285 /// expression refers to a non-static member function or an overloaded 14286 /// member function. 14287 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14288 SourceLocation LParenLoc, 14289 MultiExprArg Args, 14290 SourceLocation RParenLoc, 14291 Expr *ExecConfig, bool IsExecConfig, 14292 bool AllowRecovery) { 14293 assert(MemExprE->getType() == Context.BoundMemberTy || 14294 MemExprE->getType() == Context.OverloadTy); 14295 14296 // Dig out the member expression. This holds both the object 14297 // argument and the member function we're referring to. 14298 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14299 14300 // Determine whether this is a call to a pointer-to-member function. 14301 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14302 assert(op->getType() == Context.BoundMemberTy); 14303 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14304 14305 QualType fnType = 14306 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14307 14308 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14309 QualType resultType = proto->getCallResultType(Context); 14310 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14311 14312 // Check that the object type isn't more qualified than the 14313 // member function we're calling. 14314 Qualifiers funcQuals = proto->getMethodQuals(); 14315 14316 QualType objectType = op->getLHS()->getType(); 14317 if (op->getOpcode() == BO_PtrMemI) 14318 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14319 Qualifiers objectQuals = objectType.getQualifiers(); 14320 14321 Qualifiers difference = objectQuals - funcQuals; 14322 difference.removeObjCGCAttr(); 14323 difference.removeAddressSpace(); 14324 if (difference) { 14325 std::string qualsString = difference.getAsString(); 14326 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14327 << fnType.getUnqualifiedType() 14328 << qualsString 14329 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14330 } 14331 14332 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14333 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14334 CurFPFeatureOverrides(), proto->getNumParams()); 14335 14336 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14337 call, nullptr)) 14338 return ExprError(); 14339 14340 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14341 return ExprError(); 14342 14343 if (CheckOtherCall(call, proto)) 14344 return ExprError(); 14345 14346 return MaybeBindToTemporary(call); 14347 } 14348 14349 // We only try to build a recovery expr at this level if we can preserve 14350 // the return type, otherwise we return ExprError() and let the caller 14351 // recover. 14352 auto BuildRecoveryExpr = [&](QualType Type) { 14353 if (!AllowRecovery) 14354 return ExprError(); 14355 std::vector<Expr *> SubExprs = {MemExprE}; 14356 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); }); 14357 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14358 Type); 14359 }; 14360 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14361 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 14362 RParenLoc, CurFPFeatureOverrides()); 14363 14364 UnbridgedCastsSet UnbridgedCasts; 14365 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14366 return ExprError(); 14367 14368 MemberExpr *MemExpr; 14369 CXXMethodDecl *Method = nullptr; 14370 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14371 NestedNameSpecifier *Qualifier = nullptr; 14372 if (isa<MemberExpr>(NakedMemExpr)) { 14373 MemExpr = cast<MemberExpr>(NakedMemExpr); 14374 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14375 FoundDecl = MemExpr->getFoundDecl(); 14376 Qualifier = MemExpr->getQualifier(); 14377 UnbridgedCasts.restore(); 14378 } else { 14379 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14380 Qualifier = UnresExpr->getQualifier(); 14381 14382 QualType ObjectType = UnresExpr->getBaseType(); 14383 Expr::Classification ObjectClassification 14384 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14385 : UnresExpr->getBase()->Classify(Context); 14386 14387 // Add overload candidates 14388 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14389 OverloadCandidateSet::CSK_Normal); 14390 14391 // FIXME: avoid copy. 14392 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14393 if (UnresExpr->hasExplicitTemplateArgs()) { 14394 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14395 TemplateArgs = &TemplateArgsBuffer; 14396 } 14397 14398 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14399 E = UnresExpr->decls_end(); I != E; ++I) { 14400 14401 NamedDecl *Func = *I; 14402 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14403 if (isa<UsingShadowDecl>(Func)) 14404 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14405 14406 14407 // Microsoft supports direct constructor calls. 14408 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14409 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14410 CandidateSet, 14411 /*SuppressUserConversions*/ false); 14412 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14413 // If explicit template arguments were provided, we can't call a 14414 // non-template member function. 14415 if (TemplateArgs) 14416 continue; 14417 14418 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14419 ObjectClassification, Args, CandidateSet, 14420 /*SuppressUserConversions=*/false); 14421 } else { 14422 AddMethodTemplateCandidate( 14423 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14424 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14425 /*SuppressUserConversions=*/false); 14426 } 14427 } 14428 14429 DeclarationName DeclName = UnresExpr->getMemberName(); 14430 14431 UnbridgedCasts.restore(); 14432 14433 OverloadCandidateSet::iterator Best; 14434 bool Succeeded = false; 14435 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14436 Best)) { 14437 case OR_Success: 14438 Method = cast<CXXMethodDecl>(Best->Function); 14439 FoundDecl = Best->FoundDecl; 14440 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14441 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14442 break; 14443 // If FoundDecl is different from Method (such as if one is a template 14444 // and the other a specialization), make sure DiagnoseUseOfDecl is 14445 // called on both. 14446 // FIXME: This would be more comprehensively addressed by modifying 14447 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14448 // being used. 14449 if (Method != FoundDecl.getDecl() && 14450 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14451 break; 14452 Succeeded = true; 14453 break; 14454 14455 case OR_No_Viable_Function: 14456 CandidateSet.NoteCandidates( 14457 PartialDiagnosticAt( 14458 UnresExpr->getMemberLoc(), 14459 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14460 << DeclName << MemExprE->getSourceRange()), 14461 *this, OCD_AllCandidates, Args); 14462 break; 14463 case OR_Ambiguous: 14464 CandidateSet.NoteCandidates( 14465 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14466 PDiag(diag::err_ovl_ambiguous_member_call) 14467 << DeclName << MemExprE->getSourceRange()), 14468 *this, OCD_AmbiguousCandidates, Args); 14469 break; 14470 case OR_Deleted: 14471 CandidateSet.NoteCandidates( 14472 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14473 PDiag(diag::err_ovl_deleted_member_call) 14474 << DeclName << MemExprE->getSourceRange()), 14475 *this, OCD_AllCandidates, Args); 14476 break; 14477 } 14478 // Overload resolution fails, try to recover. 14479 if (!Succeeded) 14480 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14481 14482 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14483 14484 // If overload resolution picked a static member, build a 14485 // non-member call based on that function. 14486 if (Method->isStatic()) { 14487 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 14488 ExecConfig, IsExecConfig); 14489 } 14490 14491 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14492 } 14493 14494 QualType ResultType = Method->getReturnType(); 14495 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14496 ResultType = ResultType.getNonLValueExprType(Context); 14497 14498 assert(Method && "Member call to something that isn't a method?"); 14499 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14500 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14501 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14502 CurFPFeatureOverrides(), Proto->getNumParams()); 14503 14504 // Check for a valid return type. 14505 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14506 TheCall, Method)) 14507 return BuildRecoveryExpr(ResultType); 14508 14509 // Convert the object argument (for a non-static member function call). 14510 // We only need to do this if there was actually an overload; otherwise 14511 // it was done at lookup. 14512 if (!Method->isStatic()) { 14513 ExprResult ObjectArg = 14514 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14515 FoundDecl, Method); 14516 if (ObjectArg.isInvalid()) 14517 return ExprError(); 14518 MemExpr->setBase(ObjectArg.get()); 14519 } 14520 14521 // Convert the rest of the arguments 14522 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14523 RParenLoc)) 14524 return BuildRecoveryExpr(ResultType); 14525 14526 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14527 14528 if (CheckFunctionCall(Method, TheCall, Proto)) 14529 return ExprError(); 14530 14531 // In the case the method to call was not selected by the overloading 14532 // resolution process, we still need to handle the enable_if attribute. Do 14533 // that here, so it will not hide previous -- and more relevant -- errors. 14534 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14535 if (const EnableIfAttr *Attr = 14536 CheckEnableIf(Method, LParenLoc, Args, true)) { 14537 Diag(MemE->getMemberLoc(), 14538 diag::err_ovl_no_viable_member_function_in_call) 14539 << Method << Method->getSourceRange(); 14540 Diag(Method->getLocation(), 14541 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14542 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14543 return ExprError(); 14544 } 14545 } 14546 14547 if ((isa<CXXConstructorDecl>(CurContext) || 14548 isa<CXXDestructorDecl>(CurContext)) && 14549 TheCall->getMethodDecl()->isPure()) { 14550 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14551 14552 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14553 MemExpr->performsVirtualDispatch(getLangOpts())) { 14554 Diag(MemExpr->getBeginLoc(), 14555 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14556 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14557 << MD->getParent(); 14558 14559 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14560 if (getLangOpts().AppleKext) 14561 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14562 << MD->getParent() << MD->getDeclName(); 14563 } 14564 } 14565 14566 if (CXXDestructorDecl *DD = 14567 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14568 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14569 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14570 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14571 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14572 MemExpr->getMemberLoc()); 14573 } 14574 14575 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14576 TheCall->getMethodDecl()); 14577 } 14578 14579 /// BuildCallToObjectOfClassType - Build a call to an object of class 14580 /// type (C++ [over.call.object]), which can end up invoking an 14581 /// overloaded function call operator (@c operator()) or performing a 14582 /// user-defined conversion on the object argument. 14583 ExprResult 14584 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14585 SourceLocation LParenLoc, 14586 MultiExprArg Args, 14587 SourceLocation RParenLoc) { 14588 if (checkPlaceholderForOverload(*this, Obj)) 14589 return ExprError(); 14590 ExprResult Object = Obj; 14591 14592 UnbridgedCastsSet UnbridgedCasts; 14593 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14594 return ExprError(); 14595 14596 assert(Object.get()->getType()->isRecordType() && 14597 "Requires object type argument"); 14598 14599 // C++ [over.call.object]p1: 14600 // If the primary-expression E in the function call syntax 14601 // evaluates to a class object of type "cv T", then the set of 14602 // candidate functions includes at least the function call 14603 // operators of T. The function call operators of T are obtained by 14604 // ordinary lookup of the name operator() in the context of 14605 // (E).operator(). 14606 OverloadCandidateSet CandidateSet(LParenLoc, 14607 OverloadCandidateSet::CSK_Operator); 14608 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14609 14610 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14611 diag::err_incomplete_object_call, Object.get())) 14612 return true; 14613 14614 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14615 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14616 LookupQualifiedName(R, Record->getDecl()); 14617 R.suppressDiagnostics(); 14618 14619 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14620 Oper != OperEnd; ++Oper) { 14621 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14622 Object.get()->Classify(Context), Args, CandidateSet, 14623 /*SuppressUserConversion=*/false); 14624 } 14625 14626 // C++ [over.call.object]p2: 14627 // In addition, for each (non-explicit in C++0x) conversion function 14628 // declared in T of the form 14629 // 14630 // operator conversion-type-id () cv-qualifier; 14631 // 14632 // where cv-qualifier is the same cv-qualification as, or a 14633 // greater cv-qualification than, cv, and where conversion-type-id 14634 // denotes the type "pointer to function of (P1,...,Pn) returning 14635 // R", or the type "reference to pointer to function of 14636 // (P1,...,Pn) returning R", or the type "reference to function 14637 // of (P1,...,Pn) returning R", a surrogate call function [...] 14638 // is also considered as a candidate function. Similarly, 14639 // surrogate call functions are added to the set of candidate 14640 // functions for each conversion function declared in an 14641 // accessible base class provided the function is not hidden 14642 // within T by another intervening declaration. 14643 const auto &Conversions = 14644 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14645 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14646 NamedDecl *D = *I; 14647 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14648 if (isa<UsingShadowDecl>(D)) 14649 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14650 14651 // Skip over templated conversion functions; they aren't 14652 // surrogates. 14653 if (isa<FunctionTemplateDecl>(D)) 14654 continue; 14655 14656 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14657 if (!Conv->isExplicit()) { 14658 // Strip the reference type (if any) and then the pointer type (if 14659 // any) to get down to what might be a function type. 14660 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14661 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14662 ConvType = ConvPtrType->getPointeeType(); 14663 14664 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14665 { 14666 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14667 Object.get(), Args, CandidateSet); 14668 } 14669 } 14670 } 14671 14672 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14673 14674 // Perform overload resolution. 14675 OverloadCandidateSet::iterator Best; 14676 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14677 Best)) { 14678 case OR_Success: 14679 // Overload resolution succeeded; we'll build the appropriate call 14680 // below. 14681 break; 14682 14683 case OR_No_Viable_Function: { 14684 PartialDiagnostic PD = 14685 CandidateSet.empty() 14686 ? (PDiag(diag::err_ovl_no_oper) 14687 << Object.get()->getType() << /*call*/ 1 14688 << Object.get()->getSourceRange()) 14689 : (PDiag(diag::err_ovl_no_viable_object_call) 14690 << Object.get()->getType() << Object.get()->getSourceRange()); 14691 CandidateSet.NoteCandidates( 14692 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14693 OCD_AllCandidates, Args); 14694 break; 14695 } 14696 case OR_Ambiguous: 14697 CandidateSet.NoteCandidates( 14698 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14699 PDiag(diag::err_ovl_ambiguous_object_call) 14700 << Object.get()->getType() 14701 << Object.get()->getSourceRange()), 14702 *this, OCD_AmbiguousCandidates, Args); 14703 break; 14704 14705 case OR_Deleted: 14706 CandidateSet.NoteCandidates( 14707 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14708 PDiag(diag::err_ovl_deleted_object_call) 14709 << Object.get()->getType() 14710 << Object.get()->getSourceRange()), 14711 *this, OCD_AllCandidates, Args); 14712 break; 14713 } 14714 14715 if (Best == CandidateSet.end()) 14716 return true; 14717 14718 UnbridgedCasts.restore(); 14719 14720 if (Best->Function == nullptr) { 14721 // Since there is no function declaration, this is one of the 14722 // surrogate candidates. Dig out the conversion function. 14723 CXXConversionDecl *Conv 14724 = cast<CXXConversionDecl>( 14725 Best->Conversions[0].UserDefined.ConversionFunction); 14726 14727 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14728 Best->FoundDecl); 14729 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14730 return ExprError(); 14731 assert(Conv == Best->FoundDecl.getDecl() && 14732 "Found Decl & conversion-to-functionptr should be same, right?!"); 14733 // We selected one of the surrogate functions that converts the 14734 // object parameter to a function pointer. Perform the conversion 14735 // on the object argument, then let BuildCallExpr finish the job. 14736 14737 // Create an implicit member expr to refer to the conversion operator. 14738 // and then call it. 14739 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14740 Conv, HadMultipleCandidates); 14741 if (Call.isInvalid()) 14742 return ExprError(); 14743 // Record usage of conversion in an implicit cast. 14744 Call = ImplicitCastExpr::Create( 14745 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14746 nullptr, VK_PRValue, CurFPFeatureOverrides()); 14747 14748 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14749 } 14750 14751 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14752 14753 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14754 // that calls this method, using Object for the implicit object 14755 // parameter and passing along the remaining arguments. 14756 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14757 14758 // An error diagnostic has already been printed when parsing the declaration. 14759 if (Method->isInvalidDecl()) 14760 return ExprError(); 14761 14762 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14763 unsigned NumParams = Proto->getNumParams(); 14764 14765 DeclarationNameInfo OpLocInfo( 14766 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14767 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14768 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14769 Obj, HadMultipleCandidates, 14770 OpLocInfo.getLoc(), 14771 OpLocInfo.getInfo()); 14772 if (NewFn.isInvalid()) 14773 return true; 14774 14775 SmallVector<Expr *, 8> MethodArgs; 14776 MethodArgs.reserve(NumParams + 1); 14777 14778 bool IsError = false; 14779 14780 // Initialize the implicit object parameter. 14781 ExprResult ObjRes = 14782 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14783 Best->FoundDecl, Method); 14784 if (ObjRes.isInvalid()) 14785 IsError = true; 14786 else 14787 Object = ObjRes; 14788 MethodArgs.push_back(Object.get()); 14789 14790 IsError |= PrepareArgumentsForCallToObjectOfClassType( 14791 *this, MethodArgs, Method, Args, LParenLoc); 14792 14793 // If this is a variadic call, handle args passed through "...". 14794 if (Proto->isVariadic()) { 14795 // Promote the arguments (C99 6.5.2.2p7). 14796 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14797 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14798 nullptr); 14799 IsError |= Arg.isInvalid(); 14800 MethodArgs.push_back(Arg.get()); 14801 } 14802 } 14803 14804 if (IsError) 14805 return true; 14806 14807 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14808 14809 // Once we've built TheCall, all of the expressions are properly owned. 14810 QualType ResultTy = Method->getReturnType(); 14811 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14812 ResultTy = ResultTy.getNonLValueExprType(Context); 14813 14814 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14815 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14816 CurFPFeatureOverrides()); 14817 14818 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14819 return true; 14820 14821 if (CheckFunctionCall(Method, TheCall, Proto)) 14822 return true; 14823 14824 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14825 } 14826 14827 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14828 /// (if one exists), where @c Base is an expression of class type and 14829 /// @c Member is the name of the member we're trying to find. 14830 ExprResult 14831 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14832 bool *NoArrowOperatorFound) { 14833 assert(Base->getType()->isRecordType() && 14834 "left-hand side must have class type"); 14835 14836 if (checkPlaceholderForOverload(*this, Base)) 14837 return ExprError(); 14838 14839 SourceLocation Loc = Base->getExprLoc(); 14840 14841 // C++ [over.ref]p1: 14842 // 14843 // [...] An expression x->m is interpreted as (x.operator->())->m 14844 // for a class object x of type T if T::operator->() exists and if 14845 // the operator is selected as the best match function by the 14846 // overload resolution mechanism (13.3). 14847 DeclarationName OpName = 14848 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14849 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14850 14851 if (RequireCompleteType(Loc, Base->getType(), 14852 diag::err_typecheck_incomplete_tag, Base)) 14853 return ExprError(); 14854 14855 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14856 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14857 R.suppressDiagnostics(); 14858 14859 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14860 Oper != OperEnd; ++Oper) { 14861 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14862 None, CandidateSet, /*SuppressUserConversion=*/false); 14863 } 14864 14865 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14866 14867 // Perform overload resolution. 14868 OverloadCandidateSet::iterator Best; 14869 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14870 case OR_Success: 14871 // Overload resolution succeeded; we'll build the call below. 14872 break; 14873 14874 case OR_No_Viable_Function: { 14875 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14876 if (CandidateSet.empty()) { 14877 QualType BaseType = Base->getType(); 14878 if (NoArrowOperatorFound) { 14879 // Report this specific error to the caller instead of emitting a 14880 // diagnostic, as requested. 14881 *NoArrowOperatorFound = true; 14882 return ExprError(); 14883 } 14884 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14885 << BaseType << Base->getSourceRange(); 14886 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14887 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14888 << FixItHint::CreateReplacement(OpLoc, "."); 14889 } 14890 } else 14891 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14892 << "operator->" << Base->getSourceRange(); 14893 CandidateSet.NoteCandidates(*this, Base, Cands); 14894 return ExprError(); 14895 } 14896 case OR_Ambiguous: 14897 CandidateSet.NoteCandidates( 14898 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14899 << "->" << Base->getType() 14900 << Base->getSourceRange()), 14901 *this, OCD_AmbiguousCandidates, Base); 14902 return ExprError(); 14903 14904 case OR_Deleted: 14905 CandidateSet.NoteCandidates( 14906 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14907 << "->" << Base->getSourceRange()), 14908 *this, OCD_AllCandidates, Base); 14909 return ExprError(); 14910 } 14911 14912 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14913 14914 // Convert the object parameter. 14915 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14916 ExprResult BaseResult = 14917 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14918 Best->FoundDecl, Method); 14919 if (BaseResult.isInvalid()) 14920 return ExprError(); 14921 Base = BaseResult.get(); 14922 14923 // Build the operator call. 14924 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14925 Base, HadMultipleCandidates, OpLoc); 14926 if (FnExpr.isInvalid()) 14927 return ExprError(); 14928 14929 QualType ResultTy = Method->getReturnType(); 14930 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14931 ResultTy = ResultTy.getNonLValueExprType(Context); 14932 CXXOperatorCallExpr *TheCall = 14933 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14934 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14935 14936 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14937 return ExprError(); 14938 14939 if (CheckFunctionCall(Method, TheCall, 14940 Method->getType()->castAs<FunctionProtoType>())) 14941 return ExprError(); 14942 14943 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14944 } 14945 14946 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14947 /// a literal operator described by the provided lookup results. 14948 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14949 DeclarationNameInfo &SuffixInfo, 14950 ArrayRef<Expr*> Args, 14951 SourceLocation LitEndLoc, 14952 TemplateArgumentListInfo *TemplateArgs) { 14953 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14954 14955 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14956 OverloadCandidateSet::CSK_Normal); 14957 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14958 TemplateArgs); 14959 14960 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14961 14962 // Perform overload resolution. This will usually be trivial, but might need 14963 // to perform substitutions for a literal operator template. 14964 OverloadCandidateSet::iterator Best; 14965 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14966 case OR_Success: 14967 case OR_Deleted: 14968 break; 14969 14970 case OR_No_Viable_Function: 14971 CandidateSet.NoteCandidates( 14972 PartialDiagnosticAt(UDSuffixLoc, 14973 PDiag(diag::err_ovl_no_viable_function_in_call) 14974 << R.getLookupName()), 14975 *this, OCD_AllCandidates, Args); 14976 return ExprError(); 14977 14978 case OR_Ambiguous: 14979 CandidateSet.NoteCandidates( 14980 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14981 << R.getLookupName()), 14982 *this, OCD_AmbiguousCandidates, Args); 14983 return ExprError(); 14984 } 14985 14986 FunctionDecl *FD = Best->Function; 14987 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14988 nullptr, HadMultipleCandidates, 14989 SuffixInfo.getLoc(), 14990 SuffixInfo.getInfo()); 14991 if (Fn.isInvalid()) 14992 return true; 14993 14994 // Check the argument types. This should almost always be a no-op, except 14995 // that array-to-pointer decay is applied to string literals. 14996 Expr *ConvArgs[2]; 14997 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14998 ExprResult InputInit = PerformCopyInitialization( 14999 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 15000 SourceLocation(), Args[ArgIdx]); 15001 if (InputInit.isInvalid()) 15002 return true; 15003 ConvArgs[ArgIdx] = InputInit.get(); 15004 } 15005 15006 QualType ResultTy = FD->getReturnType(); 15007 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15008 ResultTy = ResultTy.getNonLValueExprType(Context); 15009 15010 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 15011 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 15012 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 15013 15014 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 15015 return ExprError(); 15016 15017 if (CheckFunctionCall(FD, UDL, nullptr)) 15018 return ExprError(); 15019 15020 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 15021 } 15022 15023 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 15024 /// given LookupResult is non-empty, it is assumed to describe a member which 15025 /// will be invoked. Otherwise, the function will be found via argument 15026 /// dependent lookup. 15027 /// CallExpr is set to a valid expression and FRS_Success returned on success, 15028 /// otherwise CallExpr is set to ExprError() and some non-success value 15029 /// is returned. 15030 Sema::ForRangeStatus 15031 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 15032 SourceLocation RangeLoc, 15033 const DeclarationNameInfo &NameInfo, 15034 LookupResult &MemberLookup, 15035 OverloadCandidateSet *CandidateSet, 15036 Expr *Range, ExprResult *CallExpr) { 15037 Scope *S = nullptr; 15038 15039 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 15040 if (!MemberLookup.empty()) { 15041 ExprResult MemberRef = 15042 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 15043 /*IsPtr=*/false, CXXScopeSpec(), 15044 /*TemplateKWLoc=*/SourceLocation(), 15045 /*FirstQualifierInScope=*/nullptr, 15046 MemberLookup, 15047 /*TemplateArgs=*/nullptr, S); 15048 if (MemberRef.isInvalid()) { 15049 *CallExpr = ExprError(); 15050 return FRS_DiagnosticIssued; 15051 } 15052 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 15053 if (CallExpr->isInvalid()) { 15054 *CallExpr = ExprError(); 15055 return FRS_DiagnosticIssued; 15056 } 15057 } else { 15058 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 15059 NestedNameSpecifierLoc(), 15060 NameInfo, UnresolvedSet<0>()); 15061 if (FnR.isInvalid()) 15062 return FRS_DiagnosticIssued; 15063 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 15064 15065 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 15066 CandidateSet, CallExpr); 15067 if (CandidateSet->empty() || CandidateSetError) { 15068 *CallExpr = ExprError(); 15069 return FRS_NoViableFunction; 15070 } 15071 OverloadCandidateSet::iterator Best; 15072 OverloadingResult OverloadResult = 15073 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 15074 15075 if (OverloadResult == OR_No_Viable_Function) { 15076 *CallExpr = ExprError(); 15077 return FRS_NoViableFunction; 15078 } 15079 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 15080 Loc, nullptr, CandidateSet, &Best, 15081 OverloadResult, 15082 /*AllowTypoCorrection=*/false); 15083 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 15084 *CallExpr = ExprError(); 15085 return FRS_DiagnosticIssued; 15086 } 15087 } 15088 return FRS_Success; 15089 } 15090 15091 15092 /// FixOverloadedFunctionReference - E is an expression that refers to 15093 /// a C++ overloaded function (possibly with some parentheses and 15094 /// perhaps a '&' around it). We have resolved the overloaded function 15095 /// to the function declaration Fn, so patch up the expression E to 15096 /// refer (possibly indirectly) to Fn. Returns the new expr. 15097 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15098 FunctionDecl *Fn) { 15099 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15100 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15101 Found, Fn); 15102 if (SubExpr == PE->getSubExpr()) 15103 return PE; 15104 15105 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15106 } 15107 15108 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15109 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15110 Found, Fn); 15111 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15112 SubExpr->getType()) && 15113 "Implicit cast type cannot be determined from overload"); 15114 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15115 if (SubExpr == ICE->getSubExpr()) 15116 return ICE; 15117 15118 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15119 SubExpr, nullptr, ICE->getValueKind(), 15120 CurFPFeatureOverrides()); 15121 } 15122 15123 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15124 if (!GSE->isResultDependent()) { 15125 Expr *SubExpr = 15126 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15127 if (SubExpr == GSE->getResultExpr()) 15128 return GSE; 15129 15130 // Replace the resulting type information before rebuilding the generic 15131 // selection expression. 15132 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15133 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15134 unsigned ResultIdx = GSE->getResultIndex(); 15135 AssocExprs[ResultIdx] = SubExpr; 15136 15137 return GenericSelectionExpr::Create( 15138 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15139 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15140 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15141 ResultIdx); 15142 } 15143 // Rather than fall through to the unreachable, return the original generic 15144 // selection expression. 15145 return GSE; 15146 } 15147 15148 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15149 assert(UnOp->getOpcode() == UO_AddrOf && 15150 "Can only take the address of an overloaded function"); 15151 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15152 if (Method->isStatic()) { 15153 // Do nothing: static member functions aren't any different 15154 // from non-member functions. 15155 } else { 15156 // Fix the subexpression, which really has to be an 15157 // UnresolvedLookupExpr holding an overloaded member function 15158 // or template. 15159 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15160 Found, Fn); 15161 if (SubExpr == UnOp->getSubExpr()) 15162 return UnOp; 15163 15164 assert(isa<DeclRefExpr>(SubExpr) 15165 && "fixed to something other than a decl ref"); 15166 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15167 && "fixed to a member ref with no nested name qualifier"); 15168 15169 // We have taken the address of a pointer to member 15170 // function. Perform the computation here so that we get the 15171 // appropriate pointer to member type. 15172 QualType ClassType 15173 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15174 QualType MemPtrType 15175 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15176 // Under the MS ABI, lock down the inheritance model now. 15177 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15178 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15179 15180 return UnaryOperator::Create( 15181 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, 15182 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15183 } 15184 } 15185 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15186 Found, Fn); 15187 if (SubExpr == UnOp->getSubExpr()) 15188 return UnOp; 15189 15190 return UnaryOperator::Create( 15191 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()), 15192 VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false, 15193 CurFPFeatureOverrides()); 15194 } 15195 15196 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15197 // FIXME: avoid copy. 15198 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15199 if (ULE->hasExplicitTemplateArgs()) { 15200 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15201 TemplateArgs = &TemplateArgsBuffer; 15202 } 15203 15204 DeclRefExpr *DRE = 15205 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15206 ULE->getQualifierLoc(), Found.getDecl(), 15207 ULE->getTemplateKeywordLoc(), TemplateArgs); 15208 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15209 return DRE; 15210 } 15211 15212 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15213 // FIXME: avoid copy. 15214 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15215 if (MemExpr->hasExplicitTemplateArgs()) { 15216 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15217 TemplateArgs = &TemplateArgsBuffer; 15218 } 15219 15220 Expr *Base; 15221 15222 // If we're filling in a static method where we used to have an 15223 // implicit member access, rewrite to a simple decl ref. 15224 if (MemExpr->isImplicitAccess()) { 15225 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15226 DeclRefExpr *DRE = BuildDeclRefExpr( 15227 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15228 MemExpr->getQualifierLoc(), Found.getDecl(), 15229 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15230 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15231 return DRE; 15232 } else { 15233 SourceLocation Loc = MemExpr->getMemberLoc(); 15234 if (MemExpr->getQualifier()) 15235 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15236 Base = 15237 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15238 } 15239 } else 15240 Base = MemExpr->getBase(); 15241 15242 ExprValueKind valueKind; 15243 QualType type; 15244 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15245 valueKind = VK_LValue; 15246 type = Fn->getType(); 15247 } else { 15248 valueKind = VK_PRValue; 15249 type = Context.BoundMemberTy; 15250 } 15251 15252 return BuildMemberExpr( 15253 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15254 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15255 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15256 type, valueKind, OK_Ordinary, TemplateArgs); 15257 } 15258 15259 llvm_unreachable("Invalid reference to overloaded function"); 15260 } 15261 15262 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15263 DeclAccessPair Found, 15264 FunctionDecl *Fn) { 15265 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15266 } 15267 15268 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 15269 FunctionDecl *Function) { 15270 if (!PartialOverloading || !Function) 15271 return true; 15272 if (Function->isVariadic()) 15273 return false; 15274 if (const auto *Proto = 15275 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 15276 if (Proto->isTemplateVariadic()) 15277 return false; 15278 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 15279 if (const auto *Proto = 15280 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 15281 if (Proto->isTemplateVariadic()) 15282 return false; 15283 return true; 15284 } 15285