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/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.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/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 const Expr *Base, bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 DeclRefExpr *DRE = new (S.Context) 64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 65 if (HadMultipleCandidates) 66 DRE->setHadMultipleCandidates(true); 67 68 S.MarkDeclRefReferenced(DRE, Base); 69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 71 S.ResolveExceptionSpec(Loc, FPT); 72 DRE->setType(Fn->getType()); 73 } 74 } 75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 76 CK_FunctionToPointerDecay); 77 } 78 79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle, 83 bool AllowObjCWritebackConversion); 84 85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 86 QualType &ToType, 87 bool InOverloadResolution, 88 StandardConversionSequence &SCS, 89 bool CStyle); 90 static OverloadingResult 91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 92 UserDefinedConversionSequence& User, 93 OverloadCandidateSet& Conversions, 94 bool AllowExplicit, 95 bool AllowObjCConversionOnExplicit); 96 97 98 static ImplicitConversionSequence::CompareKind 99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 100 const StandardConversionSequence& SCS1, 101 const StandardConversionSequence& SCS2); 102 103 static ImplicitConversionSequence::CompareKind 104 CompareQualificationConversions(Sema &S, 105 const StandardConversionSequence& SCS1, 106 const StandardConversionSequence& SCS2); 107 108 static ImplicitConversionSequence::CompareKind 109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 110 const StandardConversionSequence& SCS1, 111 const StandardConversionSequence& SCS2); 112 113 /// GetConversionRank - Retrieve the implicit conversion rank 114 /// corresponding to the given implicit conversion kind. 115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 116 static const ImplicitConversionRank 117 Rank[(int)ICK_Num_Conversion_Kinds] = { 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Promotion, 125 ICR_Promotion, 126 ICR_Promotion, 127 ICR_Conversion, 128 ICR_Conversion, 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_OCL_Scalar_Widening, 138 ICR_Complex_Real_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Writeback_Conversion, 142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 143 // it was omitted by the patch that added 144 // ICK_Zero_Event_Conversion 145 ICR_C_Conversion, 146 ICR_C_Conversion_Extension 147 }; 148 return Rank[(int)Kind]; 149 } 150 151 /// GetImplicitConversionName - Return the name of this kind of 152 /// implicit conversion. 153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 155 "No conversion", 156 "Lvalue-to-rvalue", 157 "Array-to-pointer", 158 "Function-to-pointer", 159 "Function pointer conversion", 160 "Qualification", 161 "Integral promotion", 162 "Floating point promotion", 163 "Complex promotion", 164 "Integral conversion", 165 "Floating conversion", 166 "Complex conversion", 167 "Floating-integral conversion", 168 "Pointer conversion", 169 "Pointer-to-member conversion", 170 "Boolean conversion", 171 "Compatible-types conversion", 172 "Derived-to-base conversion", 173 "Vector conversion", 174 "Vector splat", 175 "Complex-real conversion", 176 "Block Pointer conversion", 177 "Transparent Union Conversion", 178 "Writeback conversion", 179 "OpenCL Zero Event Conversion", 180 "C specific type conversion", 181 "Incompatible pointer conversion" 182 }; 183 return Name[Kind]; 184 } 185 186 /// StandardConversionSequence - Set the standard conversion 187 /// sequence to the identity conversion. 188 void StandardConversionSequence::setAsIdentityConversion() { 189 First = ICK_Identity; 190 Second = ICK_Identity; 191 Third = ICK_Identity; 192 DeprecatedStringLiteralToCharPtr = false; 193 QualificationIncludesObjCLifetime = false; 194 ReferenceBinding = false; 195 DirectBinding = false; 196 IsLvalueReference = true; 197 BindsToFunctionLvalue = false; 198 BindsToRvalue = false; 199 BindsImplicitObjectArgumentWithoutRefQualifier = false; 200 ObjCLifetimeConversionBinding = false; 201 CopyConstructor = nullptr; 202 } 203 204 /// getRank - Retrieve the rank of this standard conversion sequence 205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 206 /// implicit conversions. 207 ImplicitConversionRank StandardConversionSequence::getRank() const { 208 ImplicitConversionRank Rank = ICR_Exact_Match; 209 if (GetConversionRank(First) > Rank) 210 Rank = GetConversionRank(First); 211 if (GetConversionRank(Second) > Rank) 212 Rank = GetConversionRank(Second); 213 if (GetConversionRank(Third) > Rank) 214 Rank = GetConversionRank(Third); 215 return Rank; 216 } 217 218 /// isPointerConversionToBool - Determines whether this conversion is 219 /// a conversion of a pointer or pointer-to-member to bool. This is 220 /// used as part of the ranking of standard conversion sequences 221 /// (C++ 13.3.3.2p4). 222 bool StandardConversionSequence::isPointerConversionToBool() const { 223 // Note that FromType has not necessarily been transformed by the 224 // array-to-pointer or function-to-pointer implicit conversions, so 225 // check for their presence as well as checking whether FromType is 226 // a pointer. 227 if (getToType(1)->isBooleanType() && 228 (getFromType()->isPointerType() || 229 getFromType()->isMemberPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237 } 238 239 /// isPointerConversionToVoidPointer - Determines whether this 240 /// conversion is a conversion of a pointer to a void pointer. This is 241 /// used as part of the ranking of standard conversion sequences (C++ 242 /// 13.3.3.2p4). 243 bool 244 StandardConversionSequence:: 245 isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260 } 261 262 /// Skip any implicit casts which could be either part of a narrowing conversion 263 /// or after one in an implicit conversion. 264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 265 const Expr *Converted) { 266 // We can have cleanups wrapping the converted expression; these need to be 267 // preserved so that destructors run if necessary. 268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 269 Expr *Inner = 270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 272 EWC->getObjects()); 273 } 274 275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 276 switch (ICE->getCastKind()) { 277 case CK_NoOp: 278 case CK_IntegralCast: 279 case CK_IntegralToBoolean: 280 case CK_IntegralToFloating: 281 case CK_BooleanToSignedIntegral: 282 case CK_FloatingToIntegral: 283 case CK_FloatingToBoolean: 284 case CK_FloatingCast: 285 Converted = ICE->getSubExpr(); 286 continue; 287 288 default: 289 return Converted; 290 } 291 } 292 293 return Converted; 294 } 295 296 /// Check if this standard conversion sequence represents a narrowing 297 /// conversion, according to C++11 [dcl.init.list]p7. 298 /// 299 /// \param Ctx The AST context. 300 /// \param Converted The result of applying this standard conversion sequence. 301 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 302 /// value of the expression prior to the narrowing conversion. 303 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 304 /// type of the expression prior to the narrowing conversion. 305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 306 /// from floating point types to integral types should be ignored. 307 NarrowingKind StandardConversionSequence::getNarrowingKind( 308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 310 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 311 312 // C++11 [dcl.init.list]p7: 313 // A narrowing conversion is an implicit conversion ... 314 QualType FromType = getToType(0); 315 QualType ToType = getToType(1); 316 317 // A conversion to an enumeration type is narrowing if the conversion to 318 // the underlying type is narrowing. This only arises for expressions of 319 // the form 'Enum{init}'. 320 if (auto *ET = ToType->getAs<EnumType>()) 321 ToType = ET->getDecl()->getIntegerType(); 322 323 switch (Second) { 324 // 'bool' is an integral type; dispatch to the right place to handle it. 325 case ICK_Boolean_Conversion: 326 if (FromType->isRealFloatingType()) 327 goto FloatingIntegralConversion; 328 if (FromType->isIntegralOrUnscopedEnumerationType()) 329 goto IntegralConversion; 330 // Boolean conversions can be from pointers and pointers to members 331 // [conv.bool], and those aren't considered narrowing conversions. 332 return NK_Not_Narrowing; 333 334 // -- from a floating-point type to an integer type, or 335 // 336 // -- from an integer type or unscoped enumeration type to a floating-point 337 // type, except where the source is a constant expression and the actual 338 // value after conversion will fit into the target type and will produce 339 // the original value when converted back to the original type, or 340 case ICK_Floating_Integral: 341 FloatingIntegralConversion: 342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 343 return NK_Type_Narrowing; 344 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 345 ToType->isRealFloatingType()) { 346 if (IgnoreFloatToIntegralConversion) 347 return NK_Not_Narrowing; 348 llvm::APSInt IntConstantValue; 349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 350 assert(Initializer && "Unknown conversion expression"); 351 352 // If it's value-dependent, we can't tell whether it's narrowing. 353 if (Initializer->isValueDependent()) 354 return NK_Dependent_Narrowing; 355 356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 357 // Convert the integer to the floating type. 358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 360 llvm::APFloat::rmNearestTiesToEven); 361 // And back. 362 llvm::APSInt ConvertedValue = IntConstantValue; 363 bool ignored; 364 Result.convertToInteger(ConvertedValue, 365 llvm::APFloat::rmTowardZero, &ignored); 366 // If the resulting value is different, this was a narrowing conversion. 367 if (IntConstantValue != ConvertedValue) { 368 ConstantValue = APValue(IntConstantValue); 369 ConstantType = Initializer->getType(); 370 return NK_Constant_Narrowing; 371 } 372 } else { 373 // Variables are always narrowings. 374 return NK_Variable_Narrowing; 375 } 376 } 377 return NK_Not_Narrowing; 378 379 // -- from long double to double or float, or from double to float, except 380 // where the source is a constant expression and the actual value after 381 // conversion is within the range of values that can be represented (even 382 // if it cannot be represented exactly), or 383 case ICK_Floating_Conversion: 384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 386 // FromType is larger than ToType. 387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 388 389 // If it's value-dependent, we can't tell whether it's narrowing. 390 if (Initializer->isValueDependent()) 391 return NK_Dependent_Narrowing; 392 393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 394 // Constant! 395 assert(ConstantValue.isFloat()); 396 llvm::APFloat FloatVal = ConstantValue.getFloat(); 397 // Convert the source value into the target type. 398 bool ignored; 399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 400 Ctx.getFloatTypeSemantics(ToType), 401 llvm::APFloat::rmNearestTiesToEven, &ignored); 402 // If there was no overflow, the source value is within the range of 403 // values that can be represented. 404 if (ConvertStatus & llvm::APFloat::opOverflow) { 405 ConstantType = Initializer->getType(); 406 return NK_Constant_Narrowing; 407 } 408 } else { 409 return NK_Variable_Narrowing; 410 } 411 } 412 return NK_Not_Narrowing; 413 414 // -- from an integer type or unscoped enumeration type to an integer type 415 // that cannot represent all the values of the original type, except where 416 // the source is a constant expression and the actual value after 417 // conversion will fit into the target type and will produce the original 418 // value when converted back to the original type. 419 case ICK_Integral_Conversion: 420 IntegralConversion: { 421 assert(FromType->isIntegralOrUnscopedEnumerationType()); 422 assert(ToType->isIntegralOrUnscopedEnumerationType()); 423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 424 const unsigned FromWidth = Ctx.getIntWidth(FromType); 425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 426 const unsigned ToWidth = Ctx.getIntWidth(ToType); 427 428 if (FromWidth > ToWidth || 429 (FromWidth == ToWidth && FromSigned != ToSigned) || 430 (FromSigned && !ToSigned)) { 431 // Not all values of FromType can be represented in ToType. 432 llvm::APSInt InitializerValue; 433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 434 435 // If it's value-dependent, we can't tell whether it's narrowing. 436 if (Initializer->isValueDependent()) 437 return NK_Dependent_Narrowing; 438 439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 440 // Such conversions on variables are always narrowing. 441 return NK_Variable_Narrowing; 442 } 443 bool Narrowing = false; 444 if (FromWidth < ToWidth) { 445 // Negative -> unsigned is narrowing. Otherwise, more bits is never 446 // narrowing. 447 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 448 Narrowing = true; 449 } else { 450 // Add a bit to the InitializerValue so we don't have to worry about 451 // signed vs. unsigned comparisons. 452 InitializerValue = InitializerValue.extend( 453 InitializerValue.getBitWidth() + 1); 454 // Convert the initializer to and from the target width and signed-ness. 455 llvm::APSInt ConvertedValue = InitializerValue; 456 ConvertedValue = ConvertedValue.trunc(ToWidth); 457 ConvertedValue.setIsSigned(ToSigned); 458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 459 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 460 // If the result is different, this was a narrowing conversion. 461 if (ConvertedValue != InitializerValue) 462 Narrowing = true; 463 } 464 if (Narrowing) { 465 ConstantType = Initializer->getType(); 466 ConstantValue = APValue(InitializerValue); 467 return NK_Constant_Narrowing; 468 } 469 } 470 return NK_Not_Narrowing; 471 } 472 473 default: 474 // Other kinds of conversions are not narrowings. 475 return NK_Not_Narrowing; 476 } 477 } 478 479 /// dump - Print this standard conversion sequence to standard 480 /// error. Useful for debugging overloading issues. 481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 482 raw_ostream &OS = llvm::errs(); 483 bool PrintedSomething = false; 484 if (First != ICK_Identity) { 485 OS << GetImplicitConversionName(First); 486 PrintedSomething = true; 487 } 488 489 if (Second != ICK_Identity) { 490 if (PrintedSomething) { 491 OS << " -> "; 492 } 493 OS << GetImplicitConversionName(Second); 494 495 if (CopyConstructor) { 496 OS << " (by copy constructor)"; 497 } else if (DirectBinding) { 498 OS << " (direct reference binding)"; 499 } else if (ReferenceBinding) { 500 OS << " (reference binding)"; 501 } 502 PrintedSomething = true; 503 } 504 505 if (Third != ICK_Identity) { 506 if (PrintedSomething) { 507 OS << " -> "; 508 } 509 OS << GetImplicitConversionName(Third); 510 PrintedSomething = true; 511 } 512 513 if (!PrintedSomething) { 514 OS << "No conversions required"; 515 } 516 } 517 518 /// dump - Print this user-defined conversion sequence to standard 519 /// error. Useful for debugging overloading issues. 520 void UserDefinedConversionSequence::dump() const { 521 raw_ostream &OS = llvm::errs(); 522 if (Before.First || Before.Second || Before.Third) { 523 Before.dump(); 524 OS << " -> "; 525 } 526 if (ConversionFunction) 527 OS << '\'' << *ConversionFunction << '\''; 528 else 529 OS << "aggregate initialization"; 530 if (After.First || After.Second || After.Third) { 531 OS << " -> "; 532 After.dump(); 533 } 534 } 535 536 /// dump - Print this implicit conversion sequence to standard 537 /// error. Useful for debugging overloading issues. 538 void ImplicitConversionSequence::dump() const { 539 raw_ostream &OS = llvm::errs(); 540 if (isStdInitializerListElement()) 541 OS << "Worst std::initializer_list element conversion: "; 542 switch (ConversionKind) { 543 case StandardConversion: 544 OS << "Standard conversion: "; 545 Standard.dump(); 546 break; 547 case UserDefinedConversion: 548 OS << "User-defined conversion: "; 549 UserDefined.dump(); 550 break; 551 case EllipsisConversion: 552 OS << "Ellipsis conversion"; 553 break; 554 case AmbiguousConversion: 555 OS << "Ambiguous conversion"; 556 break; 557 case BadConversion: 558 OS << "Bad conversion"; 559 break; 560 } 561 562 OS << "\n"; 563 } 564 565 void AmbiguousConversionSequence::construct() { 566 new (&conversions()) ConversionSet(); 567 } 568 569 void AmbiguousConversionSequence::destruct() { 570 conversions().~ConversionSet(); 571 } 572 573 void 574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 575 FromTypePtr = O.FromTypePtr; 576 ToTypePtr = O.ToTypePtr; 577 new (&conversions()) ConversionSet(O.conversions()); 578 } 579 580 namespace { 581 // Structure used by DeductionFailureInfo to store 582 // template argument information. 583 struct DFIArguments { 584 TemplateArgument FirstArg; 585 TemplateArgument SecondArg; 586 }; 587 // Structure used by DeductionFailureInfo to store 588 // template parameter and template argument information. 589 struct DFIParamWithArguments : DFIArguments { 590 TemplateParameter Param; 591 }; 592 // Structure used by DeductionFailureInfo to store template argument 593 // information and the index of the problematic call argument. 594 struct DFIDeducedMismatchArgs : DFIArguments { 595 TemplateArgumentList *TemplateArgs; 596 unsigned CallArgIndex; 597 }; 598 // Structure used by DeductionFailureInfo to store information about 599 // unsatisfied constraints. 600 struct CNSInfo { 601 TemplateArgumentList *TemplateArgs; 602 ConstraintSatisfaction Satisfaction; 603 }; 604 } 605 606 /// Convert from Sema's representation of template deduction information 607 /// to the form used in overload-candidate information. 608 DeductionFailureInfo 609 clang::MakeDeductionFailureInfo(ASTContext &Context, 610 Sema::TemplateDeductionResult TDK, 611 TemplateDeductionInfo &Info) { 612 DeductionFailureInfo Result; 613 Result.Result = static_cast<unsigned>(TDK); 614 Result.HasDiagnostic = false; 615 switch (TDK) { 616 case Sema::TDK_Invalid: 617 case Sema::TDK_InstantiationDepth: 618 case Sema::TDK_TooManyArguments: 619 case Sema::TDK_TooFewArguments: 620 case Sema::TDK_MiscellaneousDeductionFailure: 621 case Sema::TDK_CUDATargetMismatch: 622 Result.Data = nullptr; 623 break; 624 625 case Sema::TDK_Incomplete: 626 case Sema::TDK_InvalidExplicitArguments: 627 Result.Data = Info.Param.getOpaqueValue(); 628 break; 629 630 case Sema::TDK_DeducedMismatch: 631 case Sema::TDK_DeducedMismatchNested: { 632 // FIXME: Should allocate from normal heap so that we can free this later. 633 auto *Saved = new (Context) DFIDeducedMismatchArgs; 634 Saved->FirstArg = Info.FirstArg; 635 Saved->SecondArg = Info.SecondArg; 636 Saved->TemplateArgs = Info.take(); 637 Saved->CallArgIndex = Info.CallArgIndex; 638 Result.Data = Saved; 639 break; 640 } 641 642 case Sema::TDK_NonDeducedMismatch: { 643 // FIXME: Should allocate from normal heap so that we can free this later. 644 DFIArguments *Saved = new (Context) DFIArguments; 645 Saved->FirstArg = Info.FirstArg; 646 Saved->SecondArg = Info.SecondArg; 647 Result.Data = Saved; 648 break; 649 } 650 651 case Sema::TDK_IncompletePack: 652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 653 case Sema::TDK_Inconsistent: 654 case Sema::TDK_Underqualified: { 655 // FIXME: Should allocate from normal heap so that we can free this later. 656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 657 Saved->Param = Info.Param; 658 Saved->FirstArg = Info.FirstArg; 659 Saved->SecondArg = Info.SecondArg; 660 Result.Data = Saved; 661 break; 662 } 663 664 case Sema::TDK_SubstitutionFailure: 665 Result.Data = Info.take(); 666 if (Info.hasSFINAEDiagnostic()) { 667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 668 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 669 Info.takeSFINAEDiagnostic(*Diag); 670 Result.HasDiagnostic = true; 671 } 672 break; 673 674 case Sema::TDK_ConstraintsNotSatisfied: { 675 CNSInfo *Saved = new (Context) CNSInfo; 676 Saved->TemplateArgs = Info.take(); 677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 678 Result.Data = Saved; 679 break; 680 } 681 682 case Sema::TDK_Success: 683 case Sema::TDK_NonDependentConversionFailure: 684 llvm_unreachable("not a deduction failure"); 685 } 686 687 return Result; 688 } 689 690 void DeductionFailureInfo::Destroy() { 691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 692 case Sema::TDK_Success: 693 case Sema::TDK_Invalid: 694 case Sema::TDK_InstantiationDepth: 695 case Sema::TDK_Incomplete: 696 case Sema::TDK_TooManyArguments: 697 case Sema::TDK_TooFewArguments: 698 case Sema::TDK_InvalidExplicitArguments: 699 case Sema::TDK_CUDATargetMismatch: 700 case Sema::TDK_NonDependentConversionFailure: 701 break; 702 703 case Sema::TDK_IncompletePack: 704 case Sema::TDK_Inconsistent: 705 case Sema::TDK_Underqualified: 706 case Sema::TDK_DeducedMismatch: 707 case Sema::TDK_DeducedMismatchNested: 708 case Sema::TDK_NonDeducedMismatch: 709 // FIXME: Destroy the data? 710 Data = nullptr; 711 break; 712 713 case Sema::TDK_SubstitutionFailure: 714 // FIXME: Destroy the template argument list? 715 Data = nullptr; 716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 717 Diag->~PartialDiagnosticAt(); 718 HasDiagnostic = false; 719 } 720 break; 721 722 case Sema::TDK_ConstraintsNotSatisfied: 723 // FIXME: Destroy the template argument list? 724 Data = nullptr; 725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 726 Diag->~PartialDiagnosticAt(); 727 HasDiagnostic = false; 728 } 729 break; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 } 736 737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 738 if (HasDiagnostic) 739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 740 return nullptr; 741 } 742 743 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 745 case Sema::TDK_Success: 746 case Sema::TDK_Invalid: 747 case Sema::TDK_InstantiationDepth: 748 case Sema::TDK_TooManyArguments: 749 case Sema::TDK_TooFewArguments: 750 case Sema::TDK_SubstitutionFailure: 751 case Sema::TDK_DeducedMismatch: 752 case Sema::TDK_DeducedMismatchNested: 753 case Sema::TDK_NonDeducedMismatch: 754 case Sema::TDK_CUDATargetMismatch: 755 case Sema::TDK_NonDependentConversionFailure: 756 case Sema::TDK_ConstraintsNotSatisfied: 757 return TemplateParameter(); 758 759 case Sema::TDK_Incomplete: 760 case Sema::TDK_InvalidExplicitArguments: 761 return TemplateParameter::getFromOpaqueValue(Data); 762 763 case Sema::TDK_IncompletePack: 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 return static_cast<DFIParamWithArguments*>(Data)->Param; 767 768 // Unhandled 769 case Sema::TDK_MiscellaneousDeductionFailure: 770 break; 771 } 772 773 return TemplateParameter(); 774 } 775 776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 778 case Sema::TDK_Success: 779 case Sema::TDK_Invalid: 780 case Sema::TDK_InstantiationDepth: 781 case Sema::TDK_TooManyArguments: 782 case Sema::TDK_TooFewArguments: 783 case Sema::TDK_Incomplete: 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_InvalidExplicitArguments: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_NonDeducedMismatch: 789 case Sema::TDK_CUDATargetMismatch: 790 case Sema::TDK_NonDependentConversionFailure: 791 return nullptr; 792 793 case Sema::TDK_DeducedMismatch: 794 case Sema::TDK_DeducedMismatchNested: 795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 796 797 case Sema::TDK_SubstitutionFailure: 798 return static_cast<TemplateArgumentList*>(Data); 799 800 case Sema::TDK_ConstraintsNotSatisfied: 801 return static_cast<CNSInfo*>(Data)->TemplateArgs; 802 803 // Unhandled 804 case Sema::TDK_MiscellaneousDeductionFailure: 805 break; 806 } 807 808 return nullptr; 809 } 810 811 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 813 case Sema::TDK_Success: 814 case Sema::TDK_Invalid: 815 case Sema::TDK_InstantiationDepth: 816 case Sema::TDK_Incomplete: 817 case Sema::TDK_TooManyArguments: 818 case Sema::TDK_TooFewArguments: 819 case Sema::TDK_InvalidExplicitArguments: 820 case Sema::TDK_SubstitutionFailure: 821 case Sema::TDK_CUDATargetMismatch: 822 case Sema::TDK_NonDependentConversionFailure: 823 case Sema::TDK_ConstraintsNotSatisfied: 824 return nullptr; 825 826 case Sema::TDK_IncompletePack: 827 case Sema::TDK_Inconsistent: 828 case Sema::TDK_Underqualified: 829 case Sema::TDK_DeducedMismatch: 830 case Sema::TDK_DeducedMismatchNested: 831 case Sema::TDK_NonDeducedMismatch: 832 return &static_cast<DFIArguments*>(Data)->FirstArg; 833 834 // Unhandled 835 case Sema::TDK_MiscellaneousDeductionFailure: 836 break; 837 } 838 839 return nullptr; 840 } 841 842 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 844 case Sema::TDK_Success: 845 case Sema::TDK_Invalid: 846 case Sema::TDK_InstantiationDepth: 847 case Sema::TDK_Incomplete: 848 case Sema::TDK_IncompletePack: 849 case Sema::TDK_TooManyArguments: 850 case Sema::TDK_TooFewArguments: 851 case Sema::TDK_InvalidExplicitArguments: 852 case Sema::TDK_SubstitutionFailure: 853 case Sema::TDK_CUDATargetMismatch: 854 case Sema::TDK_NonDependentConversionFailure: 855 case Sema::TDK_ConstraintsNotSatisfied: 856 return nullptr; 857 858 case Sema::TDK_Inconsistent: 859 case Sema::TDK_Underqualified: 860 case Sema::TDK_DeducedMismatch: 861 case Sema::TDK_DeducedMismatchNested: 862 case Sema::TDK_NonDeducedMismatch: 863 return &static_cast<DFIArguments*>(Data)->SecondArg; 864 865 // Unhandled 866 case Sema::TDK_MiscellaneousDeductionFailure: 867 break; 868 } 869 870 return nullptr; 871 } 872 873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 875 case Sema::TDK_DeducedMismatch: 876 case Sema::TDK_DeducedMismatchNested: 877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 878 879 default: 880 return llvm::None; 881 } 882 } 883 884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 885 OverloadedOperatorKind Op) { 886 if (!AllowRewrittenCandidates) 887 return false; 888 return Op == OO_EqualEqual || Op == OO_Spaceship; 889 } 890 891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 892 ASTContext &Ctx, const FunctionDecl *FD) { 893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 894 return false; 895 // Don't bother adding a reversed candidate that can never be a better 896 // match than the non-reversed version. 897 return FD->getNumParams() != 2 || 898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 899 FD->getParamDecl(1)->getType()) || 900 FD->hasAttr<EnableIfAttr>(); 901 } 902 903 void OverloadCandidateSet::destroyCandidates() { 904 for (iterator i = begin(), e = end(); i != e; ++i) { 905 for (auto &C : i->Conversions) 906 C.~ImplicitConversionSequence(); 907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 908 i->DeductionFailure.Destroy(); 909 } 910 } 911 912 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 913 destroyCandidates(); 914 SlabAllocator.Reset(); 915 NumInlineBytesUsed = 0; 916 Candidates.clear(); 917 Functions.clear(); 918 Kind = CSK; 919 } 920 921 namespace { 922 class UnbridgedCastsSet { 923 struct Entry { 924 Expr **Addr; 925 Expr *Saved; 926 }; 927 SmallVector<Entry, 2> Entries; 928 929 public: 930 void save(Sema &S, Expr *&E) { 931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 932 Entry entry = { &E, E }; 933 Entries.push_back(entry); 934 E = S.stripARCUnbridgedCast(E); 935 } 936 937 void restore() { 938 for (SmallVectorImpl<Entry>::iterator 939 i = Entries.begin(), e = Entries.end(); i != e; ++i) 940 *i->Addr = i->Saved; 941 } 942 }; 943 } 944 945 /// checkPlaceholderForOverload - Do any interesting placeholder-like 946 /// preprocessing on the given expression. 947 /// 948 /// \param unbridgedCasts a collection to which to add unbridged casts; 949 /// without this, they will be immediately diagnosed as errors 950 /// 951 /// Return true on unrecoverable error. 952 static bool 953 checkPlaceholderForOverload(Sema &S, Expr *&E, 954 UnbridgedCastsSet *unbridgedCasts = nullptr) { 955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 956 // We can't handle overloaded expressions here because overload 957 // resolution might reasonably tweak them. 958 if (placeholder->getKind() == BuiltinType::Overload) return false; 959 960 // If the context potentially accepts unbridged ARC casts, strip 961 // the unbridged cast and add it to the collection for later restoration. 962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 963 unbridgedCasts) { 964 unbridgedCasts->save(S, E); 965 return false; 966 } 967 968 // Go ahead and check everything else. 969 ExprResult result = S.CheckPlaceholderExpr(E); 970 if (result.isInvalid()) 971 return true; 972 973 E = result.get(); 974 return false; 975 } 976 977 // Nothing to do. 978 return false; 979 } 980 981 /// checkArgPlaceholdersForOverload - Check a set of call operands for 982 /// placeholders. 983 static bool checkArgPlaceholdersForOverload(Sema &S, 984 MultiExprArg Args, 985 UnbridgedCastsSet &unbridged) { 986 for (unsigned i = 0, e = Args.size(); i != e; ++i) 987 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 988 return true; 989 990 return false; 991 } 992 993 /// Determine whether the given New declaration is an overload of the 994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 995 /// New and Old cannot be overloaded, e.g., if New has the same signature as 996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 997 /// functions (or function templates) at all. When it does return Ovl_Match or 998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1000 /// declaration. 1001 /// 1002 /// Example: Given the following input: 1003 /// 1004 /// void f(int, float); // #1 1005 /// void f(int, int); // #2 1006 /// int f(int, int); // #3 1007 /// 1008 /// When we process #1, there is no previous declaration of "f", so IsOverload 1009 /// will not be used. 1010 /// 1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1014 /// unchanged. 1015 /// 1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1020 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1021 /// 1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1023 /// by a using declaration. The rules for whether to hide shadow declarations 1024 /// ignore some properties which otherwise figure into a function template's 1025 /// signature. 1026 Sema::OverloadKind 1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1028 NamedDecl *&Match, bool NewIsUsingDecl) { 1029 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1030 I != E; ++I) { 1031 NamedDecl *OldD = *I; 1032 1033 bool OldIsUsingDecl = false; 1034 if (isa<UsingShadowDecl>(OldD)) { 1035 OldIsUsingDecl = true; 1036 1037 // We can always introduce two using declarations into the same 1038 // context, even if they have identical signatures. 1039 if (NewIsUsingDecl) continue; 1040 1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1042 } 1043 1044 // A using-declaration does not conflict with another declaration 1045 // if one of them is hidden. 1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1047 continue; 1048 1049 // If either declaration was introduced by a using declaration, 1050 // we'll need to use slightly different rules for matching. 1051 // Essentially, these rules are the normal rules, except that 1052 // function templates hide function templates with different 1053 // return types or template parameter lists. 1054 bool UseMemberUsingDeclRules = 1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1056 !New->getFriendObjectKind(); 1057 1058 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1062 continue; 1063 } 1064 1065 if (!isa<FunctionTemplateDecl>(OldD) && 1066 !shouldLinkPossiblyHiddenDecl(*I, New)) 1067 continue; 1068 1069 Match = *I; 1070 return Ovl_Match; 1071 } 1072 1073 // Builtins that have custom typechecking or have a reference should 1074 // not be overloadable or redeclarable. 1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1076 Match = *I; 1077 return Ovl_NonFunction; 1078 } 1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1080 // We can overload with these, which can show up when doing 1081 // redeclaration checks for UsingDecls. 1082 assert(Old.getLookupKind() == LookupUsingDeclName); 1083 } else if (isa<TagDecl>(OldD)) { 1084 // We can always overload with tags by hiding them. 1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1086 // Optimistically assume that an unresolved using decl will 1087 // overload; if it doesn't, we'll have to diagnose during 1088 // template instantiation. 1089 // 1090 // Exception: if the scope is dependent and this is not a class 1091 // member, the using declaration can only introduce an enumerator. 1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1093 Match = *I; 1094 return Ovl_NonFunction; 1095 } 1096 } else { 1097 // (C++ 13p1): 1098 // Only function declarations can be overloaded; object and type 1099 // declarations cannot be overloaded. 1100 Match = *I; 1101 return Ovl_NonFunction; 1102 } 1103 } 1104 1105 // C++ [temp.friend]p1: 1106 // For a friend function declaration that is not a template declaration: 1107 // -- if the name of the friend is a qualified or unqualified template-id, 1108 // [...], otherwise 1109 // -- if the name of the friend is a qualified-id and a matching 1110 // non-template function is found in the specified class or namespace, 1111 // the friend declaration refers to that function, otherwise, 1112 // -- if the name of the friend is a qualified-id and a matching function 1113 // template is found in the specified class or namespace, the friend 1114 // declaration refers to the deduced specialization of that function 1115 // template, otherwise 1116 // -- the name shall be an unqualified-id [...] 1117 // If we get here for a qualified friend declaration, we've just reached the 1118 // third bullet. If the type of the friend is dependent, skip this lookup 1119 // until instantiation. 1120 if (New->getFriendObjectKind() && New->getQualifier() && 1121 !New->getDescribedFunctionTemplate() && 1122 !New->getDependentSpecializationInfo() && 1123 !New->getType()->isDependentType()) { 1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1125 TemplateSpecResult.addAllDecls(Old); 1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1127 /*QualifiedFriend*/true)) { 1128 New->setInvalidDecl(); 1129 return Ovl_Overload; 1130 } 1131 1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1133 return Ovl_Match; 1134 } 1135 1136 return Ovl_Overload; 1137 } 1138 1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1141 // C++ [basic.start.main]p2: This function shall not be overloaded. 1142 if (New->isMain()) 1143 return false; 1144 1145 // MSVCRT user defined entry points cannot be overloaded. 1146 if (New->isMSVCRTEntryPoint()) 1147 return false; 1148 1149 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1150 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1151 1152 // C++ [temp.fct]p2: 1153 // A function template can be overloaded with other function templates 1154 // and with normal (non-template) functions. 1155 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1156 return true; 1157 1158 // Is the function New an overload of the function Old? 1159 QualType OldQType = Context.getCanonicalType(Old->getType()); 1160 QualType NewQType = Context.getCanonicalType(New->getType()); 1161 1162 // Compare the signatures (C++ 1.3.10) of the two functions to 1163 // determine whether they are overloads. If we find any mismatch 1164 // in the signature, they are overloads. 1165 1166 // If either of these functions is a K&R-style function (no 1167 // prototype), then we consider them to have matching signatures. 1168 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1169 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1170 return false; 1171 1172 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1173 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1174 1175 // The signature of a function includes the types of its 1176 // parameters (C++ 1.3.10), which includes the presence or absence 1177 // of the ellipsis; see C++ DR 357). 1178 if (OldQType != NewQType && 1179 (OldType->getNumParams() != NewType->getNumParams() || 1180 OldType->isVariadic() != NewType->isVariadic() || 1181 !FunctionParamTypesAreEqual(OldType, NewType))) 1182 return true; 1183 1184 // C++ [temp.over.link]p4: 1185 // The signature of a function template consists of its function 1186 // signature, its return type and its template parameter list. The names 1187 // of the template parameters are significant only for establishing the 1188 // relationship between the template parameters and the rest of the 1189 // signature. 1190 // 1191 // We check the return type and template parameter lists for function 1192 // templates first; the remaining checks follow. 1193 // 1194 // However, we don't consider either of these when deciding whether 1195 // a member introduced by a shadow declaration is hidden. 1196 if (!UseMemberUsingDeclRules && NewTemplate && 1197 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1198 OldTemplate->getTemplateParameters(), 1199 false, TPL_TemplateMatch) || 1200 !Context.hasSameType(Old->getDeclaredReturnType(), 1201 New->getDeclaredReturnType()))) 1202 return true; 1203 1204 // If the function is a class member, its signature includes the 1205 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1206 // 1207 // As part of this, also check whether one of the member functions 1208 // is static, in which case they are not overloads (C++ 1209 // 13.1p2). While not part of the definition of the signature, 1210 // this check is important to determine whether these functions 1211 // can be overloaded. 1212 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1213 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1214 if (OldMethod && NewMethod && 1215 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1216 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1217 if (!UseMemberUsingDeclRules && 1218 (OldMethod->getRefQualifier() == RQ_None || 1219 NewMethod->getRefQualifier() == RQ_None)) { 1220 // C++0x [over.load]p2: 1221 // - Member function declarations with the same name and the same 1222 // parameter-type-list as well as member function template 1223 // declarations with the same name, the same parameter-type-list, and 1224 // the same template parameter lists cannot be overloaded if any of 1225 // them, but not all, have a ref-qualifier (8.3.5). 1226 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1227 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1228 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1229 } 1230 return true; 1231 } 1232 1233 // We may not have applied the implicit const for a constexpr member 1234 // function yet (because we haven't yet resolved whether this is a static 1235 // or non-static member function). Add it now, on the assumption that this 1236 // is a redeclaration of OldMethod. 1237 auto OldQuals = OldMethod->getMethodQualifiers(); 1238 auto NewQuals = NewMethod->getMethodQualifiers(); 1239 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1240 !isa<CXXConstructorDecl>(NewMethod)) 1241 NewQuals.addConst(); 1242 // We do not allow overloading based off of '__restrict'. 1243 OldQuals.removeRestrict(); 1244 NewQuals.removeRestrict(); 1245 if (OldQuals != NewQuals) 1246 return true; 1247 } 1248 1249 // Though pass_object_size is placed on parameters and takes an argument, we 1250 // consider it to be a function-level modifier for the sake of function 1251 // identity. Either the function has one or more parameters with 1252 // pass_object_size or it doesn't. 1253 if (functionHasPassObjectSizeParams(New) != 1254 functionHasPassObjectSizeParams(Old)) 1255 return true; 1256 1257 // enable_if attributes are an order-sensitive part of the signature. 1258 for (specific_attr_iterator<EnableIfAttr> 1259 NewI = New->specific_attr_begin<EnableIfAttr>(), 1260 NewE = New->specific_attr_end<EnableIfAttr>(), 1261 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1262 OldE = Old->specific_attr_end<EnableIfAttr>(); 1263 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1264 if (NewI == NewE || OldI == OldE) 1265 return true; 1266 llvm::FoldingSetNodeID NewID, OldID; 1267 NewI->getCond()->Profile(NewID, Context, true); 1268 OldI->getCond()->Profile(OldID, Context, true); 1269 if (NewID != OldID) 1270 return true; 1271 } 1272 1273 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1274 // Don't allow overloading of destructors. (In theory we could, but it 1275 // would be a giant change to clang.) 1276 if (isa<CXXDestructorDecl>(New)) 1277 return false; 1278 1279 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1280 OldTarget = IdentifyCUDATarget(Old); 1281 if (NewTarget == CFT_InvalidTarget) 1282 return false; 1283 1284 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1285 1286 // Allow overloading of functions with same signature and different CUDA 1287 // target attributes. 1288 return NewTarget != OldTarget; 1289 } 1290 1291 // TODO: Concepts: Check function trailing requires clauses here. 1292 1293 // The signatures match; this is not an overload. 1294 return false; 1295 } 1296 1297 /// Tries a user-defined conversion from From to ToType. 1298 /// 1299 /// Produces an implicit conversion sequence for when a standard conversion 1300 /// is not an option. See TryImplicitConversion for more information. 1301 static ImplicitConversionSequence 1302 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1303 bool SuppressUserConversions, 1304 bool AllowExplicit, 1305 bool InOverloadResolution, 1306 bool CStyle, 1307 bool AllowObjCWritebackConversion, 1308 bool AllowObjCConversionOnExplicit) { 1309 ImplicitConversionSequence ICS; 1310 1311 if (SuppressUserConversions) { 1312 // We're not in the case above, so there is no conversion that 1313 // we can perform. 1314 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1315 return ICS; 1316 } 1317 1318 // Attempt user-defined conversion. 1319 OverloadCandidateSet Conversions(From->getExprLoc(), 1320 OverloadCandidateSet::CSK_Normal); 1321 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1322 Conversions, AllowExplicit, 1323 AllowObjCConversionOnExplicit)) { 1324 case OR_Success: 1325 case OR_Deleted: 1326 ICS.setUserDefined(); 1327 // C++ [over.ics.user]p4: 1328 // A conversion of an expression of class type to the same class 1329 // type is given Exact Match rank, and a conversion of an 1330 // expression of class type to a base class of that type is 1331 // given Conversion rank, in spite of the fact that a copy 1332 // constructor (i.e., a user-defined conversion function) is 1333 // called for those cases. 1334 if (CXXConstructorDecl *Constructor 1335 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1336 QualType FromCanon 1337 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1338 QualType ToCanon 1339 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1340 if (Constructor->isCopyConstructor() && 1341 (FromCanon == ToCanon || 1342 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1343 // Turn this into a "standard" conversion sequence, so that it 1344 // gets ranked with standard conversion sequences. 1345 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1346 ICS.setStandard(); 1347 ICS.Standard.setAsIdentityConversion(); 1348 ICS.Standard.setFromType(From->getType()); 1349 ICS.Standard.setAllToTypes(ToType); 1350 ICS.Standard.CopyConstructor = Constructor; 1351 ICS.Standard.FoundCopyConstructor = Found; 1352 if (ToCanon != FromCanon) 1353 ICS.Standard.Second = ICK_Derived_To_Base; 1354 } 1355 } 1356 break; 1357 1358 case OR_Ambiguous: 1359 ICS.setAmbiguous(); 1360 ICS.Ambiguous.setFromType(From->getType()); 1361 ICS.Ambiguous.setToType(ToType); 1362 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1363 Cand != Conversions.end(); ++Cand) 1364 if (Cand->Best) 1365 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1366 break; 1367 1368 // Fall through. 1369 case OR_No_Viable_Function: 1370 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1371 break; 1372 } 1373 1374 return ICS; 1375 } 1376 1377 /// TryImplicitConversion - Attempt to perform an implicit conversion 1378 /// from the given expression (Expr) to the given type (ToType). This 1379 /// function returns an implicit conversion sequence that can be used 1380 /// to perform the initialization. Given 1381 /// 1382 /// void f(float f); 1383 /// void g(int i) { f(i); } 1384 /// 1385 /// this routine would produce an implicit conversion sequence to 1386 /// describe the initialization of f from i, which will be a standard 1387 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1388 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1389 // 1390 /// Note that this routine only determines how the conversion can be 1391 /// performed; it does not actually perform the conversion. As such, 1392 /// it will not produce any diagnostics if no conversion is available, 1393 /// but will instead return an implicit conversion sequence of kind 1394 /// "BadConversion". 1395 /// 1396 /// If @p SuppressUserConversions, then user-defined conversions are 1397 /// not permitted. 1398 /// If @p AllowExplicit, then explicit user-defined conversions are 1399 /// permitted. 1400 /// 1401 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1402 /// writeback conversion, which allows __autoreleasing id* parameters to 1403 /// be initialized with __strong id* or __weak id* arguments. 1404 static ImplicitConversionSequence 1405 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1406 bool SuppressUserConversions, 1407 bool AllowExplicit, 1408 bool InOverloadResolution, 1409 bool CStyle, 1410 bool AllowObjCWritebackConversion, 1411 bool AllowObjCConversionOnExplicit) { 1412 ImplicitConversionSequence ICS; 1413 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1414 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1415 ICS.setStandard(); 1416 return ICS; 1417 } 1418 1419 if (!S.getLangOpts().CPlusPlus) { 1420 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1421 return ICS; 1422 } 1423 1424 // C++ [over.ics.user]p4: 1425 // A conversion of an expression of class type to the same class 1426 // type is given Exact Match rank, and a conversion of an 1427 // expression of class type to a base class of that type is 1428 // given Conversion rank, in spite of the fact that a copy/move 1429 // constructor (i.e., a user-defined conversion function) is 1430 // called for those cases. 1431 QualType FromType = From->getType(); 1432 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1433 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1434 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1435 ICS.setStandard(); 1436 ICS.Standard.setAsIdentityConversion(); 1437 ICS.Standard.setFromType(FromType); 1438 ICS.Standard.setAllToTypes(ToType); 1439 1440 // We don't actually check at this point whether there is a valid 1441 // copy/move constructor, since overloading just assumes that it 1442 // exists. When we actually perform initialization, we'll find the 1443 // appropriate constructor to copy the returned object, if needed. 1444 ICS.Standard.CopyConstructor = nullptr; 1445 1446 // Determine whether this is considered a derived-to-base conversion. 1447 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1448 ICS.Standard.Second = ICK_Derived_To_Base; 1449 1450 return ICS; 1451 } 1452 1453 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1454 AllowExplicit, InOverloadResolution, CStyle, 1455 AllowObjCWritebackConversion, 1456 AllowObjCConversionOnExplicit); 1457 } 1458 1459 ImplicitConversionSequence 1460 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1461 bool SuppressUserConversions, 1462 bool AllowExplicit, 1463 bool InOverloadResolution, 1464 bool CStyle, 1465 bool AllowObjCWritebackConversion) { 1466 return ::TryImplicitConversion(*this, From, ToType, 1467 SuppressUserConversions, AllowExplicit, 1468 InOverloadResolution, CStyle, 1469 AllowObjCWritebackConversion, 1470 /*AllowObjCConversionOnExplicit=*/false); 1471 } 1472 1473 /// PerformImplicitConversion - Perform an implicit conversion of the 1474 /// expression From to the type ToType. Returns the 1475 /// converted expression. Flavor is the kind of conversion we're 1476 /// performing, used in the error message. If @p AllowExplicit, 1477 /// explicit user-defined conversions are permitted. 1478 ExprResult 1479 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1480 AssignmentAction Action, bool AllowExplicit) { 1481 ImplicitConversionSequence ICS; 1482 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1483 } 1484 1485 ExprResult 1486 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1487 AssignmentAction Action, bool AllowExplicit, 1488 ImplicitConversionSequence& ICS) { 1489 if (checkPlaceholderForOverload(*this, From)) 1490 return ExprError(); 1491 1492 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1493 bool AllowObjCWritebackConversion 1494 = getLangOpts().ObjCAutoRefCount && 1495 (Action == AA_Passing || Action == AA_Sending); 1496 if (getLangOpts().ObjC) 1497 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1498 From->getType(), From); 1499 ICS = ::TryImplicitConversion(*this, From, ToType, 1500 /*SuppressUserConversions=*/false, 1501 AllowExplicit, 1502 /*InOverloadResolution=*/false, 1503 /*CStyle=*/false, 1504 AllowObjCWritebackConversion, 1505 /*AllowObjCConversionOnExplicit=*/false); 1506 return PerformImplicitConversion(From, ToType, ICS, Action); 1507 } 1508 1509 /// Determine whether the conversion from FromType to ToType is a valid 1510 /// conversion that strips "noexcept" or "noreturn" off the nested function 1511 /// type. 1512 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1513 QualType &ResultTy) { 1514 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1515 return false; 1516 1517 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1518 // or F(t noexcept) -> F(t) 1519 // where F adds one of the following at most once: 1520 // - a pointer 1521 // - a member pointer 1522 // - a block pointer 1523 // Changes here need matching changes in FindCompositePointerType. 1524 CanQualType CanTo = Context.getCanonicalType(ToType); 1525 CanQualType CanFrom = Context.getCanonicalType(FromType); 1526 Type::TypeClass TyClass = CanTo->getTypeClass(); 1527 if (TyClass != CanFrom->getTypeClass()) return false; 1528 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1529 if (TyClass == Type::Pointer) { 1530 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1531 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1532 } else if (TyClass == Type::BlockPointer) { 1533 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1534 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1535 } else if (TyClass == Type::MemberPointer) { 1536 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1537 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1538 // A function pointer conversion cannot change the class of the function. 1539 if (ToMPT->getClass() != FromMPT->getClass()) 1540 return false; 1541 CanTo = ToMPT->getPointeeType(); 1542 CanFrom = FromMPT->getPointeeType(); 1543 } else { 1544 return false; 1545 } 1546 1547 TyClass = CanTo->getTypeClass(); 1548 if (TyClass != CanFrom->getTypeClass()) return false; 1549 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1550 return false; 1551 } 1552 1553 const auto *FromFn = cast<FunctionType>(CanFrom); 1554 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1555 1556 const auto *ToFn = cast<FunctionType>(CanTo); 1557 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1558 1559 bool Changed = false; 1560 1561 // Drop 'noreturn' if not present in target type. 1562 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1563 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1564 Changed = true; 1565 } 1566 1567 // Drop 'noexcept' if not present in target type. 1568 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1569 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1570 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1571 FromFn = cast<FunctionType>( 1572 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1573 EST_None) 1574 .getTypePtr()); 1575 Changed = true; 1576 } 1577 1578 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1579 // only if the ExtParameterInfo lists of the two function prototypes can be 1580 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1581 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1582 bool CanUseToFPT, CanUseFromFPT; 1583 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1584 CanUseFromFPT, NewParamInfos) && 1585 CanUseToFPT && !CanUseFromFPT) { 1586 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1587 ExtInfo.ExtParameterInfos = 1588 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1589 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1590 FromFPT->getParamTypes(), ExtInfo); 1591 FromFn = QT->getAs<FunctionType>(); 1592 Changed = true; 1593 } 1594 } 1595 1596 if (!Changed) 1597 return false; 1598 1599 assert(QualType(FromFn, 0).isCanonical()); 1600 if (QualType(FromFn, 0) != CanTo) return false; 1601 1602 ResultTy = ToType; 1603 return true; 1604 } 1605 1606 /// Determine whether the conversion from FromType to ToType is a valid 1607 /// vector conversion. 1608 /// 1609 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1610 /// conversion. 1611 static bool IsVectorConversion(Sema &S, QualType FromType, 1612 QualType ToType, ImplicitConversionKind &ICK) { 1613 // We need at least one of these types to be a vector type to have a vector 1614 // conversion. 1615 if (!ToType->isVectorType() && !FromType->isVectorType()) 1616 return false; 1617 1618 // Identical types require no conversions. 1619 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1620 return false; 1621 1622 // There are no conversions between extended vector types, only identity. 1623 if (ToType->isExtVectorType()) { 1624 // There are no conversions between extended vector types other than the 1625 // identity conversion. 1626 if (FromType->isExtVectorType()) 1627 return false; 1628 1629 // Vector splat from any arithmetic type to a vector. 1630 if (FromType->isArithmeticType()) { 1631 ICK = ICK_Vector_Splat; 1632 return true; 1633 } 1634 } 1635 1636 // We can perform the conversion between vector types in the following cases: 1637 // 1)vector types are equivalent AltiVec and GCC vector types 1638 // 2)lax vector conversions are permitted and the vector types are of the 1639 // same size 1640 if (ToType->isVectorType() && FromType->isVectorType()) { 1641 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1642 S.isLaxVectorConversion(FromType, ToType)) { 1643 ICK = ICK_Vector_Conversion; 1644 return true; 1645 } 1646 } 1647 1648 return false; 1649 } 1650 1651 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1652 bool InOverloadResolution, 1653 StandardConversionSequence &SCS, 1654 bool CStyle); 1655 1656 /// IsStandardConversion - Determines whether there is a standard 1657 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1658 /// expression From to the type ToType. Standard conversion sequences 1659 /// only consider non-class types; for conversions that involve class 1660 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1661 /// contain the standard conversion sequence required to perform this 1662 /// conversion and this routine will return true. Otherwise, this 1663 /// routine will return false and the value of SCS is unspecified. 1664 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1665 bool InOverloadResolution, 1666 StandardConversionSequence &SCS, 1667 bool CStyle, 1668 bool AllowObjCWritebackConversion) { 1669 QualType FromType = From->getType(); 1670 1671 // Standard conversions (C++ [conv]) 1672 SCS.setAsIdentityConversion(); 1673 SCS.IncompatibleObjC = false; 1674 SCS.setFromType(FromType); 1675 SCS.CopyConstructor = nullptr; 1676 1677 // There are no standard conversions for class types in C++, so 1678 // abort early. When overloading in C, however, we do permit them. 1679 if (S.getLangOpts().CPlusPlus && 1680 (FromType->isRecordType() || ToType->isRecordType())) 1681 return false; 1682 1683 // The first conversion can be an lvalue-to-rvalue conversion, 1684 // array-to-pointer conversion, or function-to-pointer conversion 1685 // (C++ 4p1). 1686 1687 if (FromType == S.Context.OverloadTy) { 1688 DeclAccessPair AccessPair; 1689 if (FunctionDecl *Fn 1690 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1691 AccessPair)) { 1692 // We were able to resolve the address of the overloaded function, 1693 // so we can convert to the type of that function. 1694 FromType = Fn->getType(); 1695 SCS.setFromType(FromType); 1696 1697 // we can sometimes resolve &foo<int> regardless of ToType, so check 1698 // if the type matches (identity) or we are converting to bool 1699 if (!S.Context.hasSameUnqualifiedType( 1700 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1701 QualType resultTy; 1702 // if the function type matches except for [[noreturn]], it's ok 1703 if (!S.IsFunctionConversion(FromType, 1704 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1705 // otherwise, only a boolean conversion is standard 1706 if (!ToType->isBooleanType()) 1707 return false; 1708 } 1709 1710 // Check if the "from" expression is taking the address of an overloaded 1711 // function and recompute the FromType accordingly. Take advantage of the 1712 // fact that non-static member functions *must* have such an address-of 1713 // expression. 1714 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1715 if (Method && !Method->isStatic()) { 1716 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1717 "Non-unary operator on non-static member address"); 1718 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1719 == UO_AddrOf && 1720 "Non-address-of operator on non-static member address"); 1721 const Type *ClassType 1722 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1723 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1724 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1725 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1726 UO_AddrOf && 1727 "Non-address-of operator for overloaded function expression"); 1728 FromType = S.Context.getPointerType(FromType); 1729 } 1730 1731 // Check that we've computed the proper type after overload resolution. 1732 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1733 // be calling it from within an NDEBUG block. 1734 assert(S.Context.hasSameType( 1735 FromType, 1736 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1737 } else { 1738 return false; 1739 } 1740 } 1741 // Lvalue-to-rvalue conversion (C++11 4.1): 1742 // A glvalue (3.10) of a non-function, non-array type T can 1743 // be converted to a prvalue. 1744 bool argIsLValue = From->isGLValue(); 1745 if (argIsLValue && 1746 !FromType->isFunctionType() && !FromType->isArrayType() && 1747 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1748 SCS.First = ICK_Lvalue_To_Rvalue; 1749 1750 // C11 6.3.2.1p2: 1751 // ... if the lvalue has atomic type, the value has the non-atomic version 1752 // of the type of the lvalue ... 1753 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1754 FromType = Atomic->getValueType(); 1755 1756 // If T is a non-class type, the type of the rvalue is the 1757 // cv-unqualified version of T. Otherwise, the type of the rvalue 1758 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1759 // just strip the qualifiers because they don't matter. 1760 FromType = FromType.getUnqualifiedType(); 1761 } else if (FromType->isArrayType()) { 1762 // Array-to-pointer conversion (C++ 4.2) 1763 SCS.First = ICK_Array_To_Pointer; 1764 1765 // An lvalue or rvalue of type "array of N T" or "array of unknown 1766 // bound of T" can be converted to an rvalue of type "pointer to 1767 // T" (C++ 4.2p1). 1768 FromType = S.Context.getArrayDecayedType(FromType); 1769 1770 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1771 // This conversion is deprecated in C++03 (D.4) 1772 SCS.DeprecatedStringLiteralToCharPtr = true; 1773 1774 // For the purpose of ranking in overload resolution 1775 // (13.3.3.1.1), this conversion is considered an 1776 // array-to-pointer conversion followed by a qualification 1777 // conversion (4.4). (C++ 4.2p2) 1778 SCS.Second = ICK_Identity; 1779 SCS.Third = ICK_Qualification; 1780 SCS.QualificationIncludesObjCLifetime = false; 1781 SCS.setAllToTypes(FromType); 1782 return true; 1783 } 1784 } else if (FromType->isFunctionType() && argIsLValue) { 1785 // Function-to-pointer conversion (C++ 4.3). 1786 SCS.First = ICK_Function_To_Pointer; 1787 1788 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1789 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1790 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1791 return false; 1792 1793 // An lvalue of function type T can be converted to an rvalue of 1794 // type "pointer to T." The result is a pointer to the 1795 // function. (C++ 4.3p1). 1796 FromType = S.Context.getPointerType(FromType); 1797 } else { 1798 // We don't require any conversions for the first step. 1799 SCS.First = ICK_Identity; 1800 } 1801 SCS.setToType(0, FromType); 1802 1803 // The second conversion can be an integral promotion, floating 1804 // point promotion, integral conversion, floating point conversion, 1805 // floating-integral conversion, pointer conversion, 1806 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1807 // For overloading in C, this can also be a "compatible-type" 1808 // conversion. 1809 bool IncompatibleObjC = false; 1810 ImplicitConversionKind SecondICK = ICK_Identity; 1811 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1812 // The unqualified versions of the types are the same: there's no 1813 // conversion to do. 1814 SCS.Second = ICK_Identity; 1815 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1816 // Integral promotion (C++ 4.5). 1817 SCS.Second = ICK_Integral_Promotion; 1818 FromType = ToType.getUnqualifiedType(); 1819 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1820 // Floating point promotion (C++ 4.6). 1821 SCS.Second = ICK_Floating_Promotion; 1822 FromType = ToType.getUnqualifiedType(); 1823 } else if (S.IsComplexPromotion(FromType, ToType)) { 1824 // Complex promotion (Clang extension) 1825 SCS.Second = ICK_Complex_Promotion; 1826 FromType = ToType.getUnqualifiedType(); 1827 } else if (ToType->isBooleanType() && 1828 (FromType->isArithmeticType() || 1829 FromType->isAnyPointerType() || 1830 FromType->isBlockPointerType() || 1831 FromType->isMemberPointerType() || 1832 FromType->isNullPtrType())) { 1833 // Boolean conversions (C++ 4.12). 1834 SCS.Second = ICK_Boolean_Conversion; 1835 FromType = S.Context.BoolTy; 1836 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1837 ToType->isIntegralType(S.Context)) { 1838 // Integral conversions (C++ 4.7). 1839 SCS.Second = ICK_Integral_Conversion; 1840 FromType = ToType.getUnqualifiedType(); 1841 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1842 // Complex conversions (C99 6.3.1.6) 1843 SCS.Second = ICK_Complex_Conversion; 1844 FromType = ToType.getUnqualifiedType(); 1845 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1846 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1847 // Complex-real conversions (C99 6.3.1.7) 1848 SCS.Second = ICK_Complex_Real; 1849 FromType = ToType.getUnqualifiedType(); 1850 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1851 // FIXME: disable conversions between long double and __float128 if 1852 // their representation is different until there is back end support 1853 // We of course allow this conversion if long double is really double. 1854 if (&S.Context.getFloatTypeSemantics(FromType) != 1855 &S.Context.getFloatTypeSemantics(ToType)) { 1856 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1857 ToType == S.Context.LongDoubleTy) || 1858 (FromType == S.Context.LongDoubleTy && 1859 ToType == S.Context.Float128Ty)); 1860 if (Float128AndLongDouble && 1861 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1862 &llvm::APFloat::PPCDoubleDouble())) 1863 return false; 1864 } 1865 // Floating point conversions (C++ 4.8). 1866 SCS.Second = ICK_Floating_Conversion; 1867 FromType = ToType.getUnqualifiedType(); 1868 } else if ((FromType->isRealFloatingType() && 1869 ToType->isIntegralType(S.Context)) || 1870 (FromType->isIntegralOrUnscopedEnumerationType() && 1871 ToType->isRealFloatingType())) { 1872 // Floating-integral conversions (C++ 4.9). 1873 SCS.Second = ICK_Floating_Integral; 1874 FromType = ToType.getUnqualifiedType(); 1875 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1876 SCS.Second = ICK_Block_Pointer_Conversion; 1877 } else if (AllowObjCWritebackConversion && 1878 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1879 SCS.Second = ICK_Writeback_Conversion; 1880 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1881 FromType, IncompatibleObjC)) { 1882 // Pointer conversions (C++ 4.10). 1883 SCS.Second = ICK_Pointer_Conversion; 1884 SCS.IncompatibleObjC = IncompatibleObjC; 1885 FromType = FromType.getUnqualifiedType(); 1886 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1887 InOverloadResolution, FromType)) { 1888 // Pointer to member conversions (4.11). 1889 SCS.Second = ICK_Pointer_Member; 1890 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1891 SCS.Second = SecondICK; 1892 FromType = ToType.getUnqualifiedType(); 1893 } else if (!S.getLangOpts().CPlusPlus && 1894 S.Context.typesAreCompatible(ToType, FromType)) { 1895 // Compatible conversions (Clang extension for C function overloading) 1896 SCS.Second = ICK_Compatible_Conversion; 1897 FromType = ToType.getUnqualifiedType(); 1898 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1899 InOverloadResolution, 1900 SCS, CStyle)) { 1901 SCS.Second = ICK_TransparentUnionConversion; 1902 FromType = ToType; 1903 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1904 CStyle)) { 1905 // tryAtomicConversion has updated the standard conversion sequence 1906 // appropriately. 1907 return true; 1908 } else if (ToType->isEventT() && 1909 From->isIntegerConstantExpr(S.getASTContext()) && 1910 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1911 SCS.Second = ICK_Zero_Event_Conversion; 1912 FromType = ToType; 1913 } else if (ToType->isQueueT() && 1914 From->isIntegerConstantExpr(S.getASTContext()) && 1915 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1916 SCS.Second = ICK_Zero_Queue_Conversion; 1917 FromType = ToType; 1918 } else if (ToType->isSamplerT() && 1919 From->isIntegerConstantExpr(S.getASTContext())) { 1920 SCS.Second = ICK_Compatible_Conversion; 1921 FromType = ToType; 1922 } else { 1923 // No second conversion required. 1924 SCS.Second = ICK_Identity; 1925 } 1926 SCS.setToType(1, FromType); 1927 1928 // The third conversion can be a function pointer conversion or a 1929 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1930 bool ObjCLifetimeConversion; 1931 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1932 // Function pointer conversions (removing 'noexcept') including removal of 1933 // 'noreturn' (Clang extension). 1934 SCS.Third = ICK_Function_Conversion; 1935 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1936 ObjCLifetimeConversion)) { 1937 SCS.Third = ICK_Qualification; 1938 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1939 FromType = ToType; 1940 } else { 1941 // No conversion required 1942 SCS.Third = ICK_Identity; 1943 } 1944 1945 // C++ [over.best.ics]p6: 1946 // [...] Any difference in top-level cv-qualification is 1947 // subsumed by the initialization itself and does not constitute 1948 // a conversion. [...] 1949 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1950 QualType CanonTo = S.Context.getCanonicalType(ToType); 1951 if (CanonFrom.getLocalUnqualifiedType() 1952 == CanonTo.getLocalUnqualifiedType() && 1953 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1954 FromType = ToType; 1955 CanonFrom = CanonTo; 1956 } 1957 1958 SCS.setToType(2, FromType); 1959 1960 if (CanonFrom == CanonTo) 1961 return true; 1962 1963 // If we have not converted the argument type to the parameter type, 1964 // this is a bad conversion sequence, unless we're resolving an overload in C. 1965 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1966 return false; 1967 1968 ExprResult ER = ExprResult{From}; 1969 Sema::AssignConvertType Conv = 1970 S.CheckSingleAssignmentConstraints(ToType, ER, 1971 /*Diagnose=*/false, 1972 /*DiagnoseCFAudited=*/false, 1973 /*ConvertRHS=*/false); 1974 ImplicitConversionKind SecondConv; 1975 switch (Conv) { 1976 case Sema::Compatible: 1977 SecondConv = ICK_C_Only_Conversion; 1978 break; 1979 // For our purposes, discarding qualifiers is just as bad as using an 1980 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1981 // qualifiers, as well. 1982 case Sema::CompatiblePointerDiscardsQualifiers: 1983 case Sema::IncompatiblePointer: 1984 case Sema::IncompatiblePointerSign: 1985 SecondConv = ICK_Incompatible_Pointer_Conversion; 1986 break; 1987 default: 1988 return false; 1989 } 1990 1991 // First can only be an lvalue conversion, so we pretend that this was the 1992 // second conversion. First should already be valid from earlier in the 1993 // function. 1994 SCS.Second = SecondConv; 1995 SCS.setToType(1, ToType); 1996 1997 // Third is Identity, because Second should rank us worse than any other 1998 // conversion. This could also be ICK_Qualification, but it's simpler to just 1999 // lump everything in with the second conversion, and we don't gain anything 2000 // from making this ICK_Qualification. 2001 SCS.Third = ICK_Identity; 2002 SCS.setToType(2, ToType); 2003 return true; 2004 } 2005 2006 static bool 2007 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2008 QualType &ToType, 2009 bool InOverloadResolution, 2010 StandardConversionSequence &SCS, 2011 bool CStyle) { 2012 2013 const RecordType *UT = ToType->getAsUnionType(); 2014 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2015 return false; 2016 // The field to initialize within the transparent union. 2017 RecordDecl *UD = UT->getDecl(); 2018 // It's compatible if the expression matches any of the fields. 2019 for (const auto *it : UD->fields()) { 2020 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2021 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2022 ToType = it->getType(); 2023 return true; 2024 } 2025 } 2026 return false; 2027 } 2028 2029 /// IsIntegralPromotion - Determines whether the conversion from the 2030 /// expression From (whose potentially-adjusted type is FromType) to 2031 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2032 /// sets PromotedType to the promoted type. 2033 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2034 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2035 // All integers are built-in. 2036 if (!To) { 2037 return false; 2038 } 2039 2040 // An rvalue of type char, signed char, unsigned char, short int, or 2041 // unsigned short int can be converted to an rvalue of type int if 2042 // int can represent all the values of the source type; otherwise, 2043 // the source rvalue can be converted to an rvalue of type unsigned 2044 // int (C++ 4.5p1). 2045 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2046 !FromType->isEnumeralType()) { 2047 if (// We can promote any signed, promotable integer type to an int 2048 (FromType->isSignedIntegerType() || 2049 // We can promote any unsigned integer type whose size is 2050 // less than int to an int. 2051 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2052 return To->getKind() == BuiltinType::Int; 2053 } 2054 2055 return To->getKind() == BuiltinType::UInt; 2056 } 2057 2058 // C++11 [conv.prom]p3: 2059 // A prvalue of an unscoped enumeration type whose underlying type is not 2060 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2061 // following types that can represent all the values of the enumeration 2062 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2063 // unsigned int, long int, unsigned long int, long long int, or unsigned 2064 // long long int. If none of the types in that list can represent all the 2065 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2066 // type can be converted to an rvalue a prvalue of the extended integer type 2067 // with lowest integer conversion rank (4.13) greater than the rank of long 2068 // long in which all the values of the enumeration can be represented. If 2069 // there are two such extended types, the signed one is chosen. 2070 // C++11 [conv.prom]p4: 2071 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2072 // can be converted to a prvalue of its underlying type. Moreover, if 2073 // integral promotion can be applied to its underlying type, a prvalue of an 2074 // unscoped enumeration type whose underlying type is fixed can also be 2075 // converted to a prvalue of the promoted underlying type. 2076 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2077 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2078 // provided for a scoped enumeration. 2079 if (FromEnumType->getDecl()->isScoped()) 2080 return false; 2081 2082 // We can perform an integral promotion to the underlying type of the enum, 2083 // even if that's not the promoted type. Note that the check for promoting 2084 // the underlying type is based on the type alone, and does not consider 2085 // the bitfield-ness of the actual source expression. 2086 if (FromEnumType->getDecl()->isFixed()) { 2087 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2088 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2089 IsIntegralPromotion(nullptr, Underlying, ToType); 2090 } 2091 2092 // We have already pre-calculated the promotion type, so this is trivial. 2093 if (ToType->isIntegerType() && 2094 isCompleteType(From->getBeginLoc(), FromType)) 2095 return Context.hasSameUnqualifiedType( 2096 ToType, FromEnumType->getDecl()->getPromotionType()); 2097 2098 // C++ [conv.prom]p5: 2099 // If the bit-field has an enumerated type, it is treated as any other 2100 // value of that type for promotion purposes. 2101 // 2102 // ... so do not fall through into the bit-field checks below in C++. 2103 if (getLangOpts().CPlusPlus) 2104 return false; 2105 } 2106 2107 // C++0x [conv.prom]p2: 2108 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2109 // to an rvalue a prvalue of the first of the following types that can 2110 // represent all the values of its underlying type: int, unsigned int, 2111 // long int, unsigned long int, long long int, or unsigned long long int. 2112 // If none of the types in that list can represent all the values of its 2113 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2114 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2115 // type. 2116 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2117 ToType->isIntegerType()) { 2118 // Determine whether the type we're converting from is signed or 2119 // unsigned. 2120 bool FromIsSigned = FromType->isSignedIntegerType(); 2121 uint64_t FromSize = Context.getTypeSize(FromType); 2122 2123 // The types we'll try to promote to, in the appropriate 2124 // order. Try each of these types. 2125 QualType PromoteTypes[6] = { 2126 Context.IntTy, Context.UnsignedIntTy, 2127 Context.LongTy, Context.UnsignedLongTy , 2128 Context.LongLongTy, Context.UnsignedLongLongTy 2129 }; 2130 for (int Idx = 0; Idx < 6; ++Idx) { 2131 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2132 if (FromSize < ToSize || 2133 (FromSize == ToSize && 2134 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2135 // We found the type that we can promote to. If this is the 2136 // type we wanted, we have a promotion. Otherwise, no 2137 // promotion. 2138 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2139 } 2140 } 2141 } 2142 2143 // An rvalue for an integral bit-field (9.6) can be converted to an 2144 // rvalue of type int if int can represent all the values of the 2145 // bit-field; otherwise, it can be converted to unsigned int if 2146 // unsigned int can represent all the values of the bit-field. If 2147 // the bit-field is larger yet, no integral promotion applies to 2148 // it. If the bit-field has an enumerated type, it is treated as any 2149 // other value of that type for promotion purposes (C++ 4.5p3). 2150 // FIXME: We should delay checking of bit-fields until we actually perform the 2151 // conversion. 2152 // 2153 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2154 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2155 // bit-fields and those whose underlying type is larger than int) for GCC 2156 // compatibility. 2157 if (From) { 2158 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2159 llvm::APSInt BitWidth; 2160 if (FromType->isIntegralType(Context) && 2161 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2162 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2163 ToSize = Context.getTypeSize(ToType); 2164 2165 // Are we promoting to an int from a bitfield that fits in an int? 2166 if (BitWidth < ToSize || 2167 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2168 return To->getKind() == BuiltinType::Int; 2169 } 2170 2171 // Are we promoting to an unsigned int from an unsigned bitfield 2172 // that fits into an unsigned int? 2173 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2174 return To->getKind() == BuiltinType::UInt; 2175 } 2176 2177 return false; 2178 } 2179 } 2180 } 2181 2182 // An rvalue of type bool can be converted to an rvalue of type int, 2183 // with false becoming zero and true becoming one (C++ 4.5p4). 2184 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2185 return true; 2186 } 2187 2188 return false; 2189 } 2190 2191 /// IsFloatingPointPromotion - Determines whether the conversion from 2192 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2193 /// returns true and sets PromotedType to the promoted type. 2194 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2195 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2196 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2197 /// An rvalue of type float can be converted to an rvalue of type 2198 /// double. (C++ 4.6p1). 2199 if (FromBuiltin->getKind() == BuiltinType::Float && 2200 ToBuiltin->getKind() == BuiltinType::Double) 2201 return true; 2202 2203 // C99 6.3.1.5p1: 2204 // When a float is promoted to double or long double, or a 2205 // double is promoted to long double [...]. 2206 if (!getLangOpts().CPlusPlus && 2207 (FromBuiltin->getKind() == BuiltinType::Float || 2208 FromBuiltin->getKind() == BuiltinType::Double) && 2209 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2210 ToBuiltin->getKind() == BuiltinType::Float128)) 2211 return true; 2212 2213 // Half can be promoted to float. 2214 if (!getLangOpts().NativeHalfType && 2215 FromBuiltin->getKind() == BuiltinType::Half && 2216 ToBuiltin->getKind() == BuiltinType::Float) 2217 return true; 2218 } 2219 2220 return false; 2221 } 2222 2223 /// Determine if a conversion is a complex promotion. 2224 /// 2225 /// A complex promotion is defined as a complex -> complex conversion 2226 /// where the conversion between the underlying real types is a 2227 /// floating-point or integral promotion. 2228 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2229 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2230 if (!FromComplex) 2231 return false; 2232 2233 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2234 if (!ToComplex) 2235 return false; 2236 2237 return IsFloatingPointPromotion(FromComplex->getElementType(), 2238 ToComplex->getElementType()) || 2239 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2240 ToComplex->getElementType()); 2241 } 2242 2243 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2244 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2245 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2246 /// if non-empty, will be a pointer to ToType that may or may not have 2247 /// the right set of qualifiers on its pointee. 2248 /// 2249 static QualType 2250 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2251 QualType ToPointee, QualType ToType, 2252 ASTContext &Context, 2253 bool StripObjCLifetime = false) { 2254 assert((FromPtr->getTypeClass() == Type::Pointer || 2255 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2256 "Invalid similarly-qualified pointer type"); 2257 2258 /// Conversions to 'id' subsume cv-qualifier conversions. 2259 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2260 return ToType.getUnqualifiedType(); 2261 2262 QualType CanonFromPointee 2263 = Context.getCanonicalType(FromPtr->getPointeeType()); 2264 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2265 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2266 2267 if (StripObjCLifetime) 2268 Quals.removeObjCLifetime(); 2269 2270 // Exact qualifier match -> return the pointer type we're converting to. 2271 if (CanonToPointee.getLocalQualifiers() == Quals) { 2272 // ToType is exactly what we need. Return it. 2273 if (!ToType.isNull()) 2274 return ToType.getUnqualifiedType(); 2275 2276 // Build a pointer to ToPointee. It has the right qualifiers 2277 // already. 2278 if (isa<ObjCObjectPointerType>(ToType)) 2279 return Context.getObjCObjectPointerType(ToPointee); 2280 return Context.getPointerType(ToPointee); 2281 } 2282 2283 // Just build a canonical type that has the right qualifiers. 2284 QualType QualifiedCanonToPointee 2285 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2286 2287 if (isa<ObjCObjectPointerType>(ToType)) 2288 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2289 return Context.getPointerType(QualifiedCanonToPointee); 2290 } 2291 2292 static bool isNullPointerConstantForConversion(Expr *Expr, 2293 bool InOverloadResolution, 2294 ASTContext &Context) { 2295 // Handle value-dependent integral null pointer constants correctly. 2296 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2297 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2298 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2299 return !InOverloadResolution; 2300 2301 return Expr->isNullPointerConstant(Context, 2302 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2303 : Expr::NPC_ValueDependentIsNull); 2304 } 2305 2306 /// IsPointerConversion - Determines whether the conversion of the 2307 /// expression From, which has the (possibly adjusted) type FromType, 2308 /// can be converted to the type ToType via a pointer conversion (C++ 2309 /// 4.10). If so, returns true and places the converted type (that 2310 /// might differ from ToType in its cv-qualifiers at some level) into 2311 /// ConvertedType. 2312 /// 2313 /// This routine also supports conversions to and from block pointers 2314 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2315 /// pointers to interfaces. FIXME: Once we've determined the 2316 /// appropriate overloading rules for Objective-C, we may want to 2317 /// split the Objective-C checks into a different routine; however, 2318 /// GCC seems to consider all of these conversions to be pointer 2319 /// conversions, so for now they live here. IncompatibleObjC will be 2320 /// set if the conversion is an allowed Objective-C conversion that 2321 /// should result in a warning. 2322 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2323 bool InOverloadResolution, 2324 QualType& ConvertedType, 2325 bool &IncompatibleObjC) { 2326 IncompatibleObjC = false; 2327 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2328 IncompatibleObjC)) 2329 return true; 2330 2331 // Conversion from a null pointer constant to any Objective-C pointer type. 2332 if (ToType->isObjCObjectPointerType() && 2333 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2334 ConvertedType = ToType; 2335 return true; 2336 } 2337 2338 // Blocks: Block pointers can be converted to void*. 2339 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2340 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2341 ConvertedType = ToType; 2342 return true; 2343 } 2344 // Blocks: A null pointer constant can be converted to a block 2345 // pointer type. 2346 if (ToType->isBlockPointerType() && 2347 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2348 ConvertedType = ToType; 2349 return true; 2350 } 2351 2352 // If the left-hand-side is nullptr_t, the right side can be a null 2353 // pointer constant. 2354 if (ToType->isNullPtrType() && 2355 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2356 ConvertedType = ToType; 2357 return true; 2358 } 2359 2360 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2361 if (!ToTypePtr) 2362 return false; 2363 2364 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2365 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2366 ConvertedType = ToType; 2367 return true; 2368 } 2369 2370 // Beyond this point, both types need to be pointers 2371 // , including objective-c pointers. 2372 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2373 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2374 !getLangOpts().ObjCAutoRefCount) { 2375 ConvertedType = BuildSimilarlyQualifiedPointerType( 2376 FromType->getAs<ObjCObjectPointerType>(), 2377 ToPointeeType, 2378 ToType, Context); 2379 return true; 2380 } 2381 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2382 if (!FromTypePtr) 2383 return false; 2384 2385 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2386 2387 // If the unqualified pointee types are the same, this can't be a 2388 // pointer conversion, so don't do all of the work below. 2389 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2390 return false; 2391 2392 // An rvalue of type "pointer to cv T," where T is an object type, 2393 // can be converted to an rvalue of type "pointer to cv void" (C++ 2394 // 4.10p2). 2395 if (FromPointeeType->isIncompleteOrObjectType() && 2396 ToPointeeType->isVoidType()) { 2397 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2398 ToPointeeType, 2399 ToType, Context, 2400 /*StripObjCLifetime=*/true); 2401 return true; 2402 } 2403 2404 // MSVC allows implicit function to void* type conversion. 2405 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2406 ToPointeeType->isVoidType()) { 2407 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2408 ToPointeeType, 2409 ToType, Context); 2410 return true; 2411 } 2412 2413 // When we're overloading in C, we allow a special kind of pointer 2414 // conversion for compatible-but-not-identical pointee types. 2415 if (!getLangOpts().CPlusPlus && 2416 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2417 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2418 ToPointeeType, 2419 ToType, Context); 2420 return true; 2421 } 2422 2423 // C++ [conv.ptr]p3: 2424 // 2425 // An rvalue of type "pointer to cv D," where D is a class type, 2426 // can be converted to an rvalue of type "pointer to cv B," where 2427 // B is a base class (clause 10) of D. If B is an inaccessible 2428 // (clause 11) or ambiguous (10.2) base class of D, a program that 2429 // necessitates this conversion is ill-formed. The result of the 2430 // conversion is a pointer to the base class sub-object of the 2431 // derived class object. The null pointer value is converted to 2432 // the null pointer value of the destination type. 2433 // 2434 // Note that we do not check for ambiguity or inaccessibility 2435 // here. That is handled by CheckPointerConversion. 2436 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2437 ToPointeeType->isRecordType() && 2438 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2439 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2440 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2441 ToPointeeType, 2442 ToType, Context); 2443 return true; 2444 } 2445 2446 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2447 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2449 ToPointeeType, 2450 ToType, Context); 2451 return true; 2452 } 2453 2454 return false; 2455 } 2456 2457 /// Adopt the given qualifiers for the given type. 2458 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2459 Qualifiers TQs = T.getQualifiers(); 2460 2461 // Check whether qualifiers already match. 2462 if (TQs == Qs) 2463 return T; 2464 2465 if (Qs.compatiblyIncludes(TQs)) 2466 return Context.getQualifiedType(T, Qs); 2467 2468 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2469 } 2470 2471 /// isObjCPointerConversion - Determines whether this is an 2472 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2473 /// with the same arguments and return values. 2474 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2475 QualType& ConvertedType, 2476 bool &IncompatibleObjC) { 2477 if (!getLangOpts().ObjC) 2478 return false; 2479 2480 // The set of qualifiers on the type we're converting from. 2481 Qualifiers FromQualifiers = FromType.getQualifiers(); 2482 2483 // First, we handle all conversions on ObjC object pointer types. 2484 const ObjCObjectPointerType* ToObjCPtr = 2485 ToType->getAs<ObjCObjectPointerType>(); 2486 const ObjCObjectPointerType *FromObjCPtr = 2487 FromType->getAs<ObjCObjectPointerType>(); 2488 2489 if (ToObjCPtr && FromObjCPtr) { 2490 // If the pointee types are the same (ignoring qualifications), 2491 // then this is not a pointer conversion. 2492 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2493 FromObjCPtr->getPointeeType())) 2494 return false; 2495 2496 // Conversion between Objective-C pointers. 2497 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2498 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2499 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2500 if (getLangOpts().CPlusPlus && LHS && RHS && 2501 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2502 FromObjCPtr->getPointeeType())) 2503 return false; 2504 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2505 ToObjCPtr->getPointeeType(), 2506 ToType, Context); 2507 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2508 return true; 2509 } 2510 2511 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2512 // Okay: this is some kind of implicit downcast of Objective-C 2513 // interfaces, which is permitted. However, we're going to 2514 // complain about it. 2515 IncompatibleObjC = true; 2516 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2517 ToObjCPtr->getPointeeType(), 2518 ToType, Context); 2519 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2520 return true; 2521 } 2522 } 2523 // Beyond this point, both types need to be C pointers or block pointers. 2524 QualType ToPointeeType; 2525 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2526 ToPointeeType = ToCPtr->getPointeeType(); 2527 else if (const BlockPointerType *ToBlockPtr = 2528 ToType->getAs<BlockPointerType>()) { 2529 // Objective C++: We're able to convert from a pointer to any object 2530 // to a block pointer type. 2531 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2532 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2533 return true; 2534 } 2535 ToPointeeType = ToBlockPtr->getPointeeType(); 2536 } 2537 else if (FromType->getAs<BlockPointerType>() && 2538 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2539 // Objective C++: We're able to convert from a block pointer type to a 2540 // pointer to any object. 2541 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2542 return true; 2543 } 2544 else 2545 return false; 2546 2547 QualType FromPointeeType; 2548 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2549 FromPointeeType = FromCPtr->getPointeeType(); 2550 else if (const BlockPointerType *FromBlockPtr = 2551 FromType->getAs<BlockPointerType>()) 2552 FromPointeeType = FromBlockPtr->getPointeeType(); 2553 else 2554 return false; 2555 2556 // If we have pointers to pointers, recursively check whether this 2557 // is an Objective-C conversion. 2558 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2559 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2560 IncompatibleObjC)) { 2561 // We always complain about this conversion. 2562 IncompatibleObjC = true; 2563 ConvertedType = Context.getPointerType(ConvertedType); 2564 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2565 return true; 2566 } 2567 // Allow conversion of pointee being objective-c pointer to another one; 2568 // as in I* to id. 2569 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2570 ToPointeeType->getAs<ObjCObjectPointerType>() && 2571 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2572 IncompatibleObjC)) { 2573 2574 ConvertedType = Context.getPointerType(ConvertedType); 2575 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2576 return true; 2577 } 2578 2579 // If we have pointers to functions or blocks, check whether the only 2580 // differences in the argument and result types are in Objective-C 2581 // pointer conversions. If so, we permit the conversion (but 2582 // complain about it). 2583 const FunctionProtoType *FromFunctionType 2584 = FromPointeeType->getAs<FunctionProtoType>(); 2585 const FunctionProtoType *ToFunctionType 2586 = ToPointeeType->getAs<FunctionProtoType>(); 2587 if (FromFunctionType && ToFunctionType) { 2588 // If the function types are exactly the same, this isn't an 2589 // Objective-C pointer conversion. 2590 if (Context.getCanonicalType(FromPointeeType) 2591 == Context.getCanonicalType(ToPointeeType)) 2592 return false; 2593 2594 // Perform the quick checks that will tell us whether these 2595 // function types are obviously different. 2596 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2597 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2598 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2599 return false; 2600 2601 bool HasObjCConversion = false; 2602 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2603 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2604 // Okay, the types match exactly. Nothing to do. 2605 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2606 ToFunctionType->getReturnType(), 2607 ConvertedType, IncompatibleObjC)) { 2608 // Okay, we have an Objective-C pointer conversion. 2609 HasObjCConversion = true; 2610 } else { 2611 // Function types are too different. Abort. 2612 return false; 2613 } 2614 2615 // Check argument types. 2616 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2617 ArgIdx != NumArgs; ++ArgIdx) { 2618 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2619 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2620 if (Context.getCanonicalType(FromArgType) 2621 == Context.getCanonicalType(ToArgType)) { 2622 // Okay, the types match exactly. Nothing to do. 2623 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2624 ConvertedType, IncompatibleObjC)) { 2625 // Okay, we have an Objective-C pointer conversion. 2626 HasObjCConversion = true; 2627 } else { 2628 // Argument types are too different. Abort. 2629 return false; 2630 } 2631 } 2632 2633 if (HasObjCConversion) { 2634 // We had an Objective-C conversion. Allow this pointer 2635 // conversion, but complain about it. 2636 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2637 IncompatibleObjC = true; 2638 return true; 2639 } 2640 } 2641 2642 return false; 2643 } 2644 2645 /// Determine whether this is an Objective-C writeback conversion, 2646 /// used for parameter passing when performing automatic reference counting. 2647 /// 2648 /// \param FromType The type we're converting form. 2649 /// 2650 /// \param ToType The type we're converting to. 2651 /// 2652 /// \param ConvertedType The type that will be produced after applying 2653 /// this conversion. 2654 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2655 QualType &ConvertedType) { 2656 if (!getLangOpts().ObjCAutoRefCount || 2657 Context.hasSameUnqualifiedType(FromType, ToType)) 2658 return false; 2659 2660 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2661 QualType ToPointee; 2662 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2663 ToPointee = ToPointer->getPointeeType(); 2664 else 2665 return false; 2666 2667 Qualifiers ToQuals = ToPointee.getQualifiers(); 2668 if (!ToPointee->isObjCLifetimeType() || 2669 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2670 !ToQuals.withoutObjCLifetime().empty()) 2671 return false; 2672 2673 // Argument must be a pointer to __strong to __weak. 2674 QualType FromPointee; 2675 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2676 FromPointee = FromPointer->getPointeeType(); 2677 else 2678 return false; 2679 2680 Qualifiers FromQuals = FromPointee.getQualifiers(); 2681 if (!FromPointee->isObjCLifetimeType() || 2682 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2683 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2684 return false; 2685 2686 // Make sure that we have compatible qualifiers. 2687 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2688 if (!ToQuals.compatiblyIncludes(FromQuals)) 2689 return false; 2690 2691 // Remove qualifiers from the pointee type we're converting from; they 2692 // aren't used in the compatibility check belong, and we'll be adding back 2693 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2694 FromPointee = FromPointee.getUnqualifiedType(); 2695 2696 // The unqualified form of the pointee types must be compatible. 2697 ToPointee = ToPointee.getUnqualifiedType(); 2698 bool IncompatibleObjC; 2699 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2700 FromPointee = ToPointee; 2701 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2702 IncompatibleObjC)) 2703 return false; 2704 2705 /// Construct the type we're converting to, which is a pointer to 2706 /// __autoreleasing pointee. 2707 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2708 ConvertedType = Context.getPointerType(FromPointee); 2709 return true; 2710 } 2711 2712 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2713 QualType& ConvertedType) { 2714 QualType ToPointeeType; 2715 if (const BlockPointerType *ToBlockPtr = 2716 ToType->getAs<BlockPointerType>()) 2717 ToPointeeType = ToBlockPtr->getPointeeType(); 2718 else 2719 return false; 2720 2721 QualType FromPointeeType; 2722 if (const BlockPointerType *FromBlockPtr = 2723 FromType->getAs<BlockPointerType>()) 2724 FromPointeeType = FromBlockPtr->getPointeeType(); 2725 else 2726 return false; 2727 // We have pointer to blocks, check whether the only 2728 // differences in the argument and result types are in Objective-C 2729 // pointer conversions. If so, we permit the conversion. 2730 2731 const FunctionProtoType *FromFunctionType 2732 = FromPointeeType->getAs<FunctionProtoType>(); 2733 const FunctionProtoType *ToFunctionType 2734 = ToPointeeType->getAs<FunctionProtoType>(); 2735 2736 if (!FromFunctionType || !ToFunctionType) 2737 return false; 2738 2739 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2740 return true; 2741 2742 // Perform the quick checks that will tell us whether these 2743 // function types are obviously different. 2744 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2745 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2746 return false; 2747 2748 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2749 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2750 if (FromEInfo != ToEInfo) 2751 return false; 2752 2753 bool IncompatibleObjC = false; 2754 if (Context.hasSameType(FromFunctionType->getReturnType(), 2755 ToFunctionType->getReturnType())) { 2756 // Okay, the types match exactly. Nothing to do. 2757 } else { 2758 QualType RHS = FromFunctionType->getReturnType(); 2759 QualType LHS = ToFunctionType->getReturnType(); 2760 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2761 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2762 LHS = LHS.getUnqualifiedType(); 2763 2764 if (Context.hasSameType(RHS,LHS)) { 2765 // OK exact match. 2766 } else if (isObjCPointerConversion(RHS, LHS, 2767 ConvertedType, IncompatibleObjC)) { 2768 if (IncompatibleObjC) 2769 return false; 2770 // Okay, we have an Objective-C pointer conversion. 2771 } 2772 else 2773 return false; 2774 } 2775 2776 // Check argument types. 2777 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2778 ArgIdx != NumArgs; ++ArgIdx) { 2779 IncompatibleObjC = false; 2780 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2781 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2782 if (Context.hasSameType(FromArgType, ToArgType)) { 2783 // Okay, the types match exactly. Nothing to do. 2784 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2785 ConvertedType, IncompatibleObjC)) { 2786 if (IncompatibleObjC) 2787 return false; 2788 // Okay, we have an Objective-C pointer conversion. 2789 } else 2790 // Argument types are too different. Abort. 2791 return false; 2792 } 2793 2794 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2795 bool CanUseToFPT, CanUseFromFPT; 2796 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2797 CanUseToFPT, CanUseFromFPT, 2798 NewParamInfos)) 2799 return false; 2800 2801 ConvertedType = ToType; 2802 return true; 2803 } 2804 2805 enum { 2806 ft_default, 2807 ft_different_class, 2808 ft_parameter_arity, 2809 ft_parameter_mismatch, 2810 ft_return_type, 2811 ft_qualifer_mismatch, 2812 ft_noexcept 2813 }; 2814 2815 /// Attempts to get the FunctionProtoType from a Type. Handles 2816 /// MemberFunctionPointers properly. 2817 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2818 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2819 return FPT; 2820 2821 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2822 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2823 2824 return nullptr; 2825 } 2826 2827 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2828 /// function types. Catches different number of parameter, mismatch in 2829 /// parameter types, and different return types. 2830 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2831 QualType FromType, QualType ToType) { 2832 // If either type is not valid, include no extra info. 2833 if (FromType.isNull() || ToType.isNull()) { 2834 PDiag << ft_default; 2835 return; 2836 } 2837 2838 // Get the function type from the pointers. 2839 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2840 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2841 *ToMember = ToType->getAs<MemberPointerType>(); 2842 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2843 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2844 << QualType(FromMember->getClass(), 0); 2845 return; 2846 } 2847 FromType = FromMember->getPointeeType(); 2848 ToType = ToMember->getPointeeType(); 2849 } 2850 2851 if (FromType->isPointerType()) 2852 FromType = FromType->getPointeeType(); 2853 if (ToType->isPointerType()) 2854 ToType = ToType->getPointeeType(); 2855 2856 // Remove references. 2857 FromType = FromType.getNonReferenceType(); 2858 ToType = ToType.getNonReferenceType(); 2859 2860 // Don't print extra info for non-specialized template functions. 2861 if (FromType->isInstantiationDependentType() && 2862 !FromType->getAs<TemplateSpecializationType>()) { 2863 PDiag << ft_default; 2864 return; 2865 } 2866 2867 // No extra info for same types. 2868 if (Context.hasSameType(FromType, ToType)) { 2869 PDiag << ft_default; 2870 return; 2871 } 2872 2873 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2874 *ToFunction = tryGetFunctionProtoType(ToType); 2875 2876 // Both types need to be function types. 2877 if (!FromFunction || !ToFunction) { 2878 PDiag << ft_default; 2879 return; 2880 } 2881 2882 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2883 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2884 << FromFunction->getNumParams(); 2885 return; 2886 } 2887 2888 // Handle different parameter types. 2889 unsigned ArgPos; 2890 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2891 PDiag << ft_parameter_mismatch << ArgPos + 1 2892 << ToFunction->getParamType(ArgPos) 2893 << FromFunction->getParamType(ArgPos); 2894 return; 2895 } 2896 2897 // Handle different return type. 2898 if (!Context.hasSameType(FromFunction->getReturnType(), 2899 ToFunction->getReturnType())) { 2900 PDiag << ft_return_type << ToFunction->getReturnType() 2901 << FromFunction->getReturnType(); 2902 return; 2903 } 2904 2905 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2906 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2907 << FromFunction->getMethodQuals(); 2908 return; 2909 } 2910 2911 // Handle exception specification differences on canonical type (in C++17 2912 // onwards). 2913 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2914 ->isNothrow() != 2915 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2916 ->isNothrow()) { 2917 PDiag << ft_noexcept; 2918 return; 2919 } 2920 2921 // Unable to find a difference, so add no extra info. 2922 PDiag << ft_default; 2923 } 2924 2925 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2926 /// for equality of their argument types. Caller has already checked that 2927 /// they have same number of arguments. If the parameters are different, 2928 /// ArgPos will have the parameter index of the first different parameter. 2929 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2930 const FunctionProtoType *NewType, 2931 unsigned *ArgPos) { 2932 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2933 N = NewType->param_type_begin(), 2934 E = OldType->param_type_end(); 2935 O && (O != E); ++O, ++N) { 2936 // Ignore address spaces in pointee type. This is to disallow overloading 2937 // on __ptr32/__ptr64 address spaces. 2938 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2939 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2940 2941 if (!Context.hasSameType(Old, New)) { 2942 if (ArgPos) 2943 *ArgPos = O - OldType->param_type_begin(); 2944 return false; 2945 } 2946 } 2947 return true; 2948 } 2949 2950 /// CheckPointerConversion - Check the pointer conversion from the 2951 /// expression From to the type ToType. This routine checks for 2952 /// ambiguous or inaccessible derived-to-base pointer 2953 /// conversions for which IsPointerConversion has already returned 2954 /// true. It returns true and produces a diagnostic if there was an 2955 /// error, or returns false otherwise. 2956 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2957 CastKind &Kind, 2958 CXXCastPath& BasePath, 2959 bool IgnoreBaseAccess, 2960 bool Diagnose) { 2961 QualType FromType = From->getType(); 2962 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2963 2964 Kind = CK_BitCast; 2965 2966 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2967 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2968 Expr::NPCK_ZeroExpression) { 2969 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2970 DiagRuntimeBehavior(From->getExprLoc(), From, 2971 PDiag(diag::warn_impcast_bool_to_null_pointer) 2972 << ToType << From->getSourceRange()); 2973 else if (!isUnevaluatedContext()) 2974 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2975 << ToType << From->getSourceRange(); 2976 } 2977 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2978 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2979 QualType FromPointeeType = FromPtrType->getPointeeType(), 2980 ToPointeeType = ToPtrType->getPointeeType(); 2981 2982 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2983 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2984 // We must have a derived-to-base conversion. Check an 2985 // ambiguous or inaccessible conversion. 2986 unsigned InaccessibleID = 0; 2987 unsigned AmbigiousID = 0; 2988 if (Diagnose) { 2989 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2990 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2991 } 2992 if (CheckDerivedToBaseConversion( 2993 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2994 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2995 &BasePath, IgnoreBaseAccess)) 2996 return true; 2997 2998 // The conversion was successful. 2999 Kind = CK_DerivedToBase; 3000 } 3001 3002 if (Diagnose && !IsCStyleOrFunctionalCast && 3003 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3004 assert(getLangOpts().MSVCCompat && 3005 "this should only be possible with MSVCCompat!"); 3006 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3007 << From->getSourceRange(); 3008 } 3009 } 3010 } else if (const ObjCObjectPointerType *ToPtrType = 3011 ToType->getAs<ObjCObjectPointerType>()) { 3012 if (const ObjCObjectPointerType *FromPtrType = 3013 FromType->getAs<ObjCObjectPointerType>()) { 3014 // Objective-C++ conversions are always okay. 3015 // FIXME: We should have a different class of conversions for the 3016 // Objective-C++ implicit conversions. 3017 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3018 return false; 3019 } else if (FromType->isBlockPointerType()) { 3020 Kind = CK_BlockPointerToObjCPointerCast; 3021 } else { 3022 Kind = CK_CPointerToObjCPointerCast; 3023 } 3024 } else if (ToType->isBlockPointerType()) { 3025 if (!FromType->isBlockPointerType()) 3026 Kind = CK_AnyPointerToBlockPointerCast; 3027 } 3028 3029 // We shouldn't fall into this case unless it's valid for other 3030 // reasons. 3031 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3032 Kind = CK_NullToPointer; 3033 3034 return false; 3035 } 3036 3037 /// IsMemberPointerConversion - Determines whether the conversion of the 3038 /// expression From, which has the (possibly adjusted) type FromType, can be 3039 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3040 /// If so, returns true and places the converted type (that might differ from 3041 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3042 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3043 QualType ToType, 3044 bool InOverloadResolution, 3045 QualType &ConvertedType) { 3046 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3047 if (!ToTypePtr) 3048 return false; 3049 3050 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3051 if (From->isNullPointerConstant(Context, 3052 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3053 : Expr::NPC_ValueDependentIsNull)) { 3054 ConvertedType = ToType; 3055 return true; 3056 } 3057 3058 // Otherwise, both types have to be member pointers. 3059 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3060 if (!FromTypePtr) 3061 return false; 3062 3063 // A pointer to member of B can be converted to a pointer to member of D, 3064 // where D is derived from B (C++ 4.11p2). 3065 QualType FromClass(FromTypePtr->getClass(), 0); 3066 QualType ToClass(ToTypePtr->getClass(), 0); 3067 3068 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3069 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3070 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3071 ToClass.getTypePtr()); 3072 return true; 3073 } 3074 3075 return false; 3076 } 3077 3078 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3079 /// expression From to the type ToType. This routine checks for ambiguous or 3080 /// virtual or inaccessible base-to-derived member pointer conversions 3081 /// for which IsMemberPointerConversion has already returned true. It returns 3082 /// true and produces a diagnostic if there was an error, or returns false 3083 /// otherwise. 3084 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3085 CastKind &Kind, 3086 CXXCastPath &BasePath, 3087 bool IgnoreBaseAccess) { 3088 QualType FromType = From->getType(); 3089 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3090 if (!FromPtrType) { 3091 // This must be a null pointer to member pointer conversion 3092 assert(From->isNullPointerConstant(Context, 3093 Expr::NPC_ValueDependentIsNull) && 3094 "Expr must be null pointer constant!"); 3095 Kind = CK_NullToMemberPointer; 3096 return false; 3097 } 3098 3099 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3100 assert(ToPtrType && "No member pointer cast has a target type " 3101 "that is not a member pointer."); 3102 3103 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3104 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3105 3106 // FIXME: What about dependent types? 3107 assert(FromClass->isRecordType() && "Pointer into non-class."); 3108 assert(ToClass->isRecordType() && "Pointer into non-class."); 3109 3110 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3111 /*DetectVirtual=*/true); 3112 bool DerivationOkay = 3113 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3114 assert(DerivationOkay && 3115 "Should not have been called if derivation isn't OK."); 3116 (void)DerivationOkay; 3117 3118 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3119 getUnqualifiedType())) { 3120 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3121 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3122 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3123 return true; 3124 } 3125 3126 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3127 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3128 << FromClass << ToClass << QualType(VBase, 0) 3129 << From->getSourceRange(); 3130 return true; 3131 } 3132 3133 if (!IgnoreBaseAccess) 3134 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3135 Paths.front(), 3136 diag::err_downcast_from_inaccessible_base); 3137 3138 // Must be a base to derived member conversion. 3139 BuildBasePathArray(Paths, BasePath); 3140 Kind = CK_BaseToDerivedMemberPointer; 3141 return false; 3142 } 3143 3144 /// Determine whether the lifetime conversion between the two given 3145 /// qualifiers sets is nontrivial. 3146 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3147 Qualifiers ToQuals) { 3148 // Converting anything to const __unsafe_unretained is trivial. 3149 if (ToQuals.hasConst() && 3150 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3151 return false; 3152 3153 return true; 3154 } 3155 3156 /// IsQualificationConversion - Determines whether the conversion from 3157 /// an rvalue of type FromType to ToType is a qualification conversion 3158 /// (C++ 4.4). 3159 /// 3160 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3161 /// when the qualification conversion involves a change in the Objective-C 3162 /// object lifetime. 3163 bool 3164 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3165 bool CStyle, bool &ObjCLifetimeConversion) { 3166 FromType = Context.getCanonicalType(FromType); 3167 ToType = Context.getCanonicalType(ToType); 3168 ObjCLifetimeConversion = false; 3169 3170 // If FromType and ToType are the same type, this is not a 3171 // qualification conversion. 3172 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3173 return false; 3174 3175 // (C++ 4.4p4): 3176 // A conversion can add cv-qualifiers at levels other than the first 3177 // in multi-level pointers, subject to the following rules: [...] 3178 bool PreviousToQualsIncludeConst = true; 3179 bool UnwrappedAnyPointer = false; 3180 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3181 // Within each iteration of the loop, we check the qualifiers to 3182 // determine if this still looks like a qualification 3183 // conversion. Then, if all is well, we unwrap one more level of 3184 // pointers or pointers-to-members and do it all again 3185 // until there are no more pointers or pointers-to-members left to 3186 // unwrap. 3187 UnwrappedAnyPointer = true; 3188 3189 Qualifiers FromQuals = FromType.getQualifiers(); 3190 Qualifiers ToQuals = ToType.getQualifiers(); 3191 3192 // Ignore __unaligned qualifier if this type is void. 3193 if (ToType.getUnqualifiedType()->isVoidType()) 3194 FromQuals.removeUnaligned(); 3195 3196 // Objective-C ARC: 3197 // Check Objective-C lifetime conversions. 3198 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3199 UnwrappedAnyPointer) { 3200 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3201 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3202 ObjCLifetimeConversion = true; 3203 FromQuals.removeObjCLifetime(); 3204 ToQuals.removeObjCLifetime(); 3205 } else { 3206 // Qualification conversions cannot cast between different 3207 // Objective-C lifetime qualifiers. 3208 return false; 3209 } 3210 } 3211 3212 // Allow addition/removal of GC attributes but not changing GC attributes. 3213 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3214 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3215 FromQuals.removeObjCGCAttr(); 3216 ToQuals.removeObjCGCAttr(); 3217 } 3218 3219 // -- for every j > 0, if const is in cv 1,j then const is in cv 3220 // 2,j, and similarly for volatile. 3221 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3222 return false; 3223 3224 // -- if the cv 1,j and cv 2,j are different, then const is in 3225 // every cv for 0 < k < j. 3226 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3227 && !PreviousToQualsIncludeConst) 3228 return false; 3229 3230 // Keep track of whether all prior cv-qualifiers in the "to" type 3231 // include const. 3232 PreviousToQualsIncludeConst 3233 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3234 } 3235 3236 // Allows address space promotion by language rules implemented in 3237 // Type::Qualifiers::isAddressSpaceSupersetOf. 3238 Qualifiers FromQuals = FromType.getQualifiers(); 3239 Qualifiers ToQuals = ToType.getQualifiers(); 3240 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3241 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3242 return false; 3243 } 3244 3245 // We are left with FromType and ToType being the pointee types 3246 // after unwrapping the original FromType and ToType the same number 3247 // of types. If we unwrapped any pointers, and if FromType and 3248 // ToType have the same unqualified type (since we checked 3249 // qualifiers above), then this is a qualification conversion. 3250 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3251 } 3252 3253 /// - Determine whether this is a conversion from a scalar type to an 3254 /// atomic type. 3255 /// 3256 /// If successful, updates \c SCS's second and third steps in the conversion 3257 /// sequence to finish the conversion. 3258 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3259 bool InOverloadResolution, 3260 StandardConversionSequence &SCS, 3261 bool CStyle) { 3262 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3263 if (!ToAtomic) 3264 return false; 3265 3266 StandardConversionSequence InnerSCS; 3267 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3268 InOverloadResolution, InnerSCS, 3269 CStyle, /*AllowObjCWritebackConversion=*/false)) 3270 return false; 3271 3272 SCS.Second = InnerSCS.Second; 3273 SCS.setToType(1, InnerSCS.getToType(1)); 3274 SCS.Third = InnerSCS.Third; 3275 SCS.QualificationIncludesObjCLifetime 3276 = InnerSCS.QualificationIncludesObjCLifetime; 3277 SCS.setToType(2, InnerSCS.getToType(2)); 3278 return true; 3279 } 3280 3281 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3282 CXXConstructorDecl *Constructor, 3283 QualType Type) { 3284 const FunctionProtoType *CtorType = 3285 Constructor->getType()->getAs<FunctionProtoType>(); 3286 if (CtorType->getNumParams() > 0) { 3287 QualType FirstArg = CtorType->getParamType(0); 3288 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3289 return true; 3290 } 3291 return false; 3292 } 3293 3294 static OverloadingResult 3295 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3296 CXXRecordDecl *To, 3297 UserDefinedConversionSequence &User, 3298 OverloadCandidateSet &CandidateSet, 3299 bool AllowExplicit) { 3300 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3301 for (auto *D : S.LookupConstructors(To)) { 3302 auto Info = getConstructorInfo(D); 3303 if (!Info) 3304 continue; 3305 3306 bool Usable = !Info.Constructor->isInvalidDecl() && 3307 S.isInitListConstructor(Info.Constructor) && 3308 (AllowExplicit || !Info.Constructor->isExplicit()); 3309 if (Usable) { 3310 // If the first argument is (a reference to) the target type, 3311 // suppress conversions. 3312 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3313 S.Context, Info.Constructor, ToType); 3314 if (Info.ConstructorTmpl) 3315 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3316 /*ExplicitArgs*/ nullptr, From, 3317 CandidateSet, SuppressUserConversions, 3318 /*PartialOverloading*/ false, 3319 AllowExplicit); 3320 else 3321 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3322 CandidateSet, SuppressUserConversions, 3323 /*PartialOverloading*/ false, AllowExplicit); 3324 } 3325 } 3326 3327 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3328 3329 OverloadCandidateSet::iterator Best; 3330 switch (auto Result = 3331 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3332 case OR_Deleted: 3333 case OR_Success: { 3334 // Record the standard conversion we used and the conversion function. 3335 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3336 QualType ThisType = Constructor->getThisType(); 3337 // Initializer lists don't have conversions as such. 3338 User.Before.setAsIdentityConversion(); 3339 User.HadMultipleCandidates = HadMultipleCandidates; 3340 User.ConversionFunction = Constructor; 3341 User.FoundConversionFunction = Best->FoundDecl; 3342 User.After.setAsIdentityConversion(); 3343 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3344 User.After.setAllToTypes(ToType); 3345 return Result; 3346 } 3347 3348 case OR_No_Viable_Function: 3349 return OR_No_Viable_Function; 3350 case OR_Ambiguous: 3351 return OR_Ambiguous; 3352 } 3353 3354 llvm_unreachable("Invalid OverloadResult!"); 3355 } 3356 3357 /// Determines whether there is a user-defined conversion sequence 3358 /// (C++ [over.ics.user]) that converts expression From to the type 3359 /// ToType. If such a conversion exists, User will contain the 3360 /// user-defined conversion sequence that performs such a conversion 3361 /// and this routine will return true. Otherwise, this routine returns 3362 /// false and User is unspecified. 3363 /// 3364 /// \param AllowExplicit true if the conversion should consider C++0x 3365 /// "explicit" conversion functions as well as non-explicit conversion 3366 /// functions (C++0x [class.conv.fct]p2). 3367 /// 3368 /// \param AllowObjCConversionOnExplicit true if the conversion should 3369 /// allow an extra Objective-C pointer conversion on uses of explicit 3370 /// constructors. Requires \c AllowExplicit to also be set. 3371 static OverloadingResult 3372 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3373 UserDefinedConversionSequence &User, 3374 OverloadCandidateSet &CandidateSet, 3375 bool AllowExplicit, 3376 bool AllowObjCConversionOnExplicit) { 3377 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3378 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3379 3380 // Whether we will only visit constructors. 3381 bool ConstructorsOnly = false; 3382 3383 // If the type we are conversion to is a class type, enumerate its 3384 // constructors. 3385 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3386 // C++ [over.match.ctor]p1: 3387 // When objects of class type are direct-initialized (8.5), or 3388 // copy-initialized from an expression of the same or a 3389 // derived class type (8.5), overload resolution selects the 3390 // constructor. [...] For copy-initialization, the candidate 3391 // functions are all the converting constructors (12.3.1) of 3392 // that class. The argument list is the expression-list within 3393 // the parentheses of the initializer. 3394 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3395 (From->getType()->getAs<RecordType>() && 3396 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3397 ConstructorsOnly = true; 3398 3399 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3400 // We're not going to find any constructors. 3401 } else if (CXXRecordDecl *ToRecordDecl 3402 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3403 3404 Expr **Args = &From; 3405 unsigned NumArgs = 1; 3406 bool ListInitializing = false; 3407 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3408 // But first, see if there is an init-list-constructor that will work. 3409 OverloadingResult Result = IsInitializerListConstructorConversion( 3410 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3411 if (Result != OR_No_Viable_Function) 3412 return Result; 3413 // Never mind. 3414 CandidateSet.clear( 3415 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3416 3417 // If we're list-initializing, we pass the individual elements as 3418 // arguments, not the entire list. 3419 Args = InitList->getInits(); 3420 NumArgs = InitList->getNumInits(); 3421 ListInitializing = true; 3422 } 3423 3424 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3425 auto Info = getConstructorInfo(D); 3426 if (!Info) 3427 continue; 3428 3429 bool Usable = !Info.Constructor->isInvalidDecl(); 3430 if (ListInitializing) 3431 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3432 else 3433 Usable = Usable && 3434 Info.Constructor->isConvertingConstructor(AllowExplicit); 3435 if (Usable) { 3436 bool SuppressUserConversions = !ConstructorsOnly; 3437 if (SuppressUserConversions && ListInitializing) { 3438 SuppressUserConversions = false; 3439 if (NumArgs == 1) { 3440 // If the first argument is (a reference to) the target type, 3441 // suppress conversions. 3442 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3443 S.Context, Info.Constructor, ToType); 3444 } 3445 } 3446 if (Info.ConstructorTmpl) 3447 S.AddTemplateOverloadCandidate( 3448 Info.ConstructorTmpl, Info.FoundDecl, 3449 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3450 CandidateSet, SuppressUserConversions, 3451 /*PartialOverloading*/ false, AllowExplicit); 3452 else 3453 // Allow one user-defined conversion when user specifies a 3454 // From->ToType conversion via an static cast (c-style, etc). 3455 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3456 llvm::makeArrayRef(Args, NumArgs), 3457 CandidateSet, SuppressUserConversions, 3458 /*PartialOverloading*/ false, AllowExplicit); 3459 } 3460 } 3461 } 3462 } 3463 3464 // Enumerate conversion functions, if we're allowed to. 3465 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3466 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3467 // No conversion functions from incomplete types. 3468 } else if (const RecordType *FromRecordType = 3469 From->getType()->getAs<RecordType>()) { 3470 if (CXXRecordDecl *FromRecordDecl 3471 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3472 // Add all of the conversion functions as candidates. 3473 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3474 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3475 DeclAccessPair FoundDecl = I.getPair(); 3476 NamedDecl *D = FoundDecl.getDecl(); 3477 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3478 if (isa<UsingShadowDecl>(D)) 3479 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3480 3481 CXXConversionDecl *Conv; 3482 FunctionTemplateDecl *ConvTemplate; 3483 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3484 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3485 else 3486 Conv = cast<CXXConversionDecl>(D); 3487 3488 if (AllowExplicit || !Conv->isExplicit()) { 3489 if (ConvTemplate) 3490 S.AddTemplateConversionCandidate( 3491 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3492 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3493 else 3494 S.AddConversionCandidate( 3495 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3496 AllowObjCConversionOnExplicit, AllowExplicit); 3497 } 3498 } 3499 } 3500 } 3501 3502 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3503 3504 OverloadCandidateSet::iterator Best; 3505 switch (auto Result = 3506 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3507 case OR_Success: 3508 case OR_Deleted: 3509 // Record the standard conversion we used and the conversion function. 3510 if (CXXConstructorDecl *Constructor 3511 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3512 // C++ [over.ics.user]p1: 3513 // If the user-defined conversion is specified by a 3514 // constructor (12.3.1), the initial standard conversion 3515 // sequence converts the source type to the type required by 3516 // the argument of the constructor. 3517 // 3518 QualType ThisType = Constructor->getThisType(); 3519 if (isa<InitListExpr>(From)) { 3520 // Initializer lists don't have conversions as such. 3521 User.Before.setAsIdentityConversion(); 3522 } else { 3523 if (Best->Conversions[0].isEllipsis()) 3524 User.EllipsisConversion = true; 3525 else { 3526 User.Before = Best->Conversions[0].Standard; 3527 User.EllipsisConversion = false; 3528 } 3529 } 3530 User.HadMultipleCandidates = HadMultipleCandidates; 3531 User.ConversionFunction = Constructor; 3532 User.FoundConversionFunction = Best->FoundDecl; 3533 User.After.setAsIdentityConversion(); 3534 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3535 User.After.setAllToTypes(ToType); 3536 return Result; 3537 } 3538 if (CXXConversionDecl *Conversion 3539 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3540 // C++ [over.ics.user]p1: 3541 // 3542 // [...] If the user-defined conversion is specified by a 3543 // conversion function (12.3.2), the initial standard 3544 // conversion sequence converts the source type to the 3545 // implicit object parameter of the conversion function. 3546 User.Before = Best->Conversions[0].Standard; 3547 User.HadMultipleCandidates = HadMultipleCandidates; 3548 User.ConversionFunction = Conversion; 3549 User.FoundConversionFunction = Best->FoundDecl; 3550 User.EllipsisConversion = false; 3551 3552 // C++ [over.ics.user]p2: 3553 // The second standard conversion sequence converts the 3554 // result of the user-defined conversion to the target type 3555 // for the sequence. Since an implicit conversion sequence 3556 // is an initialization, the special rules for 3557 // initialization by user-defined conversion apply when 3558 // selecting the best user-defined conversion for a 3559 // user-defined conversion sequence (see 13.3.3 and 3560 // 13.3.3.1). 3561 User.After = Best->FinalConversion; 3562 return Result; 3563 } 3564 llvm_unreachable("Not a constructor or conversion function?"); 3565 3566 case OR_No_Viable_Function: 3567 return OR_No_Viable_Function; 3568 3569 case OR_Ambiguous: 3570 return OR_Ambiguous; 3571 } 3572 3573 llvm_unreachable("Invalid OverloadResult!"); 3574 } 3575 3576 bool 3577 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3578 ImplicitConversionSequence ICS; 3579 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3580 OverloadCandidateSet::CSK_Normal); 3581 OverloadingResult OvResult = 3582 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3583 CandidateSet, false, false); 3584 3585 if (!(OvResult == OR_Ambiguous || 3586 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3587 return false; 3588 3589 auto Cands = CandidateSet.CompleteCandidates( 3590 *this, 3591 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3592 From); 3593 if (OvResult == OR_Ambiguous) 3594 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3595 << From->getType() << ToType << From->getSourceRange(); 3596 else { // OR_No_Viable_Function && !CandidateSet.empty() 3597 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3598 diag::err_typecheck_nonviable_condition_incomplete, 3599 From->getType(), From->getSourceRange())) 3600 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3601 << false << From->getType() << From->getSourceRange() << ToType; 3602 } 3603 3604 CandidateSet.NoteCandidates( 3605 *this, From, Cands); 3606 return true; 3607 } 3608 3609 /// Compare the user-defined conversion functions or constructors 3610 /// of two user-defined conversion sequences to determine whether any ordering 3611 /// is possible. 3612 static ImplicitConversionSequence::CompareKind 3613 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3614 FunctionDecl *Function2) { 3615 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3616 return ImplicitConversionSequence::Indistinguishable; 3617 3618 // Objective-C++: 3619 // If both conversion functions are implicitly-declared conversions from 3620 // a lambda closure type to a function pointer and a block pointer, 3621 // respectively, always prefer the conversion to a function pointer, 3622 // because the function pointer is more lightweight and is more likely 3623 // to keep code working. 3624 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3625 if (!Conv1) 3626 return ImplicitConversionSequence::Indistinguishable; 3627 3628 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3629 if (!Conv2) 3630 return ImplicitConversionSequence::Indistinguishable; 3631 3632 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3633 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3634 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3635 if (Block1 != Block2) 3636 return Block1 ? ImplicitConversionSequence::Worse 3637 : ImplicitConversionSequence::Better; 3638 } 3639 3640 return ImplicitConversionSequence::Indistinguishable; 3641 } 3642 3643 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3644 const ImplicitConversionSequence &ICS) { 3645 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3646 (ICS.isUserDefined() && 3647 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3648 } 3649 3650 /// CompareImplicitConversionSequences - Compare two implicit 3651 /// conversion sequences to determine whether one is better than the 3652 /// other or if they are indistinguishable (C++ 13.3.3.2). 3653 static ImplicitConversionSequence::CompareKind 3654 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3655 const ImplicitConversionSequence& ICS1, 3656 const ImplicitConversionSequence& ICS2) 3657 { 3658 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3659 // conversion sequences (as defined in 13.3.3.1) 3660 // -- a standard conversion sequence (13.3.3.1.1) is a better 3661 // conversion sequence than a user-defined conversion sequence or 3662 // an ellipsis conversion sequence, and 3663 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3664 // conversion sequence than an ellipsis conversion sequence 3665 // (13.3.3.1.3). 3666 // 3667 // C++0x [over.best.ics]p10: 3668 // For the purpose of ranking implicit conversion sequences as 3669 // described in 13.3.3.2, the ambiguous conversion sequence is 3670 // treated as a user-defined sequence that is indistinguishable 3671 // from any other user-defined conversion sequence. 3672 3673 // String literal to 'char *' conversion has been deprecated in C++03. It has 3674 // been removed from C++11. We still accept this conversion, if it happens at 3675 // the best viable function. Otherwise, this conversion is considered worse 3676 // than ellipsis conversion. Consider this as an extension; this is not in the 3677 // standard. For example: 3678 // 3679 // int &f(...); // #1 3680 // void f(char*); // #2 3681 // void g() { int &r = f("foo"); } 3682 // 3683 // In C++03, we pick #2 as the best viable function. 3684 // In C++11, we pick #1 as the best viable function, because ellipsis 3685 // conversion is better than string-literal to char* conversion (since there 3686 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3687 // convert arguments, #2 would be the best viable function in C++11. 3688 // If the best viable function has this conversion, a warning will be issued 3689 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3690 3691 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3692 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3693 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3694 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3695 ? ImplicitConversionSequence::Worse 3696 : ImplicitConversionSequence::Better; 3697 3698 if (ICS1.getKindRank() < ICS2.getKindRank()) 3699 return ImplicitConversionSequence::Better; 3700 if (ICS2.getKindRank() < ICS1.getKindRank()) 3701 return ImplicitConversionSequence::Worse; 3702 3703 // The following checks require both conversion sequences to be of 3704 // the same kind. 3705 if (ICS1.getKind() != ICS2.getKind()) 3706 return ImplicitConversionSequence::Indistinguishable; 3707 3708 ImplicitConversionSequence::CompareKind Result = 3709 ImplicitConversionSequence::Indistinguishable; 3710 3711 // Two implicit conversion sequences of the same form are 3712 // indistinguishable conversion sequences unless one of the 3713 // following rules apply: (C++ 13.3.3.2p3): 3714 3715 // List-initialization sequence L1 is a better conversion sequence than 3716 // list-initialization sequence L2 if: 3717 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3718 // if not that, 3719 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3720 // and N1 is smaller than N2., 3721 // even if one of the other rules in this paragraph would otherwise apply. 3722 if (!ICS1.isBad()) { 3723 if (ICS1.isStdInitializerListElement() && 3724 !ICS2.isStdInitializerListElement()) 3725 return ImplicitConversionSequence::Better; 3726 if (!ICS1.isStdInitializerListElement() && 3727 ICS2.isStdInitializerListElement()) 3728 return ImplicitConversionSequence::Worse; 3729 } 3730 3731 if (ICS1.isStandard()) 3732 // Standard conversion sequence S1 is a better conversion sequence than 3733 // standard conversion sequence S2 if [...] 3734 Result = CompareStandardConversionSequences(S, Loc, 3735 ICS1.Standard, ICS2.Standard); 3736 else if (ICS1.isUserDefined()) { 3737 // User-defined conversion sequence U1 is a better conversion 3738 // sequence than another user-defined conversion sequence U2 if 3739 // they contain the same user-defined conversion function or 3740 // constructor and if the second standard conversion sequence of 3741 // U1 is better than the second standard conversion sequence of 3742 // U2 (C++ 13.3.3.2p3). 3743 if (ICS1.UserDefined.ConversionFunction == 3744 ICS2.UserDefined.ConversionFunction) 3745 Result = CompareStandardConversionSequences(S, Loc, 3746 ICS1.UserDefined.After, 3747 ICS2.UserDefined.After); 3748 else 3749 Result = compareConversionFunctions(S, 3750 ICS1.UserDefined.ConversionFunction, 3751 ICS2.UserDefined.ConversionFunction); 3752 } 3753 3754 return Result; 3755 } 3756 3757 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3758 // determine if one is a proper subset of the other. 3759 static ImplicitConversionSequence::CompareKind 3760 compareStandardConversionSubsets(ASTContext &Context, 3761 const StandardConversionSequence& SCS1, 3762 const StandardConversionSequence& SCS2) { 3763 ImplicitConversionSequence::CompareKind Result 3764 = ImplicitConversionSequence::Indistinguishable; 3765 3766 // the identity conversion sequence is considered to be a subsequence of 3767 // any non-identity conversion sequence 3768 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3769 return ImplicitConversionSequence::Better; 3770 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3771 return ImplicitConversionSequence::Worse; 3772 3773 if (SCS1.Second != SCS2.Second) { 3774 if (SCS1.Second == ICK_Identity) 3775 Result = ImplicitConversionSequence::Better; 3776 else if (SCS2.Second == ICK_Identity) 3777 Result = ImplicitConversionSequence::Worse; 3778 else 3779 return ImplicitConversionSequence::Indistinguishable; 3780 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3781 return ImplicitConversionSequence::Indistinguishable; 3782 3783 if (SCS1.Third == SCS2.Third) { 3784 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3785 : ImplicitConversionSequence::Indistinguishable; 3786 } 3787 3788 if (SCS1.Third == ICK_Identity) 3789 return Result == ImplicitConversionSequence::Worse 3790 ? ImplicitConversionSequence::Indistinguishable 3791 : ImplicitConversionSequence::Better; 3792 3793 if (SCS2.Third == ICK_Identity) 3794 return Result == ImplicitConversionSequence::Better 3795 ? ImplicitConversionSequence::Indistinguishable 3796 : ImplicitConversionSequence::Worse; 3797 3798 return ImplicitConversionSequence::Indistinguishable; 3799 } 3800 3801 /// Determine whether one of the given reference bindings is better 3802 /// than the other based on what kind of bindings they are. 3803 static bool 3804 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3805 const StandardConversionSequence &SCS2) { 3806 // C++0x [over.ics.rank]p3b4: 3807 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3808 // implicit object parameter of a non-static member function declared 3809 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3810 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3811 // lvalue reference to a function lvalue and S2 binds an rvalue 3812 // reference*. 3813 // 3814 // FIXME: Rvalue references. We're going rogue with the above edits, 3815 // because the semantics in the current C++0x working paper (N3225 at the 3816 // time of this writing) break the standard definition of std::forward 3817 // and std::reference_wrapper when dealing with references to functions. 3818 // Proposed wording changes submitted to CWG for consideration. 3819 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3820 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3821 return false; 3822 3823 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3824 SCS2.IsLvalueReference) || 3825 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3826 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3827 } 3828 3829 enum class FixedEnumPromotion { 3830 None, 3831 ToUnderlyingType, 3832 ToPromotedUnderlyingType 3833 }; 3834 3835 /// Returns kind of fixed enum promotion the \a SCS uses. 3836 static FixedEnumPromotion 3837 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3838 3839 if (SCS.Second != ICK_Integral_Promotion) 3840 return FixedEnumPromotion::None; 3841 3842 QualType FromType = SCS.getFromType(); 3843 if (!FromType->isEnumeralType()) 3844 return FixedEnumPromotion::None; 3845 3846 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3847 if (!Enum->isFixed()) 3848 return FixedEnumPromotion::None; 3849 3850 QualType UnderlyingType = Enum->getIntegerType(); 3851 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3852 return FixedEnumPromotion::ToUnderlyingType; 3853 3854 return FixedEnumPromotion::ToPromotedUnderlyingType; 3855 } 3856 3857 /// CompareStandardConversionSequences - Compare two standard 3858 /// conversion sequences to determine whether one is better than the 3859 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3860 static ImplicitConversionSequence::CompareKind 3861 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3862 const StandardConversionSequence& SCS1, 3863 const StandardConversionSequence& SCS2) 3864 { 3865 // Standard conversion sequence S1 is a better conversion sequence 3866 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3867 3868 // -- S1 is a proper subsequence of S2 (comparing the conversion 3869 // sequences in the canonical form defined by 13.3.3.1.1, 3870 // excluding any Lvalue Transformation; the identity conversion 3871 // sequence is considered to be a subsequence of any 3872 // non-identity conversion sequence) or, if not that, 3873 if (ImplicitConversionSequence::CompareKind CK 3874 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3875 return CK; 3876 3877 // -- the rank of S1 is better than the rank of S2 (by the rules 3878 // defined below), or, if not that, 3879 ImplicitConversionRank Rank1 = SCS1.getRank(); 3880 ImplicitConversionRank Rank2 = SCS2.getRank(); 3881 if (Rank1 < Rank2) 3882 return ImplicitConversionSequence::Better; 3883 else if (Rank2 < Rank1) 3884 return ImplicitConversionSequence::Worse; 3885 3886 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3887 // are indistinguishable unless one of the following rules 3888 // applies: 3889 3890 // A conversion that is not a conversion of a pointer, or 3891 // pointer to member, to bool is better than another conversion 3892 // that is such a conversion. 3893 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3894 return SCS2.isPointerConversionToBool() 3895 ? ImplicitConversionSequence::Better 3896 : ImplicitConversionSequence::Worse; 3897 3898 // C++14 [over.ics.rank]p4b2: 3899 // This is retroactively applied to C++11 by CWG 1601. 3900 // 3901 // A conversion that promotes an enumeration whose underlying type is fixed 3902 // to its underlying type is better than one that promotes to the promoted 3903 // underlying type, if the two are different. 3904 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3905 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3906 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3907 FEP1 != FEP2) 3908 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3909 ? ImplicitConversionSequence::Better 3910 : ImplicitConversionSequence::Worse; 3911 3912 // C++ [over.ics.rank]p4b2: 3913 // 3914 // If class B is derived directly or indirectly from class A, 3915 // conversion of B* to A* is better than conversion of B* to 3916 // void*, and conversion of A* to void* is better than conversion 3917 // of B* to void*. 3918 bool SCS1ConvertsToVoid 3919 = SCS1.isPointerConversionToVoidPointer(S.Context); 3920 bool SCS2ConvertsToVoid 3921 = SCS2.isPointerConversionToVoidPointer(S.Context); 3922 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3923 // Exactly one of the conversion sequences is a conversion to 3924 // a void pointer; it's the worse conversion. 3925 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3926 : ImplicitConversionSequence::Worse; 3927 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3928 // Neither conversion sequence converts to a void pointer; compare 3929 // their derived-to-base conversions. 3930 if (ImplicitConversionSequence::CompareKind DerivedCK 3931 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3932 return DerivedCK; 3933 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3934 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3935 // Both conversion sequences are conversions to void 3936 // pointers. Compare the source types to determine if there's an 3937 // inheritance relationship in their sources. 3938 QualType FromType1 = SCS1.getFromType(); 3939 QualType FromType2 = SCS2.getFromType(); 3940 3941 // Adjust the types we're converting from via the array-to-pointer 3942 // conversion, if we need to. 3943 if (SCS1.First == ICK_Array_To_Pointer) 3944 FromType1 = S.Context.getArrayDecayedType(FromType1); 3945 if (SCS2.First == ICK_Array_To_Pointer) 3946 FromType2 = S.Context.getArrayDecayedType(FromType2); 3947 3948 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3949 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3950 3951 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3952 return ImplicitConversionSequence::Better; 3953 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3954 return ImplicitConversionSequence::Worse; 3955 3956 // Objective-C++: If one interface is more specific than the 3957 // other, it is the better one. 3958 const ObjCObjectPointerType* FromObjCPtr1 3959 = FromType1->getAs<ObjCObjectPointerType>(); 3960 const ObjCObjectPointerType* FromObjCPtr2 3961 = FromType2->getAs<ObjCObjectPointerType>(); 3962 if (FromObjCPtr1 && FromObjCPtr2) { 3963 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3964 FromObjCPtr2); 3965 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3966 FromObjCPtr1); 3967 if (AssignLeft != AssignRight) { 3968 return AssignLeft? ImplicitConversionSequence::Better 3969 : ImplicitConversionSequence::Worse; 3970 } 3971 } 3972 } 3973 3974 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3975 // bullet 3). 3976 if (ImplicitConversionSequence::CompareKind QualCK 3977 = CompareQualificationConversions(S, SCS1, SCS2)) 3978 return QualCK; 3979 3980 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3981 // Check for a better reference binding based on the kind of bindings. 3982 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3983 return ImplicitConversionSequence::Better; 3984 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3985 return ImplicitConversionSequence::Worse; 3986 3987 // C++ [over.ics.rank]p3b4: 3988 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3989 // which the references refer are the same type except for 3990 // top-level cv-qualifiers, and the type to which the reference 3991 // initialized by S2 refers is more cv-qualified than the type 3992 // to which the reference initialized by S1 refers. 3993 QualType T1 = SCS1.getToType(2); 3994 QualType T2 = SCS2.getToType(2); 3995 T1 = S.Context.getCanonicalType(T1); 3996 T2 = S.Context.getCanonicalType(T2); 3997 Qualifiers T1Quals, T2Quals; 3998 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3999 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4000 if (UnqualT1 == UnqualT2) { 4001 // Objective-C++ ARC: If the references refer to objects with different 4002 // lifetimes, prefer bindings that don't change lifetime. 4003 if (SCS1.ObjCLifetimeConversionBinding != 4004 SCS2.ObjCLifetimeConversionBinding) { 4005 return SCS1.ObjCLifetimeConversionBinding 4006 ? ImplicitConversionSequence::Worse 4007 : ImplicitConversionSequence::Better; 4008 } 4009 4010 // If the type is an array type, promote the element qualifiers to the 4011 // type for comparison. 4012 if (isa<ArrayType>(T1) && T1Quals) 4013 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4014 if (isa<ArrayType>(T2) && T2Quals) 4015 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4016 if (T2.isMoreQualifiedThan(T1)) 4017 return ImplicitConversionSequence::Better; 4018 else if (T1.isMoreQualifiedThan(T2)) 4019 return ImplicitConversionSequence::Worse; 4020 } 4021 } 4022 4023 // In Microsoft mode, prefer an integral conversion to a 4024 // floating-to-integral conversion if the integral conversion 4025 // is between types of the same size. 4026 // For example: 4027 // void f(float); 4028 // void f(int); 4029 // int main { 4030 // long a; 4031 // f(a); 4032 // } 4033 // Here, MSVC will call f(int) instead of generating a compile error 4034 // as clang will do in standard mode. 4035 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4036 SCS2.Second == ICK_Floating_Integral && 4037 S.Context.getTypeSize(SCS1.getFromType()) == 4038 S.Context.getTypeSize(SCS1.getToType(2))) 4039 return ImplicitConversionSequence::Better; 4040 4041 // Prefer a compatible vector conversion over a lax vector conversion 4042 // For example: 4043 // 4044 // typedef float __v4sf __attribute__((__vector_size__(16))); 4045 // void f(vector float); 4046 // void f(vector signed int); 4047 // int main() { 4048 // __v4sf a; 4049 // f(a); 4050 // } 4051 // Here, we'd like to choose f(vector float) and not 4052 // report an ambiguous call error 4053 if (SCS1.Second == ICK_Vector_Conversion && 4054 SCS2.Second == ICK_Vector_Conversion) { 4055 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4056 SCS1.getFromType(), SCS1.getToType(2)); 4057 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4058 SCS2.getFromType(), SCS2.getToType(2)); 4059 4060 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4061 return SCS1IsCompatibleVectorConversion 4062 ? ImplicitConversionSequence::Better 4063 : ImplicitConversionSequence::Worse; 4064 } 4065 4066 return ImplicitConversionSequence::Indistinguishable; 4067 } 4068 4069 /// CompareQualificationConversions - Compares two standard conversion 4070 /// sequences to determine whether they can be ranked based on their 4071 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4072 static ImplicitConversionSequence::CompareKind 4073 CompareQualificationConversions(Sema &S, 4074 const StandardConversionSequence& SCS1, 4075 const StandardConversionSequence& SCS2) { 4076 // C++ 13.3.3.2p3: 4077 // -- S1 and S2 differ only in their qualification conversion and 4078 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4079 // cv-qualification signature of type T1 is a proper subset of 4080 // the cv-qualification signature of type T2, and S1 is not the 4081 // deprecated string literal array-to-pointer conversion (4.2). 4082 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4083 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4084 return ImplicitConversionSequence::Indistinguishable; 4085 4086 // FIXME: the example in the standard doesn't use a qualification 4087 // conversion (!) 4088 QualType T1 = SCS1.getToType(2); 4089 QualType T2 = SCS2.getToType(2); 4090 T1 = S.Context.getCanonicalType(T1); 4091 T2 = S.Context.getCanonicalType(T2); 4092 Qualifiers T1Quals, T2Quals; 4093 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4094 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4095 4096 // If the types are the same, we won't learn anything by unwrapped 4097 // them. 4098 if (UnqualT1 == UnqualT2) 4099 return ImplicitConversionSequence::Indistinguishable; 4100 4101 // If the type is an array type, promote the element qualifiers to the type 4102 // for comparison. 4103 if (isa<ArrayType>(T1) && T1Quals) 4104 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4105 if (isa<ArrayType>(T2) && T2Quals) 4106 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4107 4108 ImplicitConversionSequence::CompareKind Result 4109 = ImplicitConversionSequence::Indistinguishable; 4110 4111 // Objective-C++ ARC: 4112 // Prefer qualification conversions not involving a change in lifetime 4113 // to qualification conversions that do not change lifetime. 4114 if (SCS1.QualificationIncludesObjCLifetime != 4115 SCS2.QualificationIncludesObjCLifetime) { 4116 Result = SCS1.QualificationIncludesObjCLifetime 4117 ? ImplicitConversionSequence::Worse 4118 : ImplicitConversionSequence::Better; 4119 } 4120 4121 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4122 // Within each iteration of the loop, we check the qualifiers to 4123 // determine if this still looks like a qualification 4124 // conversion. Then, if all is well, we unwrap one more level of 4125 // pointers or pointers-to-members and do it all again 4126 // until there are no more pointers or pointers-to-members left 4127 // to unwrap. This essentially mimics what 4128 // IsQualificationConversion does, but here we're checking for a 4129 // strict subset of qualifiers. 4130 if (T1.getQualifiers().withoutObjCLifetime() == 4131 T2.getQualifiers().withoutObjCLifetime()) 4132 // The qualifiers are the same, so this doesn't tell us anything 4133 // about how the sequences rank. 4134 // ObjC ownership quals are omitted above as they interfere with 4135 // the ARC overload rule. 4136 ; 4137 else if (T2.isMoreQualifiedThan(T1)) { 4138 // T1 has fewer qualifiers, so it could be the better sequence. 4139 if (Result == ImplicitConversionSequence::Worse) 4140 // Neither has qualifiers that are a subset of the other's 4141 // qualifiers. 4142 return ImplicitConversionSequence::Indistinguishable; 4143 4144 Result = ImplicitConversionSequence::Better; 4145 } else if (T1.isMoreQualifiedThan(T2)) { 4146 // T2 has fewer qualifiers, so it could be the better sequence. 4147 if (Result == ImplicitConversionSequence::Better) 4148 // Neither has qualifiers that are a subset of the other's 4149 // qualifiers. 4150 return ImplicitConversionSequence::Indistinguishable; 4151 4152 Result = ImplicitConversionSequence::Worse; 4153 } else { 4154 // Qualifiers are disjoint. 4155 return ImplicitConversionSequence::Indistinguishable; 4156 } 4157 4158 // If the types after this point are equivalent, we're done. 4159 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4160 break; 4161 } 4162 4163 // Check that the winning standard conversion sequence isn't using 4164 // the deprecated string literal array to pointer conversion. 4165 switch (Result) { 4166 case ImplicitConversionSequence::Better: 4167 if (SCS1.DeprecatedStringLiteralToCharPtr) 4168 Result = ImplicitConversionSequence::Indistinguishable; 4169 break; 4170 4171 case ImplicitConversionSequence::Indistinguishable: 4172 break; 4173 4174 case ImplicitConversionSequence::Worse: 4175 if (SCS2.DeprecatedStringLiteralToCharPtr) 4176 Result = ImplicitConversionSequence::Indistinguishable; 4177 break; 4178 } 4179 4180 return Result; 4181 } 4182 4183 /// CompareDerivedToBaseConversions - Compares two standard conversion 4184 /// sequences to determine whether they can be ranked based on their 4185 /// various kinds of derived-to-base conversions (C++ 4186 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4187 /// conversions between Objective-C interface types. 4188 static ImplicitConversionSequence::CompareKind 4189 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4190 const StandardConversionSequence& SCS1, 4191 const StandardConversionSequence& SCS2) { 4192 QualType FromType1 = SCS1.getFromType(); 4193 QualType ToType1 = SCS1.getToType(1); 4194 QualType FromType2 = SCS2.getFromType(); 4195 QualType ToType2 = SCS2.getToType(1); 4196 4197 // Adjust the types we're converting from via the array-to-pointer 4198 // conversion, if we need to. 4199 if (SCS1.First == ICK_Array_To_Pointer) 4200 FromType1 = S.Context.getArrayDecayedType(FromType1); 4201 if (SCS2.First == ICK_Array_To_Pointer) 4202 FromType2 = S.Context.getArrayDecayedType(FromType2); 4203 4204 // Canonicalize all of the types. 4205 FromType1 = S.Context.getCanonicalType(FromType1); 4206 ToType1 = S.Context.getCanonicalType(ToType1); 4207 FromType2 = S.Context.getCanonicalType(FromType2); 4208 ToType2 = S.Context.getCanonicalType(ToType2); 4209 4210 // C++ [over.ics.rank]p4b3: 4211 // 4212 // If class B is derived directly or indirectly from class A and 4213 // class C is derived directly or indirectly from B, 4214 // 4215 // Compare based on pointer conversions. 4216 if (SCS1.Second == ICK_Pointer_Conversion && 4217 SCS2.Second == ICK_Pointer_Conversion && 4218 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4219 FromType1->isPointerType() && FromType2->isPointerType() && 4220 ToType1->isPointerType() && ToType2->isPointerType()) { 4221 QualType FromPointee1 = 4222 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4223 QualType ToPointee1 = 4224 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4225 QualType FromPointee2 = 4226 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4227 QualType ToPointee2 = 4228 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4229 4230 // -- conversion of C* to B* is better than conversion of C* to A*, 4231 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4232 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4233 return ImplicitConversionSequence::Better; 4234 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4235 return ImplicitConversionSequence::Worse; 4236 } 4237 4238 // -- conversion of B* to A* is better than conversion of C* to A*, 4239 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4240 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4241 return ImplicitConversionSequence::Better; 4242 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4243 return ImplicitConversionSequence::Worse; 4244 } 4245 } else if (SCS1.Second == ICK_Pointer_Conversion && 4246 SCS2.Second == ICK_Pointer_Conversion) { 4247 const ObjCObjectPointerType *FromPtr1 4248 = FromType1->getAs<ObjCObjectPointerType>(); 4249 const ObjCObjectPointerType *FromPtr2 4250 = FromType2->getAs<ObjCObjectPointerType>(); 4251 const ObjCObjectPointerType *ToPtr1 4252 = ToType1->getAs<ObjCObjectPointerType>(); 4253 const ObjCObjectPointerType *ToPtr2 4254 = ToType2->getAs<ObjCObjectPointerType>(); 4255 4256 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4257 // Apply the same conversion ranking rules for Objective-C pointer types 4258 // that we do for C++ pointers to class types. However, we employ the 4259 // Objective-C pseudo-subtyping relationship used for assignment of 4260 // Objective-C pointer types. 4261 bool FromAssignLeft 4262 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4263 bool FromAssignRight 4264 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4265 bool ToAssignLeft 4266 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4267 bool ToAssignRight 4268 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4269 4270 // A conversion to an a non-id object pointer type or qualified 'id' 4271 // type is better than a conversion to 'id'. 4272 if (ToPtr1->isObjCIdType() && 4273 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4274 return ImplicitConversionSequence::Worse; 4275 if (ToPtr2->isObjCIdType() && 4276 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4277 return ImplicitConversionSequence::Better; 4278 4279 // A conversion to a non-id object pointer type is better than a 4280 // conversion to a qualified 'id' type 4281 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4282 return ImplicitConversionSequence::Worse; 4283 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4284 return ImplicitConversionSequence::Better; 4285 4286 // A conversion to an a non-Class object pointer type or qualified 'Class' 4287 // type is better than a conversion to 'Class'. 4288 if (ToPtr1->isObjCClassType() && 4289 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4290 return ImplicitConversionSequence::Worse; 4291 if (ToPtr2->isObjCClassType() && 4292 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4293 return ImplicitConversionSequence::Better; 4294 4295 // A conversion to a non-Class object pointer type is better than a 4296 // conversion to a qualified 'Class' type. 4297 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4298 return ImplicitConversionSequence::Worse; 4299 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4300 return ImplicitConversionSequence::Better; 4301 4302 // -- "conversion of C* to B* is better than conversion of C* to A*," 4303 if (S.Context.hasSameType(FromType1, FromType2) && 4304 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4305 (ToAssignLeft != ToAssignRight)) { 4306 if (FromPtr1->isSpecialized()) { 4307 // "conversion of B<A> * to B * is better than conversion of B * to 4308 // C *. 4309 bool IsFirstSame = 4310 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4311 bool IsSecondSame = 4312 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4313 if (IsFirstSame) { 4314 if (!IsSecondSame) 4315 return ImplicitConversionSequence::Better; 4316 } else if (IsSecondSame) 4317 return ImplicitConversionSequence::Worse; 4318 } 4319 return ToAssignLeft? ImplicitConversionSequence::Worse 4320 : ImplicitConversionSequence::Better; 4321 } 4322 4323 // -- "conversion of B* to A* is better than conversion of C* to A*," 4324 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4325 (FromAssignLeft != FromAssignRight)) 4326 return FromAssignLeft? ImplicitConversionSequence::Better 4327 : ImplicitConversionSequence::Worse; 4328 } 4329 } 4330 4331 // Ranking of member-pointer types. 4332 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4333 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4334 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4335 const MemberPointerType * FromMemPointer1 = 4336 FromType1->getAs<MemberPointerType>(); 4337 const MemberPointerType * ToMemPointer1 = 4338 ToType1->getAs<MemberPointerType>(); 4339 const MemberPointerType * FromMemPointer2 = 4340 FromType2->getAs<MemberPointerType>(); 4341 const MemberPointerType * ToMemPointer2 = 4342 ToType2->getAs<MemberPointerType>(); 4343 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4344 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4345 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4346 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4347 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4348 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4349 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4350 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4351 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4352 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4353 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4354 return ImplicitConversionSequence::Worse; 4355 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4356 return ImplicitConversionSequence::Better; 4357 } 4358 // conversion of B::* to C::* is better than conversion of A::* to C::* 4359 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4360 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4361 return ImplicitConversionSequence::Better; 4362 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4363 return ImplicitConversionSequence::Worse; 4364 } 4365 } 4366 4367 if (SCS1.Second == ICK_Derived_To_Base) { 4368 // -- conversion of C to B is better than conversion of C to A, 4369 // -- binding of an expression of type C to a reference of type 4370 // B& is better than binding an expression of type C to a 4371 // reference of type A&, 4372 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4373 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4374 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4375 return ImplicitConversionSequence::Better; 4376 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4377 return ImplicitConversionSequence::Worse; 4378 } 4379 4380 // -- conversion of B to A is better than conversion of C to A. 4381 // -- binding of an expression of type B to a reference of type 4382 // A& is better than binding an expression of type C to a 4383 // reference of type A&, 4384 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4385 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4386 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4387 return ImplicitConversionSequence::Better; 4388 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4389 return ImplicitConversionSequence::Worse; 4390 } 4391 } 4392 4393 return ImplicitConversionSequence::Indistinguishable; 4394 } 4395 4396 /// Determine whether the given type is valid, e.g., it is not an invalid 4397 /// C++ class. 4398 static bool isTypeValid(QualType T) { 4399 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4400 return !Record->isInvalidDecl(); 4401 4402 return true; 4403 } 4404 4405 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4406 /// determine whether they are reference-related, 4407 /// reference-compatible, reference-compatible with added 4408 /// qualification, or incompatible, for use in C++ initialization by 4409 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4410 /// type, and the first type (T1) is the pointee type of the reference 4411 /// type being initialized. 4412 Sema::ReferenceCompareResult 4413 Sema::CompareReferenceRelationship(SourceLocation Loc, 4414 QualType OrigT1, QualType OrigT2, 4415 ReferenceConversions *ConvOut) { 4416 assert(!OrigT1->isReferenceType() && 4417 "T1 must be the pointee type of the reference type"); 4418 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4419 4420 QualType T1 = Context.getCanonicalType(OrigT1); 4421 QualType T2 = Context.getCanonicalType(OrigT2); 4422 Qualifiers T1Quals, T2Quals; 4423 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4424 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4425 4426 ReferenceConversions ConvTmp; 4427 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4428 Conv = ReferenceConversions(); 4429 4430 // C++ [dcl.init.ref]p4: 4431 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4432 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4433 // T1 is a base class of T2. 4434 QualType ConvertedT2; 4435 if (UnqualT1 == UnqualT2) { 4436 // Nothing to do. 4437 } else if (isCompleteType(Loc, OrigT2) && 4438 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4439 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4440 Conv |= ReferenceConversions::DerivedToBase; 4441 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4442 UnqualT2->isObjCObjectOrInterfaceType() && 4443 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4444 Conv |= ReferenceConversions::ObjC; 4445 else if (UnqualT2->isFunctionType() && 4446 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4447 // C++1z [dcl.init.ref]p4: 4448 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4449 // function" and T1 is "function" 4450 // 4451 // We extend this to also apply to 'noreturn', so allow any function 4452 // conversion between function types. 4453 Conv |= ReferenceConversions::Function; 4454 return Ref_Compatible; 4455 } else 4456 return Ref_Incompatible; 4457 4458 // At this point, we know that T1 and T2 are reference-related (at 4459 // least). 4460 4461 // If the type is an array type, promote the element qualifiers to the type 4462 // for comparison. 4463 if (isa<ArrayType>(T1) && T1Quals) 4464 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4465 if (isa<ArrayType>(T2) && T2Quals) 4466 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4467 4468 // C++ [dcl.init.ref]p4: 4469 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4470 // reference-related to T2 and cv1 is the same cv-qualification 4471 // as, or greater cv-qualification than, cv2. For purposes of 4472 // overload resolution, cases for which cv1 is greater 4473 // cv-qualification than cv2 are identified as 4474 // reference-compatible with added qualification (see 13.3.3.2). 4475 // 4476 // Note that we also require equivalence of Objective-C GC and address-space 4477 // qualifiers when performing these computations, so that e.g., an int in 4478 // address space 1 is not reference-compatible with an int in address 4479 // space 2. 4480 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4481 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4482 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4483 Conv |= ReferenceConversions::ObjCLifetime; 4484 4485 T1Quals.removeObjCLifetime(); 4486 T2Quals.removeObjCLifetime(); 4487 } 4488 4489 // MS compiler ignores __unaligned qualifier for references; do the same. 4490 T1Quals.removeUnaligned(); 4491 T2Quals.removeUnaligned(); 4492 4493 if (T1Quals != T2Quals) 4494 Conv |= ReferenceConversions::Qualification; 4495 4496 if (T1Quals.compatiblyIncludes(T2Quals)) 4497 return Ref_Compatible; 4498 else 4499 return Ref_Related; 4500 } 4501 4502 /// Look for a user-defined conversion to a value reference-compatible 4503 /// with DeclType. Return true if something definite is found. 4504 static bool 4505 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4506 QualType DeclType, SourceLocation DeclLoc, 4507 Expr *Init, QualType T2, bool AllowRvalues, 4508 bool AllowExplicit) { 4509 assert(T2->isRecordType() && "Can only find conversions of record types."); 4510 CXXRecordDecl *T2RecordDecl 4511 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4512 4513 OverloadCandidateSet CandidateSet( 4514 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4515 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4516 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4517 NamedDecl *D = *I; 4518 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4519 if (isa<UsingShadowDecl>(D)) 4520 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4521 4522 FunctionTemplateDecl *ConvTemplate 4523 = dyn_cast<FunctionTemplateDecl>(D); 4524 CXXConversionDecl *Conv; 4525 if (ConvTemplate) 4526 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4527 else 4528 Conv = cast<CXXConversionDecl>(D); 4529 4530 // If this is an explicit conversion, and we're not allowed to consider 4531 // explicit conversions, skip it. 4532 if (!AllowExplicit && Conv->isExplicit()) 4533 continue; 4534 4535 if (AllowRvalues) { 4536 // If we are initializing an rvalue reference, don't permit conversion 4537 // functions that return lvalues. 4538 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4539 const ReferenceType *RefType 4540 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4541 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4542 continue; 4543 } 4544 4545 if (!ConvTemplate && 4546 S.CompareReferenceRelationship( 4547 DeclLoc, 4548 Conv->getConversionType() 4549 .getNonReferenceType() 4550 .getUnqualifiedType(), 4551 DeclType.getNonReferenceType().getUnqualifiedType()) == 4552 Sema::Ref_Incompatible) 4553 continue; 4554 } else { 4555 // If the conversion function doesn't return a reference type, 4556 // it can't be considered for this conversion. An rvalue reference 4557 // is only acceptable if its referencee is a function type. 4558 4559 const ReferenceType *RefType = 4560 Conv->getConversionType()->getAs<ReferenceType>(); 4561 if (!RefType || 4562 (!RefType->isLValueReferenceType() && 4563 !RefType->getPointeeType()->isFunctionType())) 4564 continue; 4565 } 4566 4567 if (ConvTemplate) 4568 S.AddTemplateConversionCandidate( 4569 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4570 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4571 else 4572 S.AddConversionCandidate( 4573 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4574 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4575 } 4576 4577 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4578 4579 OverloadCandidateSet::iterator Best; 4580 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4581 case OR_Success: 4582 // C++ [over.ics.ref]p1: 4583 // 4584 // [...] If the parameter binds directly to the result of 4585 // applying a conversion function to the argument 4586 // expression, the implicit conversion sequence is a 4587 // user-defined conversion sequence (13.3.3.1.2), with the 4588 // second standard conversion sequence either an identity 4589 // conversion or, if the conversion function returns an 4590 // entity of a type that is a derived class of the parameter 4591 // type, a derived-to-base Conversion. 4592 if (!Best->FinalConversion.DirectBinding) 4593 return false; 4594 4595 ICS.setUserDefined(); 4596 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4597 ICS.UserDefined.After = Best->FinalConversion; 4598 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4599 ICS.UserDefined.ConversionFunction = Best->Function; 4600 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4601 ICS.UserDefined.EllipsisConversion = false; 4602 assert(ICS.UserDefined.After.ReferenceBinding && 4603 ICS.UserDefined.After.DirectBinding && 4604 "Expected a direct reference binding!"); 4605 return true; 4606 4607 case OR_Ambiguous: 4608 ICS.setAmbiguous(); 4609 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4610 Cand != CandidateSet.end(); ++Cand) 4611 if (Cand->Best) 4612 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4613 return true; 4614 4615 case OR_No_Viable_Function: 4616 case OR_Deleted: 4617 // There was no suitable conversion, or we found a deleted 4618 // conversion; continue with other checks. 4619 return false; 4620 } 4621 4622 llvm_unreachable("Invalid OverloadResult!"); 4623 } 4624 4625 /// Compute an implicit conversion sequence for reference 4626 /// initialization. 4627 static ImplicitConversionSequence 4628 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4629 SourceLocation DeclLoc, 4630 bool SuppressUserConversions, 4631 bool AllowExplicit) { 4632 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4633 4634 // Most paths end in a failed conversion. 4635 ImplicitConversionSequence ICS; 4636 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4637 4638 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4639 QualType T2 = Init->getType(); 4640 4641 // If the initializer is the address of an overloaded function, try 4642 // to resolve the overloaded function. If all goes well, T2 is the 4643 // type of the resulting function. 4644 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4645 DeclAccessPair Found; 4646 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4647 false, Found)) 4648 T2 = Fn->getType(); 4649 } 4650 4651 // Compute some basic properties of the types and the initializer. 4652 bool isRValRef = DeclType->isRValueReferenceType(); 4653 Expr::Classification InitCategory = Init->Classify(S.Context); 4654 4655 Sema::ReferenceConversions RefConv; 4656 Sema::ReferenceCompareResult RefRelationship = 4657 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4658 4659 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4660 ICS.setStandard(); 4661 ICS.Standard.First = ICK_Identity; 4662 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4663 ? ICK_Derived_To_Base 4664 : (RefConv & Sema::ReferenceConversions::ObjC) 4665 ? ICK_Compatible_Conversion 4666 : ICK_Identity; 4667 ICS.Standard.Third = ICK_Identity; 4668 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4669 ICS.Standard.setToType(0, T2); 4670 ICS.Standard.setToType(1, T1); 4671 ICS.Standard.setToType(2, T1); 4672 ICS.Standard.ReferenceBinding = true; 4673 ICS.Standard.DirectBinding = BindsDirectly; 4674 ICS.Standard.IsLvalueReference = !isRValRef; 4675 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4676 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4677 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4678 ICS.Standard.ObjCLifetimeConversionBinding = 4679 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4680 ICS.Standard.CopyConstructor = nullptr; 4681 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4682 }; 4683 4684 // C++0x [dcl.init.ref]p5: 4685 // A reference to type "cv1 T1" is initialized by an expression 4686 // of type "cv2 T2" as follows: 4687 4688 // -- If reference is an lvalue reference and the initializer expression 4689 if (!isRValRef) { 4690 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4691 // reference-compatible with "cv2 T2," or 4692 // 4693 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4694 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4695 // C++ [over.ics.ref]p1: 4696 // When a parameter of reference type binds directly (8.5.3) 4697 // to an argument expression, the implicit conversion sequence 4698 // is the identity conversion, unless the argument expression 4699 // has a type that is a derived class of the parameter type, 4700 // in which case the implicit conversion sequence is a 4701 // derived-to-base Conversion (13.3.3.1). 4702 SetAsReferenceBinding(/*BindsDirectly=*/true); 4703 4704 // Nothing more to do: the inaccessibility/ambiguity check for 4705 // derived-to-base conversions is suppressed when we're 4706 // computing the implicit conversion sequence (C++ 4707 // [over.best.ics]p2). 4708 return ICS; 4709 } 4710 4711 // -- has a class type (i.e., T2 is a class type), where T1 is 4712 // not reference-related to T2, and can be implicitly 4713 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4714 // is reference-compatible with "cv3 T3" 92) (this 4715 // conversion is selected by enumerating the applicable 4716 // conversion functions (13.3.1.6) and choosing the best 4717 // one through overload resolution (13.3)), 4718 if (!SuppressUserConversions && T2->isRecordType() && 4719 S.isCompleteType(DeclLoc, T2) && 4720 RefRelationship == Sema::Ref_Incompatible) { 4721 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4722 Init, T2, /*AllowRvalues=*/false, 4723 AllowExplicit)) 4724 return ICS; 4725 } 4726 } 4727 4728 // -- Otherwise, the reference shall be an lvalue reference to a 4729 // non-volatile const type (i.e., cv1 shall be const), or the reference 4730 // shall be an rvalue reference. 4731 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4732 return ICS; 4733 4734 // -- If the initializer expression 4735 // 4736 // -- is an xvalue, class prvalue, array prvalue or function 4737 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4738 if (RefRelationship == Sema::Ref_Compatible && 4739 (InitCategory.isXValue() || 4740 (InitCategory.isPRValue() && 4741 (T2->isRecordType() || T2->isArrayType())) || 4742 (InitCategory.isLValue() && T2->isFunctionType()))) { 4743 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4744 // binding unless we're binding to a class prvalue. 4745 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4746 // allow the use of rvalue references in C++98/03 for the benefit of 4747 // standard library implementors; therefore, we need the xvalue check here. 4748 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4749 !(InitCategory.isPRValue() || T2->isRecordType())); 4750 return ICS; 4751 } 4752 4753 // -- has a class type (i.e., T2 is a class type), where T1 is not 4754 // reference-related to T2, and can be implicitly converted to 4755 // an xvalue, class prvalue, or function lvalue of type 4756 // "cv3 T3", where "cv1 T1" is reference-compatible with 4757 // "cv3 T3", 4758 // 4759 // then the reference is bound to the value of the initializer 4760 // expression in the first case and to the result of the conversion 4761 // in the second case (or, in either case, to an appropriate base 4762 // class subobject). 4763 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4764 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4765 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4766 Init, T2, /*AllowRvalues=*/true, 4767 AllowExplicit)) { 4768 // In the second case, if the reference is an rvalue reference 4769 // and the second standard conversion sequence of the 4770 // user-defined conversion sequence includes an lvalue-to-rvalue 4771 // conversion, the program is ill-formed. 4772 if (ICS.isUserDefined() && isRValRef && 4773 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4774 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4775 4776 return ICS; 4777 } 4778 4779 // A temporary of function type cannot be created; don't even try. 4780 if (T1->isFunctionType()) 4781 return ICS; 4782 4783 // -- Otherwise, a temporary of type "cv1 T1" is created and 4784 // initialized from the initializer expression using the 4785 // rules for a non-reference copy initialization (8.5). The 4786 // reference is then bound to the temporary. If T1 is 4787 // reference-related to T2, cv1 must be the same 4788 // cv-qualification as, or greater cv-qualification than, 4789 // cv2; otherwise, the program is ill-formed. 4790 if (RefRelationship == Sema::Ref_Related) { 4791 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4792 // we would be reference-compatible or reference-compatible with 4793 // added qualification. But that wasn't the case, so the reference 4794 // initialization fails. 4795 // 4796 // Note that we only want to check address spaces and cvr-qualifiers here. 4797 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4798 Qualifiers T1Quals = T1.getQualifiers(); 4799 Qualifiers T2Quals = T2.getQualifiers(); 4800 T1Quals.removeObjCGCAttr(); 4801 T1Quals.removeObjCLifetime(); 4802 T2Quals.removeObjCGCAttr(); 4803 T2Quals.removeObjCLifetime(); 4804 // MS compiler ignores __unaligned qualifier for references; do the same. 4805 T1Quals.removeUnaligned(); 4806 T2Quals.removeUnaligned(); 4807 if (!T1Quals.compatiblyIncludes(T2Quals)) 4808 return ICS; 4809 } 4810 4811 // If at least one of the types is a class type, the types are not 4812 // related, and we aren't allowed any user conversions, the 4813 // reference binding fails. This case is important for breaking 4814 // recursion, since TryImplicitConversion below will attempt to 4815 // create a temporary through the use of a copy constructor. 4816 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4817 (T1->isRecordType() || T2->isRecordType())) 4818 return ICS; 4819 4820 // If T1 is reference-related to T2 and the reference is an rvalue 4821 // reference, the initializer expression shall not be an lvalue. 4822 if (RefRelationship >= Sema::Ref_Related && 4823 isRValRef && Init->Classify(S.Context).isLValue()) 4824 return ICS; 4825 4826 // C++ [over.ics.ref]p2: 4827 // When a parameter of reference type is not bound directly to 4828 // an argument expression, the conversion sequence is the one 4829 // required to convert the argument expression to the 4830 // underlying type of the reference according to 4831 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4832 // to copy-initializing a temporary of the underlying type with 4833 // the argument expression. Any difference in top-level 4834 // cv-qualification is subsumed by the initialization itself 4835 // and does not constitute a conversion. 4836 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4837 /*AllowExplicit=*/false, 4838 /*InOverloadResolution=*/false, 4839 /*CStyle=*/false, 4840 /*AllowObjCWritebackConversion=*/false, 4841 /*AllowObjCConversionOnExplicit=*/false); 4842 4843 // Of course, that's still a reference binding. 4844 if (ICS.isStandard()) { 4845 ICS.Standard.ReferenceBinding = true; 4846 ICS.Standard.IsLvalueReference = !isRValRef; 4847 ICS.Standard.BindsToFunctionLvalue = false; 4848 ICS.Standard.BindsToRvalue = true; 4849 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4850 ICS.Standard.ObjCLifetimeConversionBinding = false; 4851 } else if (ICS.isUserDefined()) { 4852 const ReferenceType *LValRefType = 4853 ICS.UserDefined.ConversionFunction->getReturnType() 4854 ->getAs<LValueReferenceType>(); 4855 4856 // C++ [over.ics.ref]p3: 4857 // Except for an implicit object parameter, for which see 13.3.1, a 4858 // standard conversion sequence cannot be formed if it requires [...] 4859 // binding an rvalue reference to an lvalue other than a function 4860 // lvalue. 4861 // Note that the function case is not possible here. 4862 if (DeclType->isRValueReferenceType() && LValRefType) { 4863 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4864 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4865 // reference to an rvalue! 4866 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4867 return ICS; 4868 } 4869 4870 ICS.UserDefined.After.ReferenceBinding = true; 4871 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4872 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4873 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4874 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4875 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4876 } 4877 4878 return ICS; 4879 } 4880 4881 static ImplicitConversionSequence 4882 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4883 bool SuppressUserConversions, 4884 bool InOverloadResolution, 4885 bool AllowObjCWritebackConversion, 4886 bool AllowExplicit = false); 4887 4888 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4889 /// initializer list From. 4890 static ImplicitConversionSequence 4891 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4892 bool SuppressUserConversions, 4893 bool InOverloadResolution, 4894 bool AllowObjCWritebackConversion) { 4895 // C++11 [over.ics.list]p1: 4896 // When an argument is an initializer list, it is not an expression and 4897 // special rules apply for converting it to a parameter type. 4898 4899 ImplicitConversionSequence Result; 4900 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4901 4902 // We need a complete type for what follows. Incomplete types can never be 4903 // initialized from init lists. 4904 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4905 return Result; 4906 4907 // Per DR1467: 4908 // If the parameter type is a class X and the initializer list has a single 4909 // element of type cv U, where U is X or a class derived from X, the 4910 // implicit conversion sequence is the one required to convert the element 4911 // to the parameter type. 4912 // 4913 // Otherwise, if the parameter type is a character array [... ] 4914 // and the initializer list has a single element that is an 4915 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4916 // implicit conversion sequence is the identity conversion. 4917 if (From->getNumInits() == 1) { 4918 if (ToType->isRecordType()) { 4919 QualType InitType = From->getInit(0)->getType(); 4920 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4921 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4922 return TryCopyInitialization(S, From->getInit(0), ToType, 4923 SuppressUserConversions, 4924 InOverloadResolution, 4925 AllowObjCWritebackConversion); 4926 } 4927 // FIXME: Check the other conditions here: array of character type, 4928 // initializer is a string literal. 4929 if (ToType->isArrayType()) { 4930 InitializedEntity Entity = 4931 InitializedEntity::InitializeParameter(S.Context, ToType, 4932 /*Consumed=*/false); 4933 if (S.CanPerformCopyInitialization(Entity, From)) { 4934 Result.setStandard(); 4935 Result.Standard.setAsIdentityConversion(); 4936 Result.Standard.setFromType(ToType); 4937 Result.Standard.setAllToTypes(ToType); 4938 return Result; 4939 } 4940 } 4941 } 4942 4943 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4944 // C++11 [over.ics.list]p2: 4945 // If the parameter type is std::initializer_list<X> or "array of X" and 4946 // all the elements can be implicitly converted to X, the implicit 4947 // conversion sequence is the worst conversion necessary to convert an 4948 // element of the list to X. 4949 // 4950 // C++14 [over.ics.list]p3: 4951 // Otherwise, if the parameter type is "array of N X", if the initializer 4952 // list has exactly N elements or if it has fewer than N elements and X is 4953 // default-constructible, and if all the elements of the initializer list 4954 // can be implicitly converted to X, the implicit conversion sequence is 4955 // the worst conversion necessary to convert an element of the list to X. 4956 // 4957 // FIXME: We're missing a lot of these checks. 4958 bool toStdInitializerList = false; 4959 QualType X; 4960 if (ToType->isArrayType()) 4961 X = S.Context.getAsArrayType(ToType)->getElementType(); 4962 else 4963 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4964 if (!X.isNull()) { 4965 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4966 Expr *Init = From->getInit(i); 4967 ImplicitConversionSequence ICS = 4968 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4969 InOverloadResolution, 4970 AllowObjCWritebackConversion); 4971 // If a single element isn't convertible, fail. 4972 if (ICS.isBad()) { 4973 Result = ICS; 4974 break; 4975 } 4976 // Otherwise, look for the worst conversion. 4977 if (Result.isBad() || CompareImplicitConversionSequences( 4978 S, From->getBeginLoc(), ICS, Result) == 4979 ImplicitConversionSequence::Worse) 4980 Result = ICS; 4981 } 4982 4983 // For an empty list, we won't have computed any conversion sequence. 4984 // Introduce the identity conversion sequence. 4985 if (From->getNumInits() == 0) { 4986 Result.setStandard(); 4987 Result.Standard.setAsIdentityConversion(); 4988 Result.Standard.setFromType(ToType); 4989 Result.Standard.setAllToTypes(ToType); 4990 } 4991 4992 Result.setStdInitializerListElement(toStdInitializerList); 4993 return Result; 4994 } 4995 4996 // C++14 [over.ics.list]p4: 4997 // C++11 [over.ics.list]p3: 4998 // Otherwise, if the parameter is a non-aggregate class X and overload 4999 // resolution chooses a single best constructor [...] the implicit 5000 // conversion sequence is a user-defined conversion sequence. If multiple 5001 // constructors are viable but none is better than the others, the 5002 // implicit conversion sequence is a user-defined conversion sequence. 5003 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5004 // This function can deal with initializer lists. 5005 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5006 /*AllowExplicit=*/false, 5007 InOverloadResolution, /*CStyle=*/false, 5008 AllowObjCWritebackConversion, 5009 /*AllowObjCConversionOnExplicit=*/false); 5010 } 5011 5012 // C++14 [over.ics.list]p5: 5013 // C++11 [over.ics.list]p4: 5014 // Otherwise, if the parameter has an aggregate type which can be 5015 // initialized from the initializer list [...] the implicit conversion 5016 // sequence is a user-defined conversion sequence. 5017 if (ToType->isAggregateType()) { 5018 // Type is an aggregate, argument is an init list. At this point it comes 5019 // down to checking whether the initialization works. 5020 // FIXME: Find out whether this parameter is consumed or not. 5021 InitializedEntity Entity = 5022 InitializedEntity::InitializeParameter(S.Context, ToType, 5023 /*Consumed=*/false); 5024 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5025 From)) { 5026 Result.setUserDefined(); 5027 Result.UserDefined.Before.setAsIdentityConversion(); 5028 // Initializer lists don't have a type. 5029 Result.UserDefined.Before.setFromType(QualType()); 5030 Result.UserDefined.Before.setAllToTypes(QualType()); 5031 5032 Result.UserDefined.After.setAsIdentityConversion(); 5033 Result.UserDefined.After.setFromType(ToType); 5034 Result.UserDefined.After.setAllToTypes(ToType); 5035 Result.UserDefined.ConversionFunction = nullptr; 5036 } 5037 return Result; 5038 } 5039 5040 // C++14 [over.ics.list]p6: 5041 // C++11 [over.ics.list]p5: 5042 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5043 if (ToType->isReferenceType()) { 5044 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5045 // mention initializer lists in any way. So we go by what list- 5046 // initialization would do and try to extrapolate from that. 5047 5048 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5049 5050 // If the initializer list has a single element that is reference-related 5051 // to the parameter type, we initialize the reference from that. 5052 if (From->getNumInits() == 1) { 5053 Expr *Init = From->getInit(0); 5054 5055 QualType T2 = Init->getType(); 5056 5057 // If the initializer is the address of an overloaded function, try 5058 // to resolve the overloaded function. If all goes well, T2 is the 5059 // type of the resulting function. 5060 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5061 DeclAccessPair Found; 5062 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5063 Init, ToType, false, Found)) 5064 T2 = Fn->getType(); 5065 } 5066 5067 // Compute some basic properties of the types and the initializer. 5068 Sema::ReferenceCompareResult RefRelationship = 5069 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5070 5071 if (RefRelationship >= Sema::Ref_Related) { 5072 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5073 SuppressUserConversions, 5074 /*AllowExplicit=*/false); 5075 } 5076 } 5077 5078 // Otherwise, we bind the reference to a temporary created from the 5079 // initializer list. 5080 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5081 InOverloadResolution, 5082 AllowObjCWritebackConversion); 5083 if (Result.isFailure()) 5084 return Result; 5085 assert(!Result.isEllipsis() && 5086 "Sub-initialization cannot result in ellipsis conversion."); 5087 5088 // Can we even bind to a temporary? 5089 if (ToType->isRValueReferenceType() || 5090 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5091 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5092 Result.UserDefined.After; 5093 SCS.ReferenceBinding = true; 5094 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5095 SCS.BindsToRvalue = true; 5096 SCS.BindsToFunctionLvalue = false; 5097 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5098 SCS.ObjCLifetimeConversionBinding = false; 5099 } else 5100 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5101 From, ToType); 5102 return Result; 5103 } 5104 5105 // C++14 [over.ics.list]p7: 5106 // C++11 [over.ics.list]p6: 5107 // Otherwise, if the parameter type is not a class: 5108 if (!ToType->isRecordType()) { 5109 // - if the initializer list has one element that is not itself an 5110 // initializer list, the implicit conversion sequence is the one 5111 // required to convert the element to the parameter type. 5112 unsigned NumInits = From->getNumInits(); 5113 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5114 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5115 SuppressUserConversions, 5116 InOverloadResolution, 5117 AllowObjCWritebackConversion); 5118 // - if the initializer list has no elements, the implicit conversion 5119 // sequence is the identity conversion. 5120 else if (NumInits == 0) { 5121 Result.setStandard(); 5122 Result.Standard.setAsIdentityConversion(); 5123 Result.Standard.setFromType(ToType); 5124 Result.Standard.setAllToTypes(ToType); 5125 } 5126 return Result; 5127 } 5128 5129 // C++14 [over.ics.list]p8: 5130 // C++11 [over.ics.list]p7: 5131 // In all cases other than those enumerated above, no conversion is possible 5132 return Result; 5133 } 5134 5135 /// TryCopyInitialization - Try to copy-initialize a value of type 5136 /// ToType from the expression From. Return the implicit conversion 5137 /// sequence required to pass this argument, which may be a bad 5138 /// conversion sequence (meaning that the argument cannot be passed to 5139 /// a parameter of this type). If @p SuppressUserConversions, then we 5140 /// do not permit any user-defined conversion sequences. 5141 static ImplicitConversionSequence 5142 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5143 bool SuppressUserConversions, 5144 bool InOverloadResolution, 5145 bool AllowObjCWritebackConversion, 5146 bool AllowExplicit) { 5147 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5148 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5149 InOverloadResolution,AllowObjCWritebackConversion); 5150 5151 if (ToType->isReferenceType()) 5152 return TryReferenceInit(S, From, ToType, 5153 /*FIXME:*/ From->getBeginLoc(), 5154 SuppressUserConversions, AllowExplicit); 5155 5156 return TryImplicitConversion(S, From, ToType, 5157 SuppressUserConversions, 5158 /*AllowExplicit=*/false, 5159 InOverloadResolution, 5160 /*CStyle=*/false, 5161 AllowObjCWritebackConversion, 5162 /*AllowObjCConversionOnExplicit=*/false); 5163 } 5164 5165 static bool TryCopyInitialization(const CanQualType FromQTy, 5166 const CanQualType ToQTy, 5167 Sema &S, 5168 SourceLocation Loc, 5169 ExprValueKind FromVK) { 5170 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5171 ImplicitConversionSequence ICS = 5172 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5173 5174 return !ICS.isBad(); 5175 } 5176 5177 /// TryObjectArgumentInitialization - Try to initialize the object 5178 /// parameter of the given member function (@c Method) from the 5179 /// expression @p From. 5180 static ImplicitConversionSequence 5181 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5182 Expr::Classification FromClassification, 5183 CXXMethodDecl *Method, 5184 CXXRecordDecl *ActingContext) { 5185 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5186 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5187 // const volatile object. 5188 Qualifiers Quals = Method->getMethodQualifiers(); 5189 if (isa<CXXDestructorDecl>(Method)) { 5190 Quals.addConst(); 5191 Quals.addVolatile(); 5192 } 5193 5194 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5195 5196 // Set up the conversion sequence as a "bad" conversion, to allow us 5197 // to exit early. 5198 ImplicitConversionSequence ICS; 5199 5200 // We need to have an object of class type. 5201 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5202 FromType = PT->getPointeeType(); 5203 5204 // When we had a pointer, it's implicitly dereferenced, so we 5205 // better have an lvalue. 5206 assert(FromClassification.isLValue()); 5207 } 5208 5209 assert(FromType->isRecordType()); 5210 5211 // C++0x [over.match.funcs]p4: 5212 // For non-static member functions, the type of the implicit object 5213 // parameter is 5214 // 5215 // - "lvalue reference to cv X" for functions declared without a 5216 // ref-qualifier or with the & ref-qualifier 5217 // - "rvalue reference to cv X" for functions declared with the && 5218 // ref-qualifier 5219 // 5220 // where X is the class of which the function is a member and cv is the 5221 // cv-qualification on the member function declaration. 5222 // 5223 // However, when finding an implicit conversion sequence for the argument, we 5224 // are not allowed to perform user-defined conversions 5225 // (C++ [over.match.funcs]p5). We perform a simplified version of 5226 // reference binding here, that allows class rvalues to bind to 5227 // non-constant references. 5228 5229 // First check the qualifiers. 5230 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5231 if (ImplicitParamType.getCVRQualifiers() 5232 != FromTypeCanon.getLocalCVRQualifiers() && 5233 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5234 ICS.setBad(BadConversionSequence::bad_qualifiers, 5235 FromType, ImplicitParamType); 5236 return ICS; 5237 } 5238 5239 if (FromTypeCanon.hasAddressSpace()) { 5240 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5241 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5242 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5243 ICS.setBad(BadConversionSequence::bad_qualifiers, 5244 FromType, ImplicitParamType); 5245 return ICS; 5246 } 5247 } 5248 5249 // Check that we have either the same type or a derived type. It 5250 // affects the conversion rank. 5251 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5252 ImplicitConversionKind SecondKind; 5253 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5254 SecondKind = ICK_Identity; 5255 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5256 SecondKind = ICK_Derived_To_Base; 5257 else { 5258 ICS.setBad(BadConversionSequence::unrelated_class, 5259 FromType, ImplicitParamType); 5260 return ICS; 5261 } 5262 5263 // Check the ref-qualifier. 5264 switch (Method->getRefQualifier()) { 5265 case RQ_None: 5266 // Do nothing; we don't care about lvalueness or rvalueness. 5267 break; 5268 5269 case RQ_LValue: 5270 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5271 // non-const lvalue reference cannot bind to an rvalue 5272 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5273 ImplicitParamType); 5274 return ICS; 5275 } 5276 break; 5277 5278 case RQ_RValue: 5279 if (!FromClassification.isRValue()) { 5280 // rvalue reference cannot bind to an lvalue 5281 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5282 ImplicitParamType); 5283 return ICS; 5284 } 5285 break; 5286 } 5287 5288 // Success. Mark this as a reference binding. 5289 ICS.setStandard(); 5290 ICS.Standard.setAsIdentityConversion(); 5291 ICS.Standard.Second = SecondKind; 5292 ICS.Standard.setFromType(FromType); 5293 ICS.Standard.setAllToTypes(ImplicitParamType); 5294 ICS.Standard.ReferenceBinding = true; 5295 ICS.Standard.DirectBinding = true; 5296 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5297 ICS.Standard.BindsToFunctionLvalue = false; 5298 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5299 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5300 = (Method->getRefQualifier() == RQ_None); 5301 return ICS; 5302 } 5303 5304 /// PerformObjectArgumentInitialization - Perform initialization of 5305 /// the implicit object parameter for the given Method with the given 5306 /// expression. 5307 ExprResult 5308 Sema::PerformObjectArgumentInitialization(Expr *From, 5309 NestedNameSpecifier *Qualifier, 5310 NamedDecl *FoundDecl, 5311 CXXMethodDecl *Method) { 5312 QualType FromRecordType, DestType; 5313 QualType ImplicitParamRecordType = 5314 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5315 5316 Expr::Classification FromClassification; 5317 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5318 FromRecordType = PT->getPointeeType(); 5319 DestType = Method->getThisType(); 5320 FromClassification = Expr::Classification::makeSimpleLValue(); 5321 } else { 5322 FromRecordType = From->getType(); 5323 DestType = ImplicitParamRecordType; 5324 FromClassification = From->Classify(Context); 5325 5326 // When performing member access on an rvalue, materialize a temporary. 5327 if (From->isRValue()) { 5328 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5329 Method->getRefQualifier() != 5330 RefQualifierKind::RQ_RValue); 5331 } 5332 } 5333 5334 // Note that we always use the true parent context when performing 5335 // the actual argument initialization. 5336 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5337 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5338 Method->getParent()); 5339 if (ICS.isBad()) { 5340 switch (ICS.Bad.Kind) { 5341 case BadConversionSequence::bad_qualifiers: { 5342 Qualifiers FromQs = FromRecordType.getQualifiers(); 5343 Qualifiers ToQs = DestType.getQualifiers(); 5344 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5345 if (CVR) { 5346 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5347 << Method->getDeclName() << FromRecordType << (CVR - 1) 5348 << From->getSourceRange(); 5349 Diag(Method->getLocation(), diag::note_previous_decl) 5350 << Method->getDeclName(); 5351 return ExprError(); 5352 } 5353 break; 5354 } 5355 5356 case BadConversionSequence::lvalue_ref_to_rvalue: 5357 case BadConversionSequence::rvalue_ref_to_lvalue: { 5358 bool IsRValueQualified = 5359 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5360 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5361 << Method->getDeclName() << FromClassification.isRValue() 5362 << IsRValueQualified; 5363 Diag(Method->getLocation(), diag::note_previous_decl) 5364 << Method->getDeclName(); 5365 return ExprError(); 5366 } 5367 5368 case BadConversionSequence::no_conversion: 5369 case BadConversionSequence::unrelated_class: 5370 break; 5371 } 5372 5373 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5374 << ImplicitParamRecordType << FromRecordType 5375 << From->getSourceRange(); 5376 } 5377 5378 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5379 ExprResult FromRes = 5380 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5381 if (FromRes.isInvalid()) 5382 return ExprError(); 5383 From = FromRes.get(); 5384 } 5385 5386 if (!Context.hasSameType(From->getType(), DestType)) { 5387 CastKind CK; 5388 QualType PteeTy = DestType->getPointeeType(); 5389 LangAS DestAS = 5390 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5391 if (FromRecordType.getAddressSpace() != DestAS) 5392 CK = CK_AddressSpaceConversion; 5393 else 5394 CK = CK_NoOp; 5395 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5396 } 5397 return From; 5398 } 5399 5400 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5401 /// expression From to bool (C++0x [conv]p3). 5402 static ImplicitConversionSequence 5403 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5404 return TryImplicitConversion(S, From, S.Context.BoolTy, 5405 /*SuppressUserConversions=*/false, 5406 /*AllowExplicit=*/true, 5407 /*InOverloadResolution=*/false, 5408 /*CStyle=*/false, 5409 /*AllowObjCWritebackConversion=*/false, 5410 /*AllowObjCConversionOnExplicit=*/false); 5411 } 5412 5413 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5414 /// of the expression From to bool (C++0x [conv]p3). 5415 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5416 if (checkPlaceholderForOverload(*this, From)) 5417 return ExprError(); 5418 5419 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5420 if (!ICS.isBad()) 5421 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5422 5423 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5424 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5425 << From->getType() << From->getSourceRange(); 5426 return ExprError(); 5427 } 5428 5429 /// Check that the specified conversion is permitted in a converted constant 5430 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5431 /// is acceptable. 5432 static bool CheckConvertedConstantConversions(Sema &S, 5433 StandardConversionSequence &SCS) { 5434 // Since we know that the target type is an integral or unscoped enumeration 5435 // type, most conversion kinds are impossible. All possible First and Third 5436 // conversions are fine. 5437 switch (SCS.Second) { 5438 case ICK_Identity: 5439 case ICK_Function_Conversion: 5440 case ICK_Integral_Promotion: 5441 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5442 case ICK_Zero_Queue_Conversion: 5443 return true; 5444 5445 case ICK_Boolean_Conversion: 5446 // Conversion from an integral or unscoped enumeration type to bool is 5447 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5448 // conversion, so we allow it in a converted constant expression. 5449 // 5450 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5451 // a lot of popular code. We should at least add a warning for this 5452 // (non-conforming) extension. 5453 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5454 SCS.getToType(2)->isBooleanType(); 5455 5456 case ICK_Pointer_Conversion: 5457 case ICK_Pointer_Member: 5458 // C++1z: null pointer conversions and null member pointer conversions are 5459 // only permitted if the source type is std::nullptr_t. 5460 return SCS.getFromType()->isNullPtrType(); 5461 5462 case ICK_Floating_Promotion: 5463 case ICK_Complex_Promotion: 5464 case ICK_Floating_Conversion: 5465 case ICK_Complex_Conversion: 5466 case ICK_Floating_Integral: 5467 case ICK_Compatible_Conversion: 5468 case ICK_Derived_To_Base: 5469 case ICK_Vector_Conversion: 5470 case ICK_Vector_Splat: 5471 case ICK_Complex_Real: 5472 case ICK_Block_Pointer_Conversion: 5473 case ICK_TransparentUnionConversion: 5474 case ICK_Writeback_Conversion: 5475 case ICK_Zero_Event_Conversion: 5476 case ICK_C_Only_Conversion: 5477 case ICK_Incompatible_Pointer_Conversion: 5478 return false; 5479 5480 case ICK_Lvalue_To_Rvalue: 5481 case ICK_Array_To_Pointer: 5482 case ICK_Function_To_Pointer: 5483 llvm_unreachable("found a first conversion kind in Second"); 5484 5485 case ICK_Qualification: 5486 llvm_unreachable("found a third conversion kind in Second"); 5487 5488 case ICK_Num_Conversion_Kinds: 5489 break; 5490 } 5491 5492 llvm_unreachable("unknown conversion kind"); 5493 } 5494 5495 /// CheckConvertedConstantExpression - Check that the expression From is a 5496 /// converted constant expression of type T, perform the conversion and produce 5497 /// the converted expression, per C++11 [expr.const]p3. 5498 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5499 QualType T, APValue &Value, 5500 Sema::CCEKind CCE, 5501 bool RequireInt) { 5502 assert(S.getLangOpts().CPlusPlus11 && 5503 "converted constant expression outside C++11"); 5504 5505 if (checkPlaceholderForOverload(S, From)) 5506 return ExprError(); 5507 5508 // C++1z [expr.const]p3: 5509 // A converted constant expression of type T is an expression, 5510 // implicitly converted to type T, where the converted 5511 // expression is a constant expression and the implicit conversion 5512 // sequence contains only [... list of conversions ...]. 5513 // C++1z [stmt.if]p2: 5514 // If the if statement is of the form if constexpr, the value of the 5515 // condition shall be a contextually converted constant expression of type 5516 // bool. 5517 ImplicitConversionSequence ICS = 5518 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5519 ? TryContextuallyConvertToBool(S, From) 5520 : TryCopyInitialization(S, From, T, 5521 /*SuppressUserConversions=*/false, 5522 /*InOverloadResolution=*/false, 5523 /*AllowObjCWritebackConversion=*/false, 5524 /*AllowExplicit=*/false); 5525 StandardConversionSequence *SCS = nullptr; 5526 switch (ICS.getKind()) { 5527 case ImplicitConversionSequence::StandardConversion: 5528 SCS = &ICS.Standard; 5529 break; 5530 case ImplicitConversionSequence::UserDefinedConversion: 5531 // We are converting to a non-class type, so the Before sequence 5532 // must be trivial. 5533 SCS = &ICS.UserDefined.After; 5534 break; 5535 case ImplicitConversionSequence::AmbiguousConversion: 5536 case ImplicitConversionSequence::BadConversion: 5537 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5538 return S.Diag(From->getBeginLoc(), 5539 diag::err_typecheck_converted_constant_expression) 5540 << From->getType() << From->getSourceRange() << T; 5541 return ExprError(); 5542 5543 case ImplicitConversionSequence::EllipsisConversion: 5544 llvm_unreachable("ellipsis conversion in converted constant expression"); 5545 } 5546 5547 // Check that we would only use permitted conversions. 5548 if (!CheckConvertedConstantConversions(S, *SCS)) { 5549 return S.Diag(From->getBeginLoc(), 5550 diag::err_typecheck_converted_constant_expression_disallowed) 5551 << From->getType() << From->getSourceRange() << T; 5552 } 5553 // [...] and where the reference binding (if any) binds directly. 5554 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5555 return S.Diag(From->getBeginLoc(), 5556 diag::err_typecheck_converted_constant_expression_indirect) 5557 << From->getType() << From->getSourceRange() << T; 5558 } 5559 5560 ExprResult Result = 5561 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5562 if (Result.isInvalid()) 5563 return Result; 5564 5565 // C++2a [intro.execution]p5: 5566 // A full-expression is [...] a constant-expression [...] 5567 Result = 5568 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5569 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5570 if (Result.isInvalid()) 5571 return Result; 5572 5573 // Check for a narrowing implicit conversion. 5574 APValue PreNarrowingValue; 5575 QualType PreNarrowingType; 5576 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5577 PreNarrowingType)) { 5578 case NK_Dependent_Narrowing: 5579 // Implicit conversion to a narrower type, but the expression is 5580 // value-dependent so we can't tell whether it's actually narrowing. 5581 case NK_Variable_Narrowing: 5582 // Implicit conversion to a narrower type, and the value is not a constant 5583 // expression. We'll diagnose this in a moment. 5584 case NK_Not_Narrowing: 5585 break; 5586 5587 case NK_Constant_Narrowing: 5588 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5589 << CCE << /*Constant*/ 1 5590 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5591 break; 5592 5593 case NK_Type_Narrowing: 5594 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5595 << CCE << /*Constant*/ 0 << From->getType() << T; 5596 break; 5597 } 5598 5599 if (Result.get()->isValueDependent()) { 5600 Value = APValue(); 5601 return Result; 5602 } 5603 5604 // Check the expression is a constant expression. 5605 SmallVector<PartialDiagnosticAt, 8> Notes; 5606 Expr::EvalResult Eval; 5607 Eval.Diag = &Notes; 5608 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5609 ? Expr::EvaluateForMangling 5610 : Expr::EvaluateForCodeGen; 5611 5612 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5613 (RequireInt && !Eval.Val.isInt())) { 5614 // The expression can't be folded, so we can't keep it at this position in 5615 // the AST. 5616 Result = ExprError(); 5617 } else { 5618 Value = Eval.Val; 5619 5620 if (Notes.empty()) { 5621 // It's a constant expression. 5622 return ConstantExpr::Create(S.Context, Result.get(), Value); 5623 } 5624 } 5625 5626 // It's not a constant expression. Produce an appropriate diagnostic. 5627 if (Notes.size() == 1 && 5628 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5629 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5630 else { 5631 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5632 << CCE << From->getSourceRange(); 5633 for (unsigned I = 0; I < Notes.size(); ++I) 5634 S.Diag(Notes[I].first, Notes[I].second); 5635 } 5636 return ExprError(); 5637 } 5638 5639 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5640 APValue &Value, CCEKind CCE) { 5641 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5642 } 5643 5644 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5645 llvm::APSInt &Value, 5646 CCEKind CCE) { 5647 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5648 5649 APValue V; 5650 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5651 if (!R.isInvalid() && !R.get()->isValueDependent()) 5652 Value = V.getInt(); 5653 return R; 5654 } 5655 5656 5657 /// dropPointerConversions - If the given standard conversion sequence 5658 /// involves any pointer conversions, remove them. This may change 5659 /// the result type of the conversion sequence. 5660 static void dropPointerConversion(StandardConversionSequence &SCS) { 5661 if (SCS.Second == ICK_Pointer_Conversion) { 5662 SCS.Second = ICK_Identity; 5663 SCS.Third = ICK_Identity; 5664 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5665 } 5666 } 5667 5668 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5669 /// convert the expression From to an Objective-C pointer type. 5670 static ImplicitConversionSequence 5671 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5672 // Do an implicit conversion to 'id'. 5673 QualType Ty = S.Context.getObjCIdType(); 5674 ImplicitConversionSequence ICS 5675 = TryImplicitConversion(S, From, Ty, 5676 // FIXME: Are these flags correct? 5677 /*SuppressUserConversions=*/false, 5678 /*AllowExplicit=*/true, 5679 /*InOverloadResolution=*/false, 5680 /*CStyle=*/false, 5681 /*AllowObjCWritebackConversion=*/false, 5682 /*AllowObjCConversionOnExplicit=*/true); 5683 5684 // Strip off any final conversions to 'id'. 5685 switch (ICS.getKind()) { 5686 case ImplicitConversionSequence::BadConversion: 5687 case ImplicitConversionSequence::AmbiguousConversion: 5688 case ImplicitConversionSequence::EllipsisConversion: 5689 break; 5690 5691 case ImplicitConversionSequence::UserDefinedConversion: 5692 dropPointerConversion(ICS.UserDefined.After); 5693 break; 5694 5695 case ImplicitConversionSequence::StandardConversion: 5696 dropPointerConversion(ICS.Standard); 5697 break; 5698 } 5699 5700 return ICS; 5701 } 5702 5703 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5704 /// conversion of the expression From to an Objective-C pointer type. 5705 /// Returns a valid but null ExprResult if no conversion sequence exists. 5706 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5707 if (checkPlaceholderForOverload(*this, From)) 5708 return ExprError(); 5709 5710 QualType Ty = Context.getObjCIdType(); 5711 ImplicitConversionSequence ICS = 5712 TryContextuallyConvertToObjCPointer(*this, From); 5713 if (!ICS.isBad()) 5714 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5715 return ExprResult(); 5716 } 5717 5718 /// Determine whether the provided type is an integral type, or an enumeration 5719 /// type of a permitted flavor. 5720 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5721 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5722 : T->isIntegralOrUnscopedEnumerationType(); 5723 } 5724 5725 static ExprResult 5726 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5727 Sema::ContextualImplicitConverter &Converter, 5728 QualType T, UnresolvedSetImpl &ViableConversions) { 5729 5730 if (Converter.Suppress) 5731 return ExprError(); 5732 5733 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5734 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5735 CXXConversionDecl *Conv = 5736 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5737 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5738 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5739 } 5740 return From; 5741 } 5742 5743 static bool 5744 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5745 Sema::ContextualImplicitConverter &Converter, 5746 QualType T, bool HadMultipleCandidates, 5747 UnresolvedSetImpl &ExplicitConversions) { 5748 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5749 DeclAccessPair Found = ExplicitConversions[0]; 5750 CXXConversionDecl *Conversion = 5751 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5752 5753 // The user probably meant to invoke the given explicit 5754 // conversion; use it. 5755 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5756 std::string TypeStr; 5757 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5758 5759 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5760 << FixItHint::CreateInsertion(From->getBeginLoc(), 5761 "static_cast<" + TypeStr + ">(") 5762 << FixItHint::CreateInsertion( 5763 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5764 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5765 5766 // If we aren't in a SFINAE context, build a call to the 5767 // explicit conversion function. 5768 if (SemaRef.isSFINAEContext()) 5769 return true; 5770 5771 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5772 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5773 HadMultipleCandidates); 5774 if (Result.isInvalid()) 5775 return true; 5776 // Record usage of conversion in an implicit cast. 5777 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5778 CK_UserDefinedConversion, Result.get(), 5779 nullptr, Result.get()->getValueKind()); 5780 } 5781 return false; 5782 } 5783 5784 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5785 Sema::ContextualImplicitConverter &Converter, 5786 QualType T, bool HadMultipleCandidates, 5787 DeclAccessPair &Found) { 5788 CXXConversionDecl *Conversion = 5789 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5790 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5791 5792 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5793 if (!Converter.SuppressConversion) { 5794 if (SemaRef.isSFINAEContext()) 5795 return true; 5796 5797 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5798 << From->getSourceRange(); 5799 } 5800 5801 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5802 HadMultipleCandidates); 5803 if (Result.isInvalid()) 5804 return true; 5805 // Record usage of conversion in an implicit cast. 5806 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5807 CK_UserDefinedConversion, Result.get(), 5808 nullptr, Result.get()->getValueKind()); 5809 return false; 5810 } 5811 5812 static ExprResult finishContextualImplicitConversion( 5813 Sema &SemaRef, SourceLocation Loc, Expr *From, 5814 Sema::ContextualImplicitConverter &Converter) { 5815 if (!Converter.match(From->getType()) && !Converter.Suppress) 5816 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5817 << From->getSourceRange(); 5818 5819 return SemaRef.DefaultLvalueConversion(From); 5820 } 5821 5822 static void 5823 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5824 UnresolvedSetImpl &ViableConversions, 5825 OverloadCandidateSet &CandidateSet) { 5826 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5827 DeclAccessPair FoundDecl = ViableConversions[I]; 5828 NamedDecl *D = FoundDecl.getDecl(); 5829 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5830 if (isa<UsingShadowDecl>(D)) 5831 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5832 5833 CXXConversionDecl *Conv; 5834 FunctionTemplateDecl *ConvTemplate; 5835 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5836 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5837 else 5838 Conv = cast<CXXConversionDecl>(D); 5839 5840 if (ConvTemplate) 5841 SemaRef.AddTemplateConversionCandidate( 5842 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5843 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5844 else 5845 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5846 ToType, CandidateSet, 5847 /*AllowObjCConversionOnExplicit=*/false, 5848 /*AllowExplicit*/ true); 5849 } 5850 } 5851 5852 /// Attempt to convert the given expression to a type which is accepted 5853 /// by the given converter. 5854 /// 5855 /// This routine will attempt to convert an expression of class type to a 5856 /// type accepted by the specified converter. In C++11 and before, the class 5857 /// must have a single non-explicit conversion function converting to a matching 5858 /// type. In C++1y, there can be multiple such conversion functions, but only 5859 /// one target type. 5860 /// 5861 /// \param Loc The source location of the construct that requires the 5862 /// conversion. 5863 /// 5864 /// \param From The expression we're converting from. 5865 /// 5866 /// \param Converter Used to control and diagnose the conversion process. 5867 /// 5868 /// \returns The expression, converted to an integral or enumeration type if 5869 /// successful. 5870 ExprResult Sema::PerformContextualImplicitConversion( 5871 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5872 // We can't perform any more checking for type-dependent expressions. 5873 if (From->isTypeDependent()) 5874 return From; 5875 5876 // Process placeholders immediately. 5877 if (From->hasPlaceholderType()) { 5878 ExprResult result = CheckPlaceholderExpr(From); 5879 if (result.isInvalid()) 5880 return result; 5881 From = result.get(); 5882 } 5883 5884 // If the expression already has a matching type, we're golden. 5885 QualType T = From->getType(); 5886 if (Converter.match(T)) 5887 return DefaultLvalueConversion(From); 5888 5889 // FIXME: Check for missing '()' if T is a function type? 5890 5891 // We can only perform contextual implicit conversions on objects of class 5892 // type. 5893 const RecordType *RecordTy = T->getAs<RecordType>(); 5894 if (!RecordTy || !getLangOpts().CPlusPlus) { 5895 if (!Converter.Suppress) 5896 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5897 return From; 5898 } 5899 5900 // We must have a complete class type. 5901 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5902 ContextualImplicitConverter &Converter; 5903 Expr *From; 5904 5905 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5906 : Converter(Converter), From(From) {} 5907 5908 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5909 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5910 } 5911 } IncompleteDiagnoser(Converter, From); 5912 5913 if (Converter.Suppress ? !isCompleteType(Loc, T) 5914 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5915 return From; 5916 5917 // Look for a conversion to an integral or enumeration type. 5918 UnresolvedSet<4> 5919 ViableConversions; // These are *potentially* viable in C++1y. 5920 UnresolvedSet<4> ExplicitConversions; 5921 const auto &Conversions = 5922 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5923 5924 bool HadMultipleCandidates = 5925 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5926 5927 // To check that there is only one target type, in C++1y: 5928 QualType ToType; 5929 bool HasUniqueTargetType = true; 5930 5931 // Collect explicit or viable (potentially in C++1y) conversions. 5932 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5933 NamedDecl *D = (*I)->getUnderlyingDecl(); 5934 CXXConversionDecl *Conversion; 5935 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5936 if (ConvTemplate) { 5937 if (getLangOpts().CPlusPlus14) 5938 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5939 else 5940 continue; // C++11 does not consider conversion operator templates(?). 5941 } else 5942 Conversion = cast<CXXConversionDecl>(D); 5943 5944 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5945 "Conversion operator templates are considered potentially " 5946 "viable in C++1y"); 5947 5948 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5949 if (Converter.match(CurToType) || ConvTemplate) { 5950 5951 if (Conversion->isExplicit()) { 5952 // FIXME: For C++1y, do we need this restriction? 5953 // cf. diagnoseNoViableConversion() 5954 if (!ConvTemplate) 5955 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5956 } else { 5957 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5958 if (ToType.isNull()) 5959 ToType = CurToType.getUnqualifiedType(); 5960 else if (HasUniqueTargetType && 5961 (CurToType.getUnqualifiedType() != ToType)) 5962 HasUniqueTargetType = false; 5963 } 5964 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5965 } 5966 } 5967 } 5968 5969 if (getLangOpts().CPlusPlus14) { 5970 // C++1y [conv]p6: 5971 // ... An expression e of class type E appearing in such a context 5972 // is said to be contextually implicitly converted to a specified 5973 // type T and is well-formed if and only if e can be implicitly 5974 // converted to a type T that is determined as follows: E is searched 5975 // for conversion functions whose return type is cv T or reference to 5976 // cv T such that T is allowed by the context. There shall be 5977 // exactly one such T. 5978 5979 // If no unique T is found: 5980 if (ToType.isNull()) { 5981 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5982 HadMultipleCandidates, 5983 ExplicitConversions)) 5984 return ExprError(); 5985 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5986 } 5987 5988 // If more than one unique Ts are found: 5989 if (!HasUniqueTargetType) 5990 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5991 ViableConversions); 5992 5993 // If one unique T is found: 5994 // First, build a candidate set from the previously recorded 5995 // potentially viable conversions. 5996 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5997 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5998 CandidateSet); 5999 6000 // Then, perform overload resolution over the candidate set. 6001 OverloadCandidateSet::iterator Best; 6002 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6003 case OR_Success: { 6004 // Apply this conversion. 6005 DeclAccessPair Found = 6006 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6007 if (recordConversion(*this, Loc, From, Converter, T, 6008 HadMultipleCandidates, Found)) 6009 return ExprError(); 6010 break; 6011 } 6012 case OR_Ambiguous: 6013 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6014 ViableConversions); 6015 case OR_No_Viable_Function: 6016 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6017 HadMultipleCandidates, 6018 ExplicitConversions)) 6019 return ExprError(); 6020 LLVM_FALLTHROUGH; 6021 case OR_Deleted: 6022 // We'll complain below about a non-integral condition type. 6023 break; 6024 } 6025 } else { 6026 switch (ViableConversions.size()) { 6027 case 0: { 6028 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6029 HadMultipleCandidates, 6030 ExplicitConversions)) 6031 return ExprError(); 6032 6033 // We'll complain below about a non-integral condition type. 6034 break; 6035 } 6036 case 1: { 6037 // Apply this conversion. 6038 DeclAccessPair Found = ViableConversions[0]; 6039 if (recordConversion(*this, Loc, From, Converter, T, 6040 HadMultipleCandidates, Found)) 6041 return ExprError(); 6042 break; 6043 } 6044 default: 6045 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6046 ViableConversions); 6047 } 6048 } 6049 6050 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6051 } 6052 6053 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6054 /// an acceptable non-member overloaded operator for a call whose 6055 /// arguments have types T1 (and, if non-empty, T2). This routine 6056 /// implements the check in C++ [over.match.oper]p3b2 concerning 6057 /// enumeration types. 6058 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6059 FunctionDecl *Fn, 6060 ArrayRef<Expr *> Args) { 6061 QualType T1 = Args[0]->getType(); 6062 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6063 6064 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6065 return true; 6066 6067 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6068 return true; 6069 6070 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 6071 if (Proto->getNumParams() < 1) 6072 return false; 6073 6074 if (T1->isEnumeralType()) { 6075 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6076 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6077 return true; 6078 } 6079 6080 if (Proto->getNumParams() < 2) 6081 return false; 6082 6083 if (!T2.isNull() && T2->isEnumeralType()) { 6084 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6085 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6086 return true; 6087 } 6088 6089 return false; 6090 } 6091 6092 /// AddOverloadCandidate - Adds the given function to the set of 6093 /// candidate functions, using the given function call arguments. If 6094 /// @p SuppressUserConversions, then don't allow user-defined 6095 /// conversions via constructors or conversion operators. 6096 /// 6097 /// \param PartialOverloading true if we are performing "partial" overloading 6098 /// based on an incomplete set of function arguments. This feature is used by 6099 /// code completion. 6100 void Sema::AddOverloadCandidate( 6101 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6102 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6103 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6104 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6105 OverloadCandidateParamOrder PO) { 6106 const FunctionProtoType *Proto 6107 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6108 assert(Proto && "Functions without a prototype cannot be overloaded"); 6109 assert(!Function->getDescribedFunctionTemplate() && 6110 "Use AddTemplateOverloadCandidate for function templates"); 6111 6112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6113 if (!isa<CXXConstructorDecl>(Method)) { 6114 // If we get here, it's because we're calling a member function 6115 // that is named without a member access expression (e.g., 6116 // "this->f") that was either written explicitly or created 6117 // implicitly. This can happen with a qualified call to a member 6118 // function, e.g., X::f(). We use an empty type for the implied 6119 // object argument (C++ [over.call.func]p3), and the acting context 6120 // is irrelevant. 6121 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6122 Expr::Classification::makeSimpleLValue(), Args, 6123 CandidateSet, SuppressUserConversions, 6124 PartialOverloading, EarlyConversions, PO); 6125 return; 6126 } 6127 // We treat a constructor like a non-member function, since its object 6128 // argument doesn't participate in overload resolution. 6129 } 6130 6131 if (!CandidateSet.isNewCandidate(Function, PO)) 6132 return; 6133 6134 // C++11 [class.copy]p11: [DR1402] 6135 // A defaulted move constructor that is defined as deleted is ignored by 6136 // overload resolution. 6137 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6138 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6139 Constructor->isMoveConstructor()) 6140 return; 6141 6142 // Overload resolution is always an unevaluated context. 6143 EnterExpressionEvaluationContext Unevaluated( 6144 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6145 6146 // C++ [over.match.oper]p3: 6147 // if no operand has a class type, only those non-member functions in the 6148 // lookup set that have a first parameter of type T1 or "reference to 6149 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6150 // is a right operand) a second parameter of type T2 or "reference to 6151 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6152 // candidate functions. 6153 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6154 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6155 return; 6156 6157 // Add this candidate 6158 OverloadCandidate &Candidate = 6159 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6160 Candidate.FoundDecl = FoundDecl; 6161 Candidate.Function = Function; 6162 Candidate.Viable = true; 6163 Candidate.RewriteKind = 6164 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6165 Candidate.IsSurrogate = false; 6166 Candidate.IsADLCandidate = IsADLCandidate; 6167 Candidate.IgnoreObjectArgument = false; 6168 Candidate.ExplicitCallArguments = Args.size(); 6169 6170 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6171 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6172 Candidate.Viable = false; 6173 Candidate.FailureKind = ovl_non_default_multiversion_function; 6174 return; 6175 } 6176 6177 if (Constructor) { 6178 // C++ [class.copy]p3: 6179 // A member function template is never instantiated to perform the copy 6180 // of a class object to an object of its class type. 6181 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6182 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6183 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6184 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6185 ClassType))) { 6186 Candidate.Viable = false; 6187 Candidate.FailureKind = ovl_fail_illegal_constructor; 6188 return; 6189 } 6190 6191 // C++ [over.match.funcs]p8: (proposed DR resolution) 6192 // A constructor inherited from class type C that has a first parameter 6193 // of type "reference to P" (including such a constructor instantiated 6194 // from a template) is excluded from the set of candidate functions when 6195 // constructing an object of type cv D if the argument list has exactly 6196 // one argument and D is reference-related to P and P is reference-related 6197 // to C. 6198 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6199 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6200 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6201 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6202 QualType C = Context.getRecordType(Constructor->getParent()); 6203 QualType D = Context.getRecordType(Shadow->getParent()); 6204 SourceLocation Loc = Args.front()->getExprLoc(); 6205 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6206 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6207 Candidate.Viable = false; 6208 Candidate.FailureKind = ovl_fail_inhctor_slice; 6209 return; 6210 } 6211 } 6212 6213 // Check that the constructor is capable of constructing an object in the 6214 // destination address space. 6215 if (!Qualifiers::isAddressSpaceSupersetOf( 6216 Constructor->getMethodQualifiers().getAddressSpace(), 6217 CandidateSet.getDestAS())) { 6218 Candidate.Viable = false; 6219 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6220 } 6221 } 6222 6223 unsigned NumParams = Proto->getNumParams(); 6224 6225 // (C++ 13.3.2p2): A candidate function having fewer than m 6226 // parameters is viable only if it has an ellipsis in its parameter 6227 // list (8.3.5). 6228 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6229 !Proto->isVariadic()) { 6230 Candidate.Viable = false; 6231 Candidate.FailureKind = ovl_fail_too_many_arguments; 6232 return; 6233 } 6234 6235 // (C++ 13.3.2p2): A candidate function having more than m parameters 6236 // is viable only if the (m+1)st parameter has a default argument 6237 // (8.3.6). For the purposes of overload resolution, the 6238 // parameter list is truncated on the right, so that there are 6239 // exactly m parameters. 6240 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6241 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6242 // Not enough arguments. 6243 Candidate.Viable = false; 6244 Candidate.FailureKind = ovl_fail_too_few_arguments; 6245 return; 6246 } 6247 6248 // (CUDA B.1): Check for invalid calls between targets. 6249 if (getLangOpts().CUDA) 6250 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6251 // Skip the check for callers that are implicit members, because in this 6252 // case we may not yet know what the member's target is; the target is 6253 // inferred for the member automatically, based on the bases and fields of 6254 // the class. 6255 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6256 Candidate.Viable = false; 6257 Candidate.FailureKind = ovl_fail_bad_target; 6258 return; 6259 } 6260 6261 // Determine the implicit conversion sequences for each of the 6262 // arguments. 6263 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6264 unsigned ConvIdx = 6265 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6266 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6267 // We already formed a conversion sequence for this parameter during 6268 // template argument deduction. 6269 } else if (ArgIdx < NumParams) { 6270 // (C++ 13.3.2p3): for F to be a viable function, there shall 6271 // exist for each argument an implicit conversion sequence 6272 // (13.3.3.1) that converts that argument to the corresponding 6273 // parameter of F. 6274 QualType ParamType = Proto->getParamType(ArgIdx); 6275 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6276 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6277 /*InOverloadResolution=*/true, 6278 /*AllowObjCWritebackConversion=*/ 6279 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6280 if (Candidate.Conversions[ConvIdx].isBad()) { 6281 Candidate.Viable = false; 6282 Candidate.FailureKind = ovl_fail_bad_conversion; 6283 return; 6284 } 6285 } else { 6286 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6287 // argument for which there is no corresponding parameter is 6288 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6289 Candidate.Conversions[ConvIdx].setEllipsis(); 6290 } 6291 } 6292 6293 if (!AllowExplicit) { 6294 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6295 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6296 Candidate.Viable = false; 6297 Candidate.FailureKind = ovl_fail_explicit_resolved; 6298 return; 6299 } 6300 } 6301 6302 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6303 Candidate.Viable = false; 6304 Candidate.FailureKind = ovl_fail_enable_if; 6305 Candidate.DeductionFailure.Data = FailedAttr; 6306 return; 6307 } 6308 6309 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6310 Candidate.Viable = false; 6311 Candidate.FailureKind = ovl_fail_ext_disabled; 6312 return; 6313 } 6314 } 6315 6316 ObjCMethodDecl * 6317 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6318 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6319 if (Methods.size() <= 1) 6320 return nullptr; 6321 6322 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6323 bool Match = true; 6324 ObjCMethodDecl *Method = Methods[b]; 6325 unsigned NumNamedArgs = Sel.getNumArgs(); 6326 // Method might have more arguments than selector indicates. This is due 6327 // to addition of c-style arguments in method. 6328 if (Method->param_size() > NumNamedArgs) 6329 NumNamedArgs = Method->param_size(); 6330 if (Args.size() < NumNamedArgs) 6331 continue; 6332 6333 for (unsigned i = 0; i < NumNamedArgs; i++) { 6334 // We can't do any type-checking on a type-dependent argument. 6335 if (Args[i]->isTypeDependent()) { 6336 Match = false; 6337 break; 6338 } 6339 6340 ParmVarDecl *param = Method->parameters()[i]; 6341 Expr *argExpr = Args[i]; 6342 assert(argExpr && "SelectBestMethod(): missing expression"); 6343 6344 // Strip the unbridged-cast placeholder expression off unless it's 6345 // a consumed argument. 6346 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6347 !param->hasAttr<CFConsumedAttr>()) 6348 argExpr = stripARCUnbridgedCast(argExpr); 6349 6350 // If the parameter is __unknown_anytype, move on to the next method. 6351 if (param->getType() == Context.UnknownAnyTy) { 6352 Match = false; 6353 break; 6354 } 6355 6356 ImplicitConversionSequence ConversionState 6357 = TryCopyInitialization(*this, argExpr, param->getType(), 6358 /*SuppressUserConversions*/false, 6359 /*InOverloadResolution=*/true, 6360 /*AllowObjCWritebackConversion=*/ 6361 getLangOpts().ObjCAutoRefCount, 6362 /*AllowExplicit*/false); 6363 // This function looks for a reasonably-exact match, so we consider 6364 // incompatible pointer conversions to be a failure here. 6365 if (ConversionState.isBad() || 6366 (ConversionState.isStandard() && 6367 ConversionState.Standard.Second == 6368 ICK_Incompatible_Pointer_Conversion)) { 6369 Match = false; 6370 break; 6371 } 6372 } 6373 // Promote additional arguments to variadic methods. 6374 if (Match && Method->isVariadic()) { 6375 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6376 if (Args[i]->isTypeDependent()) { 6377 Match = false; 6378 break; 6379 } 6380 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6381 nullptr); 6382 if (Arg.isInvalid()) { 6383 Match = false; 6384 break; 6385 } 6386 } 6387 } else { 6388 // Check for extra arguments to non-variadic methods. 6389 if (Args.size() != NumNamedArgs) 6390 Match = false; 6391 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6392 // Special case when selectors have no argument. In this case, select 6393 // one with the most general result type of 'id'. 6394 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6395 QualType ReturnT = Methods[b]->getReturnType(); 6396 if (ReturnT->isObjCIdType()) 6397 return Methods[b]; 6398 } 6399 } 6400 } 6401 6402 if (Match) 6403 return Method; 6404 } 6405 return nullptr; 6406 } 6407 6408 static bool 6409 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6410 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6411 bool MissingImplicitThis, Expr *&ConvertedThis, 6412 SmallVectorImpl<Expr *> &ConvertedArgs) { 6413 if (ThisArg) { 6414 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6415 assert(!isa<CXXConstructorDecl>(Method) && 6416 "Shouldn't have `this` for ctors!"); 6417 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6418 ExprResult R = S.PerformObjectArgumentInitialization( 6419 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6420 if (R.isInvalid()) 6421 return false; 6422 ConvertedThis = R.get(); 6423 } else { 6424 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6425 (void)MD; 6426 assert((MissingImplicitThis || MD->isStatic() || 6427 isa<CXXConstructorDecl>(MD)) && 6428 "Expected `this` for non-ctor instance methods"); 6429 } 6430 ConvertedThis = nullptr; 6431 } 6432 6433 // Ignore any variadic arguments. Converting them is pointless, since the 6434 // user can't refer to them in the function condition. 6435 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6436 6437 // Convert the arguments. 6438 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6439 ExprResult R; 6440 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6441 S.Context, Function->getParamDecl(I)), 6442 SourceLocation(), Args[I]); 6443 6444 if (R.isInvalid()) 6445 return false; 6446 6447 ConvertedArgs.push_back(R.get()); 6448 } 6449 6450 if (Trap.hasErrorOccurred()) 6451 return false; 6452 6453 // Push default arguments if needed. 6454 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6455 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6456 ParmVarDecl *P = Function->getParamDecl(i); 6457 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6458 ? P->getUninstantiatedDefaultArg() 6459 : P->getDefaultArg(); 6460 // This can only happen in code completion, i.e. when PartialOverloading 6461 // is true. 6462 if (!DefArg) 6463 return false; 6464 ExprResult R = 6465 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6466 S.Context, Function->getParamDecl(i)), 6467 SourceLocation(), DefArg); 6468 if (R.isInvalid()) 6469 return false; 6470 ConvertedArgs.push_back(R.get()); 6471 } 6472 6473 if (Trap.hasErrorOccurred()) 6474 return false; 6475 } 6476 return true; 6477 } 6478 6479 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6480 bool MissingImplicitThis) { 6481 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6482 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6483 return nullptr; 6484 6485 SFINAETrap Trap(*this); 6486 SmallVector<Expr *, 16> ConvertedArgs; 6487 // FIXME: We should look into making enable_if late-parsed. 6488 Expr *DiscardedThis; 6489 if (!convertArgsForAvailabilityChecks( 6490 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6491 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6492 return *EnableIfAttrs.begin(); 6493 6494 for (auto *EIA : EnableIfAttrs) { 6495 APValue Result; 6496 // FIXME: This doesn't consider value-dependent cases, because doing so is 6497 // very difficult. Ideally, we should handle them more gracefully. 6498 if (EIA->getCond()->isValueDependent() || 6499 !EIA->getCond()->EvaluateWithSubstitution( 6500 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6501 return EIA; 6502 6503 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6504 return EIA; 6505 } 6506 return nullptr; 6507 } 6508 6509 template <typename CheckFn> 6510 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6511 bool ArgDependent, SourceLocation Loc, 6512 CheckFn &&IsSuccessful) { 6513 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6514 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6515 if (ArgDependent == DIA->getArgDependent()) 6516 Attrs.push_back(DIA); 6517 } 6518 6519 // Common case: No diagnose_if attributes, so we can quit early. 6520 if (Attrs.empty()) 6521 return false; 6522 6523 auto WarningBegin = std::stable_partition( 6524 Attrs.begin(), Attrs.end(), 6525 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6526 6527 // Note that diagnose_if attributes are late-parsed, so they appear in the 6528 // correct order (unlike enable_if attributes). 6529 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6530 IsSuccessful); 6531 if (ErrAttr != WarningBegin) { 6532 const DiagnoseIfAttr *DIA = *ErrAttr; 6533 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6534 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6535 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6536 return true; 6537 } 6538 6539 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6540 if (IsSuccessful(DIA)) { 6541 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6542 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6543 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6544 } 6545 6546 return false; 6547 } 6548 6549 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6550 const Expr *ThisArg, 6551 ArrayRef<const Expr *> Args, 6552 SourceLocation Loc) { 6553 return diagnoseDiagnoseIfAttrsWith( 6554 *this, Function, /*ArgDependent=*/true, Loc, 6555 [&](const DiagnoseIfAttr *DIA) { 6556 APValue Result; 6557 // It's sane to use the same Args for any redecl of this function, since 6558 // EvaluateWithSubstitution only cares about the position of each 6559 // argument in the arg list, not the ParmVarDecl* it maps to. 6560 if (!DIA->getCond()->EvaluateWithSubstitution( 6561 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6562 return false; 6563 return Result.isInt() && Result.getInt().getBoolValue(); 6564 }); 6565 } 6566 6567 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6568 SourceLocation Loc) { 6569 return diagnoseDiagnoseIfAttrsWith( 6570 *this, ND, /*ArgDependent=*/false, Loc, 6571 [&](const DiagnoseIfAttr *DIA) { 6572 bool Result; 6573 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6574 Result; 6575 }); 6576 } 6577 6578 /// Add all of the function declarations in the given function set to 6579 /// the overload candidate set. 6580 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6581 ArrayRef<Expr *> Args, 6582 OverloadCandidateSet &CandidateSet, 6583 TemplateArgumentListInfo *ExplicitTemplateArgs, 6584 bool SuppressUserConversions, 6585 bool PartialOverloading, 6586 bool FirstArgumentIsBase) { 6587 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6588 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6589 ArrayRef<Expr *> FunctionArgs = Args; 6590 6591 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6592 FunctionDecl *FD = 6593 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6594 6595 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6596 QualType ObjectType; 6597 Expr::Classification ObjectClassification; 6598 if (Args.size() > 0) { 6599 if (Expr *E = Args[0]) { 6600 // Use the explicit base to restrict the lookup: 6601 ObjectType = E->getType(); 6602 // Pointers in the object arguments are implicitly dereferenced, so we 6603 // always classify them as l-values. 6604 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6605 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6606 else 6607 ObjectClassification = E->Classify(Context); 6608 } // .. else there is an implicit base. 6609 FunctionArgs = Args.slice(1); 6610 } 6611 if (FunTmpl) { 6612 AddMethodTemplateCandidate( 6613 FunTmpl, F.getPair(), 6614 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6615 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6616 FunctionArgs, CandidateSet, SuppressUserConversions, 6617 PartialOverloading); 6618 } else { 6619 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6620 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6621 ObjectClassification, FunctionArgs, CandidateSet, 6622 SuppressUserConversions, PartialOverloading); 6623 } 6624 } else { 6625 // This branch handles both standalone functions and static methods. 6626 6627 // Slice the first argument (which is the base) when we access 6628 // static method as non-static. 6629 if (Args.size() > 0 && 6630 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6631 !isa<CXXConstructorDecl>(FD)))) { 6632 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6633 FunctionArgs = Args.slice(1); 6634 } 6635 if (FunTmpl) { 6636 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6637 ExplicitTemplateArgs, FunctionArgs, 6638 CandidateSet, SuppressUserConversions, 6639 PartialOverloading); 6640 } else { 6641 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6642 SuppressUserConversions, PartialOverloading); 6643 } 6644 } 6645 } 6646 } 6647 6648 /// AddMethodCandidate - Adds a named decl (which is some kind of 6649 /// method) as a method candidate to the given overload set. 6650 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6651 Expr::Classification ObjectClassification, 6652 ArrayRef<Expr *> Args, 6653 OverloadCandidateSet &CandidateSet, 6654 bool SuppressUserConversions, 6655 OverloadCandidateParamOrder PO) { 6656 NamedDecl *Decl = FoundDecl.getDecl(); 6657 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6658 6659 if (isa<UsingShadowDecl>(Decl)) 6660 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6661 6662 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6663 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6664 "Expected a member function template"); 6665 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6666 /*ExplicitArgs*/ nullptr, ObjectType, 6667 ObjectClassification, Args, CandidateSet, 6668 SuppressUserConversions, false, PO); 6669 } else { 6670 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6671 ObjectType, ObjectClassification, Args, CandidateSet, 6672 SuppressUserConversions, false, None, PO); 6673 } 6674 } 6675 6676 /// AddMethodCandidate - Adds the given C++ member function to the set 6677 /// of candidate functions, using the given function call arguments 6678 /// and the object argument (@c Object). For example, in a call 6679 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6680 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6681 /// allow user-defined conversions via constructors or conversion 6682 /// operators. 6683 void 6684 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6685 CXXRecordDecl *ActingContext, QualType ObjectType, 6686 Expr::Classification ObjectClassification, 6687 ArrayRef<Expr *> Args, 6688 OverloadCandidateSet &CandidateSet, 6689 bool SuppressUserConversions, 6690 bool PartialOverloading, 6691 ConversionSequenceList EarlyConversions, 6692 OverloadCandidateParamOrder PO) { 6693 const FunctionProtoType *Proto 6694 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6695 assert(Proto && "Methods without a prototype cannot be overloaded"); 6696 assert(!isa<CXXConstructorDecl>(Method) && 6697 "Use AddOverloadCandidate for constructors"); 6698 6699 if (!CandidateSet.isNewCandidate(Method, PO)) 6700 return; 6701 6702 // C++11 [class.copy]p23: [DR1402] 6703 // A defaulted move assignment operator that is defined as deleted is 6704 // ignored by overload resolution. 6705 if (Method->isDefaulted() && Method->isDeleted() && 6706 Method->isMoveAssignmentOperator()) 6707 return; 6708 6709 // Overload resolution is always an unevaluated context. 6710 EnterExpressionEvaluationContext Unevaluated( 6711 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6712 6713 // Add this candidate 6714 OverloadCandidate &Candidate = 6715 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6716 Candidate.FoundDecl = FoundDecl; 6717 Candidate.Function = Method; 6718 Candidate.RewriteKind = 6719 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6720 Candidate.IsSurrogate = false; 6721 Candidate.IgnoreObjectArgument = false; 6722 Candidate.ExplicitCallArguments = Args.size(); 6723 6724 unsigned NumParams = Proto->getNumParams(); 6725 6726 // (C++ 13.3.2p2): A candidate function having fewer than m 6727 // parameters is viable only if it has an ellipsis in its parameter 6728 // list (8.3.5). 6729 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6730 !Proto->isVariadic()) { 6731 Candidate.Viable = false; 6732 Candidate.FailureKind = ovl_fail_too_many_arguments; 6733 return; 6734 } 6735 6736 // (C++ 13.3.2p2): A candidate function having more than m parameters 6737 // is viable only if the (m+1)st parameter has a default argument 6738 // (8.3.6). For the purposes of overload resolution, the 6739 // parameter list is truncated on the right, so that there are 6740 // exactly m parameters. 6741 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6742 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6743 // Not enough arguments. 6744 Candidate.Viable = false; 6745 Candidate.FailureKind = ovl_fail_too_few_arguments; 6746 return; 6747 } 6748 6749 Candidate.Viable = true; 6750 6751 if (Method->isStatic() || ObjectType.isNull()) 6752 // The implicit object argument is ignored. 6753 Candidate.IgnoreObjectArgument = true; 6754 else { 6755 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6756 // Determine the implicit conversion sequence for the object 6757 // parameter. 6758 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6759 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6760 Method, ActingContext); 6761 if (Candidate.Conversions[ConvIdx].isBad()) { 6762 Candidate.Viable = false; 6763 Candidate.FailureKind = ovl_fail_bad_conversion; 6764 return; 6765 } 6766 } 6767 6768 // (CUDA B.1): Check for invalid calls between targets. 6769 if (getLangOpts().CUDA) 6770 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6771 if (!IsAllowedCUDACall(Caller, Method)) { 6772 Candidate.Viable = false; 6773 Candidate.FailureKind = ovl_fail_bad_target; 6774 return; 6775 } 6776 6777 // Determine the implicit conversion sequences for each of the 6778 // arguments. 6779 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6780 unsigned ConvIdx = 6781 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6782 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6783 // We already formed a conversion sequence for this parameter during 6784 // template argument deduction. 6785 } else if (ArgIdx < NumParams) { 6786 // (C++ 13.3.2p3): for F to be a viable function, there shall 6787 // exist for each argument an implicit conversion sequence 6788 // (13.3.3.1) that converts that argument to the corresponding 6789 // parameter of F. 6790 QualType ParamType = Proto->getParamType(ArgIdx); 6791 Candidate.Conversions[ConvIdx] 6792 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6793 SuppressUserConversions, 6794 /*InOverloadResolution=*/true, 6795 /*AllowObjCWritebackConversion=*/ 6796 getLangOpts().ObjCAutoRefCount); 6797 if (Candidate.Conversions[ConvIdx].isBad()) { 6798 Candidate.Viable = false; 6799 Candidate.FailureKind = ovl_fail_bad_conversion; 6800 return; 6801 } 6802 } else { 6803 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6804 // argument for which there is no corresponding parameter is 6805 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6806 Candidate.Conversions[ConvIdx].setEllipsis(); 6807 } 6808 } 6809 6810 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6811 Candidate.Viable = false; 6812 Candidate.FailureKind = ovl_fail_enable_if; 6813 Candidate.DeductionFailure.Data = FailedAttr; 6814 return; 6815 } 6816 6817 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6818 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6819 Candidate.Viable = false; 6820 Candidate.FailureKind = ovl_non_default_multiversion_function; 6821 } 6822 } 6823 6824 /// Add a C++ member function template as a candidate to the candidate 6825 /// set, using template argument deduction to produce an appropriate member 6826 /// function template specialization. 6827 void Sema::AddMethodTemplateCandidate( 6828 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6829 CXXRecordDecl *ActingContext, 6830 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6831 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6832 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6833 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6834 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6835 return; 6836 6837 // C++ [over.match.funcs]p7: 6838 // In each case where a candidate is a function template, candidate 6839 // function template specializations are generated using template argument 6840 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6841 // candidate functions in the usual way.113) A given name can refer to one 6842 // or more function templates and also to a set of overloaded non-template 6843 // functions. In such a case, the candidate functions generated from each 6844 // function template are combined with the set of non-template candidate 6845 // functions. 6846 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6847 FunctionDecl *Specialization = nullptr; 6848 ConversionSequenceList Conversions; 6849 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6850 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6851 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6852 return CheckNonDependentConversions( 6853 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6854 SuppressUserConversions, ActingContext, ObjectType, 6855 ObjectClassification, PO); 6856 })) { 6857 OverloadCandidate &Candidate = 6858 CandidateSet.addCandidate(Conversions.size(), Conversions); 6859 Candidate.FoundDecl = FoundDecl; 6860 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6861 Candidate.Viable = false; 6862 Candidate.RewriteKind = 6863 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6864 Candidate.IsSurrogate = false; 6865 Candidate.IgnoreObjectArgument = 6866 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6867 ObjectType.isNull(); 6868 Candidate.ExplicitCallArguments = Args.size(); 6869 if (Result == TDK_NonDependentConversionFailure) 6870 Candidate.FailureKind = ovl_fail_bad_conversion; 6871 else { 6872 Candidate.FailureKind = ovl_fail_bad_deduction; 6873 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6874 Info); 6875 } 6876 return; 6877 } 6878 6879 // Add the function template specialization produced by template argument 6880 // deduction as a candidate. 6881 assert(Specialization && "Missing member function template specialization?"); 6882 assert(isa<CXXMethodDecl>(Specialization) && 6883 "Specialization is not a member function?"); 6884 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6885 ActingContext, ObjectType, ObjectClassification, Args, 6886 CandidateSet, SuppressUserConversions, PartialOverloading, 6887 Conversions, PO); 6888 } 6889 6890 /// Add a C++ function template specialization as a candidate 6891 /// in the candidate set, using template argument deduction to produce 6892 /// an appropriate function template specialization. 6893 void Sema::AddTemplateOverloadCandidate( 6894 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6895 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6896 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6897 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6898 OverloadCandidateParamOrder PO) { 6899 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6900 return; 6901 6902 // C++ [over.match.funcs]p7: 6903 // In each case where a candidate is a function template, candidate 6904 // function template specializations are generated using template argument 6905 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6906 // candidate functions in the usual way.113) A given name can refer to one 6907 // or more function templates and also to a set of overloaded non-template 6908 // functions. In such a case, the candidate functions generated from each 6909 // function template are combined with the set of non-template candidate 6910 // functions. 6911 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6912 FunctionDecl *Specialization = nullptr; 6913 ConversionSequenceList Conversions; 6914 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6915 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6916 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6917 return CheckNonDependentConversions( 6918 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6919 SuppressUserConversions, nullptr, QualType(), {}, PO); 6920 })) { 6921 OverloadCandidate &Candidate = 6922 CandidateSet.addCandidate(Conversions.size(), Conversions); 6923 Candidate.FoundDecl = FoundDecl; 6924 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6925 Candidate.Viable = false; 6926 Candidate.RewriteKind = 6927 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6928 Candidate.IsSurrogate = false; 6929 Candidate.IsADLCandidate = IsADLCandidate; 6930 // Ignore the object argument if there is one, since we don't have an object 6931 // type. 6932 Candidate.IgnoreObjectArgument = 6933 isa<CXXMethodDecl>(Candidate.Function) && 6934 !isa<CXXConstructorDecl>(Candidate.Function); 6935 Candidate.ExplicitCallArguments = Args.size(); 6936 if (Result == TDK_NonDependentConversionFailure) 6937 Candidate.FailureKind = ovl_fail_bad_conversion; 6938 else { 6939 Candidate.FailureKind = ovl_fail_bad_deduction; 6940 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6941 Info); 6942 } 6943 return; 6944 } 6945 6946 // Add the function template specialization produced by template argument 6947 // deduction as a candidate. 6948 assert(Specialization && "Missing function template specialization?"); 6949 AddOverloadCandidate( 6950 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6951 PartialOverloading, AllowExplicit, 6952 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 6953 } 6954 6955 /// Check that implicit conversion sequences can be formed for each argument 6956 /// whose corresponding parameter has a non-dependent type, per DR1391's 6957 /// [temp.deduct.call]p10. 6958 bool Sema::CheckNonDependentConversions( 6959 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6960 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6961 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6962 CXXRecordDecl *ActingContext, QualType ObjectType, 6963 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 6964 // FIXME: The cases in which we allow explicit conversions for constructor 6965 // arguments never consider calling a constructor template. It's not clear 6966 // that is correct. 6967 const bool AllowExplicit = false; 6968 6969 auto *FD = FunctionTemplate->getTemplatedDecl(); 6970 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6971 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6972 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6973 6974 Conversions = 6975 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6976 6977 // Overload resolution is always an unevaluated context. 6978 EnterExpressionEvaluationContext Unevaluated( 6979 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6980 6981 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6982 // require that, but this check should never result in a hard error, and 6983 // overload resolution is permitted to sidestep instantiations. 6984 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6985 !ObjectType.isNull()) { 6986 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6987 Conversions[ConvIdx] = TryObjectArgumentInitialization( 6988 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6989 Method, ActingContext); 6990 if (Conversions[ConvIdx].isBad()) 6991 return true; 6992 } 6993 6994 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6995 ++I) { 6996 QualType ParamType = ParamTypes[I]; 6997 if (!ParamType->isDependentType()) { 6998 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 6999 ? 0 7000 : (ThisConversions + I); 7001 Conversions[ConvIdx] 7002 = TryCopyInitialization(*this, Args[I], ParamType, 7003 SuppressUserConversions, 7004 /*InOverloadResolution=*/true, 7005 /*AllowObjCWritebackConversion=*/ 7006 getLangOpts().ObjCAutoRefCount, 7007 AllowExplicit); 7008 if (Conversions[ConvIdx].isBad()) 7009 return true; 7010 } 7011 } 7012 7013 return false; 7014 } 7015 7016 /// Determine whether this is an allowable conversion from the result 7017 /// of an explicit conversion operator to the expected type, per C++ 7018 /// [over.match.conv]p1 and [over.match.ref]p1. 7019 /// 7020 /// \param ConvType The return type of the conversion function. 7021 /// 7022 /// \param ToType The type we are converting to. 7023 /// 7024 /// \param AllowObjCPointerConversion Allow a conversion from one 7025 /// Objective-C pointer to another. 7026 /// 7027 /// \returns true if the conversion is allowable, false otherwise. 7028 static bool isAllowableExplicitConversion(Sema &S, 7029 QualType ConvType, QualType ToType, 7030 bool AllowObjCPointerConversion) { 7031 QualType ToNonRefType = ToType.getNonReferenceType(); 7032 7033 // Easy case: the types are the same. 7034 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7035 return true; 7036 7037 // Allow qualification conversions. 7038 bool ObjCLifetimeConversion; 7039 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7040 ObjCLifetimeConversion)) 7041 return true; 7042 7043 // If we're not allowed to consider Objective-C pointer conversions, 7044 // we're done. 7045 if (!AllowObjCPointerConversion) 7046 return false; 7047 7048 // Is this an Objective-C pointer conversion? 7049 bool IncompatibleObjC = false; 7050 QualType ConvertedType; 7051 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7052 IncompatibleObjC); 7053 } 7054 7055 /// AddConversionCandidate - Add a C++ conversion function as a 7056 /// candidate in the candidate set (C++ [over.match.conv], 7057 /// C++ [over.match.copy]). From is the expression we're converting from, 7058 /// and ToType is the type that we're eventually trying to convert to 7059 /// (which may or may not be the same type as the type that the 7060 /// conversion function produces). 7061 void Sema::AddConversionCandidate( 7062 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7063 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7064 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7065 bool AllowExplicit, bool AllowResultConversion) { 7066 assert(!Conversion->getDescribedFunctionTemplate() && 7067 "Conversion function templates use AddTemplateConversionCandidate"); 7068 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7069 if (!CandidateSet.isNewCandidate(Conversion)) 7070 return; 7071 7072 // If the conversion function has an undeduced return type, trigger its 7073 // deduction now. 7074 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7075 if (DeduceReturnType(Conversion, From->getExprLoc())) 7076 return; 7077 ConvType = Conversion->getConversionType().getNonReferenceType(); 7078 } 7079 7080 // If we don't allow any conversion of the result type, ignore conversion 7081 // functions that don't convert to exactly (possibly cv-qualified) T. 7082 if (!AllowResultConversion && 7083 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7084 return; 7085 7086 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7087 // operator is only a candidate if its return type is the target type or 7088 // can be converted to the target type with a qualification conversion. 7089 if (Conversion->isExplicit() && 7090 !isAllowableExplicitConversion(*this, ConvType, ToType, 7091 AllowObjCConversionOnExplicit)) 7092 return; 7093 7094 // Overload resolution is always an unevaluated context. 7095 EnterExpressionEvaluationContext Unevaluated( 7096 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7097 7098 // Add this candidate 7099 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7100 Candidate.FoundDecl = FoundDecl; 7101 Candidate.Function = Conversion; 7102 Candidate.IsSurrogate = false; 7103 Candidate.IgnoreObjectArgument = false; 7104 Candidate.FinalConversion.setAsIdentityConversion(); 7105 Candidate.FinalConversion.setFromType(ConvType); 7106 Candidate.FinalConversion.setAllToTypes(ToType); 7107 Candidate.Viable = true; 7108 Candidate.ExplicitCallArguments = 1; 7109 7110 // C++ [over.match.funcs]p4: 7111 // For conversion functions, the function is considered to be a member of 7112 // the class of the implicit implied object argument for the purpose of 7113 // defining the type of the implicit object parameter. 7114 // 7115 // Determine the implicit conversion sequence for the implicit 7116 // object parameter. 7117 QualType ImplicitParamType = From->getType(); 7118 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7119 ImplicitParamType = FromPtrType->getPointeeType(); 7120 CXXRecordDecl *ConversionContext 7121 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7122 7123 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7124 *this, CandidateSet.getLocation(), From->getType(), 7125 From->Classify(Context), Conversion, ConversionContext); 7126 7127 if (Candidate.Conversions[0].isBad()) { 7128 Candidate.Viable = false; 7129 Candidate.FailureKind = ovl_fail_bad_conversion; 7130 return; 7131 } 7132 7133 // We won't go through a user-defined type conversion function to convert a 7134 // derived to base as such conversions are given Conversion Rank. They only 7135 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7136 QualType FromCanon 7137 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7138 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7139 if (FromCanon == ToCanon || 7140 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7141 Candidate.Viable = false; 7142 Candidate.FailureKind = ovl_fail_trivial_conversion; 7143 return; 7144 } 7145 7146 // To determine what the conversion from the result of calling the 7147 // conversion function to the type we're eventually trying to 7148 // convert to (ToType), we need to synthesize a call to the 7149 // conversion function and attempt copy initialization from it. This 7150 // makes sure that we get the right semantics with respect to 7151 // lvalues/rvalues and the type. Fortunately, we can allocate this 7152 // call on the stack and we don't need its arguments to be 7153 // well-formed. 7154 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7155 VK_LValue, From->getBeginLoc()); 7156 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7157 Context.getPointerType(Conversion->getType()), 7158 CK_FunctionToPointerDecay, 7159 &ConversionRef, VK_RValue); 7160 7161 QualType ConversionType = Conversion->getConversionType(); 7162 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7163 Candidate.Viable = false; 7164 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7165 return; 7166 } 7167 7168 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7169 7170 // Note that it is safe to allocate CallExpr on the stack here because 7171 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7172 // allocator). 7173 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7174 7175 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7176 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7177 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7178 7179 ImplicitConversionSequence ICS = 7180 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7181 /*SuppressUserConversions=*/true, 7182 /*InOverloadResolution=*/false, 7183 /*AllowObjCWritebackConversion=*/false); 7184 7185 switch (ICS.getKind()) { 7186 case ImplicitConversionSequence::StandardConversion: 7187 Candidate.FinalConversion = ICS.Standard; 7188 7189 // C++ [over.ics.user]p3: 7190 // If the user-defined conversion is specified by a specialization of a 7191 // conversion function template, the second standard conversion sequence 7192 // shall have exact match rank. 7193 if (Conversion->getPrimaryTemplate() && 7194 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7195 Candidate.Viable = false; 7196 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7197 return; 7198 } 7199 7200 // C++0x [dcl.init.ref]p5: 7201 // In the second case, if the reference is an rvalue reference and 7202 // the second standard conversion sequence of the user-defined 7203 // conversion sequence includes an lvalue-to-rvalue conversion, the 7204 // program is ill-formed. 7205 if (ToType->isRValueReferenceType() && 7206 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7207 Candidate.Viable = false; 7208 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7209 return; 7210 } 7211 break; 7212 7213 case ImplicitConversionSequence::BadConversion: 7214 Candidate.Viable = false; 7215 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7216 return; 7217 7218 default: 7219 llvm_unreachable( 7220 "Can only end up with a standard conversion sequence or failure"); 7221 } 7222 7223 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7224 ExplicitSpecKind::ResolvedFalse) { 7225 Candidate.Viable = false; 7226 Candidate.FailureKind = ovl_fail_explicit_resolved; 7227 return; 7228 } 7229 7230 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7231 Candidate.Viable = false; 7232 Candidate.FailureKind = ovl_fail_enable_if; 7233 Candidate.DeductionFailure.Data = FailedAttr; 7234 return; 7235 } 7236 7237 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7238 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7239 Candidate.Viable = false; 7240 Candidate.FailureKind = ovl_non_default_multiversion_function; 7241 } 7242 } 7243 7244 /// Adds a conversion function template specialization 7245 /// candidate to the overload set, using template argument deduction 7246 /// to deduce the template arguments of the conversion function 7247 /// template from the type that we are converting to (C++ 7248 /// [temp.deduct.conv]). 7249 void Sema::AddTemplateConversionCandidate( 7250 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7251 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7252 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7253 bool AllowExplicit, bool AllowResultConversion) { 7254 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7255 "Only conversion function templates permitted here"); 7256 7257 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7258 return; 7259 7260 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7261 CXXConversionDecl *Specialization = nullptr; 7262 if (TemplateDeductionResult Result 7263 = DeduceTemplateArguments(FunctionTemplate, ToType, 7264 Specialization, Info)) { 7265 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7266 Candidate.FoundDecl = FoundDecl; 7267 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7268 Candidate.Viable = false; 7269 Candidate.FailureKind = ovl_fail_bad_deduction; 7270 Candidate.IsSurrogate = false; 7271 Candidate.IgnoreObjectArgument = false; 7272 Candidate.ExplicitCallArguments = 1; 7273 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7274 Info); 7275 return; 7276 } 7277 7278 // Add the conversion function template specialization produced by 7279 // template argument deduction as a candidate. 7280 assert(Specialization && "Missing function template specialization?"); 7281 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7282 CandidateSet, AllowObjCConversionOnExplicit, 7283 AllowExplicit, AllowResultConversion); 7284 } 7285 7286 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7287 /// converts the given @c Object to a function pointer via the 7288 /// conversion function @c Conversion, and then attempts to call it 7289 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7290 /// the type of function that we'll eventually be calling. 7291 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7292 DeclAccessPair FoundDecl, 7293 CXXRecordDecl *ActingContext, 7294 const FunctionProtoType *Proto, 7295 Expr *Object, 7296 ArrayRef<Expr *> Args, 7297 OverloadCandidateSet& CandidateSet) { 7298 if (!CandidateSet.isNewCandidate(Conversion)) 7299 return; 7300 7301 // Overload resolution is always an unevaluated context. 7302 EnterExpressionEvaluationContext Unevaluated( 7303 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7304 7305 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7306 Candidate.FoundDecl = FoundDecl; 7307 Candidate.Function = nullptr; 7308 Candidate.Surrogate = Conversion; 7309 Candidate.Viable = true; 7310 Candidate.IsSurrogate = true; 7311 Candidate.IgnoreObjectArgument = false; 7312 Candidate.ExplicitCallArguments = Args.size(); 7313 7314 // Determine the implicit conversion sequence for the implicit 7315 // object parameter. 7316 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7317 *this, CandidateSet.getLocation(), Object->getType(), 7318 Object->Classify(Context), Conversion, ActingContext); 7319 if (ObjectInit.isBad()) { 7320 Candidate.Viable = false; 7321 Candidate.FailureKind = ovl_fail_bad_conversion; 7322 Candidate.Conversions[0] = ObjectInit; 7323 return; 7324 } 7325 7326 // The first conversion is actually a user-defined conversion whose 7327 // first conversion is ObjectInit's standard conversion (which is 7328 // effectively a reference binding). Record it as such. 7329 Candidate.Conversions[0].setUserDefined(); 7330 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7331 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7332 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7333 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7334 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7335 Candidate.Conversions[0].UserDefined.After 7336 = Candidate.Conversions[0].UserDefined.Before; 7337 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7338 7339 // Find the 7340 unsigned NumParams = Proto->getNumParams(); 7341 7342 // (C++ 13.3.2p2): A candidate function having fewer than m 7343 // parameters is viable only if it has an ellipsis in its parameter 7344 // list (8.3.5). 7345 if (Args.size() > NumParams && !Proto->isVariadic()) { 7346 Candidate.Viable = false; 7347 Candidate.FailureKind = ovl_fail_too_many_arguments; 7348 return; 7349 } 7350 7351 // Function types don't have any default arguments, so just check if 7352 // we have enough arguments. 7353 if (Args.size() < NumParams) { 7354 // Not enough arguments. 7355 Candidate.Viable = false; 7356 Candidate.FailureKind = ovl_fail_too_few_arguments; 7357 return; 7358 } 7359 7360 // Determine the implicit conversion sequences for each of the 7361 // arguments. 7362 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7363 if (ArgIdx < NumParams) { 7364 // (C++ 13.3.2p3): for F to be a viable function, there shall 7365 // exist for each argument an implicit conversion sequence 7366 // (13.3.3.1) that converts that argument to the corresponding 7367 // parameter of F. 7368 QualType ParamType = Proto->getParamType(ArgIdx); 7369 Candidate.Conversions[ArgIdx + 1] 7370 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7371 /*SuppressUserConversions=*/false, 7372 /*InOverloadResolution=*/false, 7373 /*AllowObjCWritebackConversion=*/ 7374 getLangOpts().ObjCAutoRefCount); 7375 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7376 Candidate.Viable = false; 7377 Candidate.FailureKind = ovl_fail_bad_conversion; 7378 return; 7379 } 7380 } else { 7381 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7382 // argument for which there is no corresponding parameter is 7383 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7384 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7385 } 7386 } 7387 7388 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7389 Candidate.Viable = false; 7390 Candidate.FailureKind = ovl_fail_enable_if; 7391 Candidate.DeductionFailure.Data = FailedAttr; 7392 return; 7393 } 7394 } 7395 7396 /// Add all of the non-member operator function declarations in the given 7397 /// function set to the overload candidate set. 7398 void Sema::AddNonMemberOperatorCandidates( 7399 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7400 OverloadCandidateSet &CandidateSet, 7401 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7402 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7403 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7404 ArrayRef<Expr *> FunctionArgs = Args; 7405 7406 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7407 FunctionDecl *FD = 7408 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7409 7410 // Don't consider rewritten functions if we're not rewriting. 7411 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7412 continue; 7413 7414 assert(!isa<CXXMethodDecl>(FD) && 7415 "unqualified operator lookup found a member function"); 7416 7417 if (FunTmpl) { 7418 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7419 FunctionArgs, CandidateSet); 7420 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7421 AddTemplateOverloadCandidate( 7422 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7423 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7424 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7425 } else { 7426 if (ExplicitTemplateArgs) 7427 continue; 7428 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7429 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7430 AddOverloadCandidate(FD, F.getPair(), 7431 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7432 false, false, true, false, ADLCallKind::NotADL, 7433 None, OverloadCandidateParamOrder::Reversed); 7434 } 7435 } 7436 } 7437 7438 /// Add overload candidates for overloaded operators that are 7439 /// member functions. 7440 /// 7441 /// Add the overloaded operator candidates that are member functions 7442 /// for the operator Op that was used in an operator expression such 7443 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7444 /// CandidateSet will store the added overload candidates. (C++ 7445 /// [over.match.oper]). 7446 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7447 SourceLocation OpLoc, 7448 ArrayRef<Expr *> Args, 7449 OverloadCandidateSet &CandidateSet, 7450 OverloadCandidateParamOrder PO) { 7451 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7452 7453 // C++ [over.match.oper]p3: 7454 // For a unary operator @ with an operand of a type whose 7455 // cv-unqualified version is T1, and for a binary operator @ with 7456 // a left operand of a type whose cv-unqualified version is T1 and 7457 // a right operand of a type whose cv-unqualified version is T2, 7458 // three sets of candidate functions, designated member 7459 // candidates, non-member candidates and built-in candidates, are 7460 // constructed as follows: 7461 QualType T1 = Args[0]->getType(); 7462 7463 // -- If T1 is a complete class type or a class currently being 7464 // defined, the set of member candidates is the result of the 7465 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7466 // the set of member candidates is empty. 7467 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7468 // Complete the type if it can be completed. 7469 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7470 return; 7471 // If the type is neither complete nor being defined, bail out now. 7472 if (!T1Rec->getDecl()->getDefinition()) 7473 return; 7474 7475 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7476 LookupQualifiedName(Operators, T1Rec->getDecl()); 7477 Operators.suppressDiagnostics(); 7478 7479 for (LookupResult::iterator Oper = Operators.begin(), 7480 OperEnd = Operators.end(); 7481 Oper != OperEnd; 7482 ++Oper) 7483 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7484 Args[0]->Classify(Context), Args.slice(1), 7485 CandidateSet, /*SuppressUserConversion=*/false, PO); 7486 } 7487 } 7488 7489 /// AddBuiltinCandidate - Add a candidate for a built-in 7490 /// operator. ResultTy and ParamTys are the result and parameter types 7491 /// of the built-in candidate, respectively. Args and NumArgs are the 7492 /// arguments being passed to the candidate. IsAssignmentOperator 7493 /// should be true when this built-in candidate is an assignment 7494 /// operator. NumContextualBoolArguments is the number of arguments 7495 /// (at the beginning of the argument list) that will be contextually 7496 /// converted to bool. 7497 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7498 OverloadCandidateSet& CandidateSet, 7499 bool IsAssignmentOperator, 7500 unsigned NumContextualBoolArguments) { 7501 // Overload resolution is always an unevaluated context. 7502 EnterExpressionEvaluationContext Unevaluated( 7503 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7504 7505 // Add this candidate 7506 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7507 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7508 Candidate.Function = nullptr; 7509 Candidate.IsSurrogate = false; 7510 Candidate.IgnoreObjectArgument = false; 7511 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7512 7513 // Determine the implicit conversion sequences for each of the 7514 // arguments. 7515 Candidate.Viable = true; 7516 Candidate.ExplicitCallArguments = Args.size(); 7517 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7518 // C++ [over.match.oper]p4: 7519 // For the built-in assignment operators, conversions of the 7520 // left operand are restricted as follows: 7521 // -- no temporaries are introduced to hold the left operand, and 7522 // -- no user-defined conversions are applied to the left 7523 // operand to achieve a type match with the left-most 7524 // parameter of a built-in candidate. 7525 // 7526 // We block these conversions by turning off user-defined 7527 // conversions, since that is the only way that initialization of 7528 // a reference to a non-class type can occur from something that 7529 // is not of the same type. 7530 if (ArgIdx < NumContextualBoolArguments) { 7531 assert(ParamTys[ArgIdx] == Context.BoolTy && 7532 "Contextual conversion to bool requires bool type"); 7533 Candidate.Conversions[ArgIdx] 7534 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7535 } else { 7536 Candidate.Conversions[ArgIdx] 7537 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7538 ArgIdx == 0 && IsAssignmentOperator, 7539 /*InOverloadResolution=*/false, 7540 /*AllowObjCWritebackConversion=*/ 7541 getLangOpts().ObjCAutoRefCount); 7542 } 7543 if (Candidate.Conversions[ArgIdx].isBad()) { 7544 Candidate.Viable = false; 7545 Candidate.FailureKind = ovl_fail_bad_conversion; 7546 break; 7547 } 7548 } 7549 } 7550 7551 namespace { 7552 7553 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7554 /// candidate operator functions for built-in operators (C++ 7555 /// [over.built]). The types are separated into pointer types and 7556 /// enumeration types. 7557 class BuiltinCandidateTypeSet { 7558 /// TypeSet - A set of types. 7559 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7560 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7561 7562 /// PointerTypes - The set of pointer types that will be used in the 7563 /// built-in candidates. 7564 TypeSet PointerTypes; 7565 7566 /// MemberPointerTypes - The set of member pointer types that will be 7567 /// used in the built-in candidates. 7568 TypeSet MemberPointerTypes; 7569 7570 /// EnumerationTypes - The set of enumeration types that will be 7571 /// used in the built-in candidates. 7572 TypeSet EnumerationTypes; 7573 7574 /// The set of vector types that will be used in the built-in 7575 /// candidates. 7576 TypeSet VectorTypes; 7577 7578 /// A flag indicating non-record types are viable candidates 7579 bool HasNonRecordTypes; 7580 7581 /// A flag indicating whether either arithmetic or enumeration types 7582 /// were present in the candidate set. 7583 bool HasArithmeticOrEnumeralTypes; 7584 7585 /// A flag indicating whether the nullptr type was present in the 7586 /// candidate set. 7587 bool HasNullPtrType; 7588 7589 /// Sema - The semantic analysis instance where we are building the 7590 /// candidate type set. 7591 Sema &SemaRef; 7592 7593 /// Context - The AST context in which we will build the type sets. 7594 ASTContext &Context; 7595 7596 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7597 const Qualifiers &VisibleQuals); 7598 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7599 7600 public: 7601 /// iterator - Iterates through the types that are part of the set. 7602 typedef TypeSet::iterator iterator; 7603 7604 BuiltinCandidateTypeSet(Sema &SemaRef) 7605 : HasNonRecordTypes(false), 7606 HasArithmeticOrEnumeralTypes(false), 7607 HasNullPtrType(false), 7608 SemaRef(SemaRef), 7609 Context(SemaRef.Context) { } 7610 7611 void AddTypesConvertedFrom(QualType Ty, 7612 SourceLocation Loc, 7613 bool AllowUserConversions, 7614 bool AllowExplicitConversions, 7615 const Qualifiers &VisibleTypeConversionsQuals); 7616 7617 /// pointer_begin - First pointer type found; 7618 iterator pointer_begin() { return PointerTypes.begin(); } 7619 7620 /// pointer_end - Past the last pointer type found; 7621 iterator pointer_end() { return PointerTypes.end(); } 7622 7623 /// member_pointer_begin - First member pointer type found; 7624 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7625 7626 /// member_pointer_end - Past the last member pointer type found; 7627 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7628 7629 /// enumeration_begin - First enumeration type found; 7630 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7631 7632 /// enumeration_end - Past the last enumeration type found; 7633 iterator enumeration_end() { return EnumerationTypes.end(); } 7634 7635 iterator vector_begin() { return VectorTypes.begin(); } 7636 iterator vector_end() { return VectorTypes.end(); } 7637 7638 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7639 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7640 bool hasNullPtrType() const { return HasNullPtrType; } 7641 }; 7642 7643 } // end anonymous namespace 7644 7645 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7646 /// the set of pointer types along with any more-qualified variants of 7647 /// that type. For example, if @p Ty is "int const *", this routine 7648 /// will add "int const *", "int const volatile *", "int const 7649 /// restrict *", and "int const volatile restrict *" to the set of 7650 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7651 /// false otherwise. 7652 /// 7653 /// FIXME: what to do about extended qualifiers? 7654 bool 7655 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7656 const Qualifiers &VisibleQuals) { 7657 7658 // Insert this type. 7659 if (!PointerTypes.insert(Ty)) 7660 return false; 7661 7662 QualType PointeeTy; 7663 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7664 bool buildObjCPtr = false; 7665 if (!PointerTy) { 7666 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7667 PointeeTy = PTy->getPointeeType(); 7668 buildObjCPtr = true; 7669 } else { 7670 PointeeTy = PointerTy->getPointeeType(); 7671 } 7672 7673 // Don't add qualified variants of arrays. For one, they're not allowed 7674 // (the qualifier would sink to the element type), and for another, the 7675 // only overload situation where it matters is subscript or pointer +- int, 7676 // and those shouldn't have qualifier variants anyway. 7677 if (PointeeTy->isArrayType()) 7678 return true; 7679 7680 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7681 bool hasVolatile = VisibleQuals.hasVolatile(); 7682 bool hasRestrict = VisibleQuals.hasRestrict(); 7683 7684 // Iterate through all strict supersets of BaseCVR. 7685 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7686 if ((CVR | BaseCVR) != CVR) continue; 7687 // Skip over volatile if no volatile found anywhere in the types. 7688 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7689 7690 // Skip over restrict if no restrict found anywhere in the types, or if 7691 // the type cannot be restrict-qualified. 7692 if ((CVR & Qualifiers::Restrict) && 7693 (!hasRestrict || 7694 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7695 continue; 7696 7697 // Build qualified pointee type. 7698 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7699 7700 // Build qualified pointer type. 7701 QualType QPointerTy; 7702 if (!buildObjCPtr) 7703 QPointerTy = Context.getPointerType(QPointeeTy); 7704 else 7705 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7706 7707 // Insert qualified pointer type. 7708 PointerTypes.insert(QPointerTy); 7709 } 7710 7711 return true; 7712 } 7713 7714 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7715 /// to the set of pointer types along with any more-qualified variants of 7716 /// that type. For example, if @p Ty is "int const *", this routine 7717 /// will add "int const *", "int const volatile *", "int const 7718 /// restrict *", and "int const volatile restrict *" to the set of 7719 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7720 /// false otherwise. 7721 /// 7722 /// FIXME: what to do about extended qualifiers? 7723 bool 7724 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7725 QualType Ty) { 7726 // Insert this type. 7727 if (!MemberPointerTypes.insert(Ty)) 7728 return false; 7729 7730 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7731 assert(PointerTy && "type was not a member pointer type!"); 7732 7733 QualType PointeeTy = PointerTy->getPointeeType(); 7734 // Don't add qualified variants of arrays. For one, they're not allowed 7735 // (the qualifier would sink to the element type), and for another, the 7736 // only overload situation where it matters is subscript or pointer +- int, 7737 // and those shouldn't have qualifier variants anyway. 7738 if (PointeeTy->isArrayType()) 7739 return true; 7740 const Type *ClassTy = PointerTy->getClass(); 7741 7742 // Iterate through all strict supersets of the pointee type's CVR 7743 // qualifiers. 7744 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7745 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7746 if ((CVR | BaseCVR) != CVR) continue; 7747 7748 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7749 MemberPointerTypes.insert( 7750 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7751 } 7752 7753 return true; 7754 } 7755 7756 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7757 /// Ty can be implicit converted to the given set of @p Types. We're 7758 /// primarily interested in pointer types and enumeration types. We also 7759 /// take member pointer types, for the conditional operator. 7760 /// AllowUserConversions is true if we should look at the conversion 7761 /// functions of a class type, and AllowExplicitConversions if we 7762 /// should also include the explicit conversion functions of a class 7763 /// type. 7764 void 7765 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7766 SourceLocation Loc, 7767 bool AllowUserConversions, 7768 bool AllowExplicitConversions, 7769 const Qualifiers &VisibleQuals) { 7770 // Only deal with canonical types. 7771 Ty = Context.getCanonicalType(Ty); 7772 7773 // Look through reference types; they aren't part of the type of an 7774 // expression for the purposes of conversions. 7775 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7776 Ty = RefTy->getPointeeType(); 7777 7778 // If we're dealing with an array type, decay to the pointer. 7779 if (Ty->isArrayType()) 7780 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7781 7782 // Otherwise, we don't care about qualifiers on the type. 7783 Ty = Ty.getLocalUnqualifiedType(); 7784 7785 // Flag if we ever add a non-record type. 7786 const RecordType *TyRec = Ty->getAs<RecordType>(); 7787 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7788 7789 // Flag if we encounter an arithmetic type. 7790 HasArithmeticOrEnumeralTypes = 7791 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7792 7793 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7794 PointerTypes.insert(Ty); 7795 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7796 // Insert our type, and its more-qualified variants, into the set 7797 // of types. 7798 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7799 return; 7800 } else if (Ty->isMemberPointerType()) { 7801 // Member pointers are far easier, since the pointee can't be converted. 7802 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7803 return; 7804 } else if (Ty->isEnumeralType()) { 7805 HasArithmeticOrEnumeralTypes = true; 7806 EnumerationTypes.insert(Ty); 7807 } else if (Ty->isVectorType()) { 7808 // We treat vector types as arithmetic types in many contexts as an 7809 // extension. 7810 HasArithmeticOrEnumeralTypes = true; 7811 VectorTypes.insert(Ty); 7812 } else if (Ty->isNullPtrType()) { 7813 HasNullPtrType = true; 7814 } else if (AllowUserConversions && TyRec) { 7815 // No conversion functions in incomplete types. 7816 if (!SemaRef.isCompleteType(Loc, Ty)) 7817 return; 7818 7819 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7820 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7821 if (isa<UsingShadowDecl>(D)) 7822 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7823 7824 // Skip conversion function templates; they don't tell us anything 7825 // about which builtin types we can convert to. 7826 if (isa<FunctionTemplateDecl>(D)) 7827 continue; 7828 7829 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7830 if (AllowExplicitConversions || !Conv->isExplicit()) { 7831 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7832 VisibleQuals); 7833 } 7834 } 7835 } 7836 } 7837 /// Helper function for adjusting address spaces for the pointer or reference 7838 /// operands of builtin operators depending on the argument. 7839 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7840 Expr *Arg) { 7841 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7842 } 7843 7844 /// Helper function for AddBuiltinOperatorCandidates() that adds 7845 /// the volatile- and non-volatile-qualified assignment operators for the 7846 /// given type to the candidate set. 7847 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7848 QualType T, 7849 ArrayRef<Expr *> Args, 7850 OverloadCandidateSet &CandidateSet) { 7851 QualType ParamTypes[2]; 7852 7853 // T& operator=(T&, T) 7854 ParamTypes[0] = S.Context.getLValueReferenceType( 7855 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7856 ParamTypes[1] = T; 7857 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7858 /*IsAssignmentOperator=*/true); 7859 7860 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7861 // volatile T& operator=(volatile T&, T) 7862 ParamTypes[0] = S.Context.getLValueReferenceType( 7863 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7864 Args[0])); 7865 ParamTypes[1] = T; 7866 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7867 /*IsAssignmentOperator=*/true); 7868 } 7869 } 7870 7871 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7872 /// if any, found in visible type conversion functions found in ArgExpr's type. 7873 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7874 Qualifiers VRQuals; 7875 const RecordType *TyRec; 7876 if (const MemberPointerType *RHSMPType = 7877 ArgExpr->getType()->getAs<MemberPointerType>()) 7878 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7879 else 7880 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7881 if (!TyRec) { 7882 // Just to be safe, assume the worst case. 7883 VRQuals.addVolatile(); 7884 VRQuals.addRestrict(); 7885 return VRQuals; 7886 } 7887 7888 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7889 if (!ClassDecl->hasDefinition()) 7890 return VRQuals; 7891 7892 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7893 if (isa<UsingShadowDecl>(D)) 7894 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7895 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7896 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7897 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7898 CanTy = ResTypeRef->getPointeeType(); 7899 // Need to go down the pointer/mempointer chain and add qualifiers 7900 // as see them. 7901 bool done = false; 7902 while (!done) { 7903 if (CanTy.isRestrictQualified()) 7904 VRQuals.addRestrict(); 7905 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7906 CanTy = ResTypePtr->getPointeeType(); 7907 else if (const MemberPointerType *ResTypeMPtr = 7908 CanTy->getAs<MemberPointerType>()) 7909 CanTy = ResTypeMPtr->getPointeeType(); 7910 else 7911 done = true; 7912 if (CanTy.isVolatileQualified()) 7913 VRQuals.addVolatile(); 7914 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7915 return VRQuals; 7916 } 7917 } 7918 } 7919 return VRQuals; 7920 } 7921 7922 namespace { 7923 7924 /// Helper class to manage the addition of builtin operator overload 7925 /// candidates. It provides shared state and utility methods used throughout 7926 /// the process, as well as a helper method to add each group of builtin 7927 /// operator overloads from the standard to a candidate set. 7928 class BuiltinOperatorOverloadBuilder { 7929 // Common instance state available to all overload candidate addition methods. 7930 Sema &S; 7931 ArrayRef<Expr *> Args; 7932 Qualifiers VisibleTypeConversionsQuals; 7933 bool HasArithmeticOrEnumeralCandidateType; 7934 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7935 OverloadCandidateSet &CandidateSet; 7936 7937 static constexpr int ArithmeticTypesCap = 24; 7938 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7939 7940 // Define some indices used to iterate over the arithmetic types in 7941 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7942 // types are that preserved by promotion (C++ [over.built]p2). 7943 unsigned FirstIntegralType, 7944 LastIntegralType; 7945 unsigned FirstPromotedIntegralType, 7946 LastPromotedIntegralType; 7947 unsigned FirstPromotedArithmeticType, 7948 LastPromotedArithmeticType; 7949 unsigned NumArithmeticTypes; 7950 7951 void InitArithmeticTypes() { 7952 // Start of promoted types. 7953 FirstPromotedArithmeticType = 0; 7954 ArithmeticTypes.push_back(S.Context.FloatTy); 7955 ArithmeticTypes.push_back(S.Context.DoubleTy); 7956 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7957 if (S.Context.getTargetInfo().hasFloat128Type()) 7958 ArithmeticTypes.push_back(S.Context.Float128Ty); 7959 7960 // Start of integral types. 7961 FirstIntegralType = ArithmeticTypes.size(); 7962 FirstPromotedIntegralType = ArithmeticTypes.size(); 7963 ArithmeticTypes.push_back(S.Context.IntTy); 7964 ArithmeticTypes.push_back(S.Context.LongTy); 7965 ArithmeticTypes.push_back(S.Context.LongLongTy); 7966 if (S.Context.getTargetInfo().hasInt128Type()) 7967 ArithmeticTypes.push_back(S.Context.Int128Ty); 7968 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7969 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7970 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7971 if (S.Context.getTargetInfo().hasInt128Type()) 7972 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7973 LastPromotedIntegralType = ArithmeticTypes.size(); 7974 LastPromotedArithmeticType = ArithmeticTypes.size(); 7975 // End of promoted types. 7976 7977 ArithmeticTypes.push_back(S.Context.BoolTy); 7978 ArithmeticTypes.push_back(S.Context.CharTy); 7979 ArithmeticTypes.push_back(S.Context.WCharTy); 7980 if (S.Context.getLangOpts().Char8) 7981 ArithmeticTypes.push_back(S.Context.Char8Ty); 7982 ArithmeticTypes.push_back(S.Context.Char16Ty); 7983 ArithmeticTypes.push_back(S.Context.Char32Ty); 7984 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7985 ArithmeticTypes.push_back(S.Context.ShortTy); 7986 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7987 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7988 LastIntegralType = ArithmeticTypes.size(); 7989 NumArithmeticTypes = ArithmeticTypes.size(); 7990 // End of integral types. 7991 // FIXME: What about complex? What about half? 7992 7993 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7994 "Enough inline storage for all arithmetic types."); 7995 } 7996 7997 /// Helper method to factor out the common pattern of adding overloads 7998 /// for '++' and '--' builtin operators. 7999 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8000 bool HasVolatile, 8001 bool HasRestrict) { 8002 QualType ParamTypes[2] = { 8003 S.Context.getLValueReferenceType(CandidateTy), 8004 S.Context.IntTy 8005 }; 8006 8007 // Non-volatile version. 8008 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8009 8010 // Use a heuristic to reduce number of builtin candidates in the set: 8011 // add volatile version only if there are conversions to a volatile type. 8012 if (HasVolatile) { 8013 ParamTypes[0] = 8014 S.Context.getLValueReferenceType( 8015 S.Context.getVolatileType(CandidateTy)); 8016 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8017 } 8018 8019 // Add restrict version only if there are conversions to a restrict type 8020 // and our candidate type is a non-restrict-qualified pointer. 8021 if (HasRestrict && CandidateTy->isAnyPointerType() && 8022 !CandidateTy.isRestrictQualified()) { 8023 ParamTypes[0] 8024 = S.Context.getLValueReferenceType( 8025 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8026 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8027 8028 if (HasVolatile) { 8029 ParamTypes[0] 8030 = S.Context.getLValueReferenceType( 8031 S.Context.getCVRQualifiedType(CandidateTy, 8032 (Qualifiers::Volatile | 8033 Qualifiers::Restrict))); 8034 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8035 } 8036 } 8037 8038 } 8039 8040 public: 8041 BuiltinOperatorOverloadBuilder( 8042 Sema &S, ArrayRef<Expr *> Args, 8043 Qualifiers VisibleTypeConversionsQuals, 8044 bool HasArithmeticOrEnumeralCandidateType, 8045 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8046 OverloadCandidateSet &CandidateSet) 8047 : S(S), Args(Args), 8048 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8049 HasArithmeticOrEnumeralCandidateType( 8050 HasArithmeticOrEnumeralCandidateType), 8051 CandidateTypes(CandidateTypes), 8052 CandidateSet(CandidateSet) { 8053 8054 InitArithmeticTypes(); 8055 } 8056 8057 // Increment is deprecated for bool since C++17. 8058 // 8059 // C++ [over.built]p3: 8060 // 8061 // For every pair (T, VQ), where T is an arithmetic type other 8062 // than bool, and VQ is either volatile or empty, there exist 8063 // candidate operator functions of the form 8064 // 8065 // VQ T& operator++(VQ T&); 8066 // T operator++(VQ T&, int); 8067 // 8068 // C++ [over.built]p4: 8069 // 8070 // For every pair (T, VQ), where T is an arithmetic type other 8071 // than bool, and VQ is either volatile or empty, there exist 8072 // candidate operator functions of the form 8073 // 8074 // VQ T& operator--(VQ T&); 8075 // T operator--(VQ T&, int); 8076 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8077 if (!HasArithmeticOrEnumeralCandidateType) 8078 return; 8079 8080 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8081 const auto TypeOfT = ArithmeticTypes[Arith]; 8082 if (TypeOfT == S.Context.BoolTy) { 8083 if (Op == OO_MinusMinus) 8084 continue; 8085 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8086 continue; 8087 } 8088 addPlusPlusMinusMinusStyleOverloads( 8089 TypeOfT, 8090 VisibleTypeConversionsQuals.hasVolatile(), 8091 VisibleTypeConversionsQuals.hasRestrict()); 8092 } 8093 } 8094 8095 // C++ [over.built]p5: 8096 // 8097 // For every pair (T, VQ), where T is a cv-qualified or 8098 // cv-unqualified object type, and VQ is either volatile or 8099 // empty, there exist candidate operator functions of the form 8100 // 8101 // T*VQ& operator++(T*VQ&); 8102 // T*VQ& operator--(T*VQ&); 8103 // T* operator++(T*VQ&, int); 8104 // T* operator--(T*VQ&, int); 8105 void addPlusPlusMinusMinusPointerOverloads() { 8106 for (BuiltinCandidateTypeSet::iterator 8107 Ptr = CandidateTypes[0].pointer_begin(), 8108 PtrEnd = CandidateTypes[0].pointer_end(); 8109 Ptr != PtrEnd; ++Ptr) { 8110 // Skip pointer types that aren't pointers to object types. 8111 if (!(*Ptr)->getPointeeType()->isObjectType()) 8112 continue; 8113 8114 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8115 (!(*Ptr).isVolatileQualified() && 8116 VisibleTypeConversionsQuals.hasVolatile()), 8117 (!(*Ptr).isRestrictQualified() && 8118 VisibleTypeConversionsQuals.hasRestrict())); 8119 } 8120 } 8121 8122 // C++ [over.built]p6: 8123 // For every cv-qualified or cv-unqualified object type T, there 8124 // exist candidate operator functions of the form 8125 // 8126 // T& operator*(T*); 8127 // 8128 // C++ [over.built]p7: 8129 // For every function type T that does not have cv-qualifiers or a 8130 // ref-qualifier, there exist candidate operator functions of the form 8131 // T& operator*(T*); 8132 void addUnaryStarPointerOverloads() { 8133 for (BuiltinCandidateTypeSet::iterator 8134 Ptr = CandidateTypes[0].pointer_begin(), 8135 PtrEnd = CandidateTypes[0].pointer_end(); 8136 Ptr != PtrEnd; ++Ptr) { 8137 QualType ParamTy = *Ptr; 8138 QualType PointeeTy = ParamTy->getPointeeType(); 8139 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8140 continue; 8141 8142 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8143 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8144 continue; 8145 8146 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8147 } 8148 } 8149 8150 // C++ [over.built]p9: 8151 // For every promoted arithmetic type T, there exist candidate 8152 // operator functions of the form 8153 // 8154 // T operator+(T); 8155 // T operator-(T); 8156 void addUnaryPlusOrMinusArithmeticOverloads() { 8157 if (!HasArithmeticOrEnumeralCandidateType) 8158 return; 8159 8160 for (unsigned Arith = FirstPromotedArithmeticType; 8161 Arith < LastPromotedArithmeticType; ++Arith) { 8162 QualType ArithTy = ArithmeticTypes[Arith]; 8163 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8164 } 8165 8166 // Extension: We also add these operators for vector types. 8167 for (BuiltinCandidateTypeSet::iterator 8168 Vec = CandidateTypes[0].vector_begin(), 8169 VecEnd = CandidateTypes[0].vector_end(); 8170 Vec != VecEnd; ++Vec) { 8171 QualType VecTy = *Vec; 8172 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8173 } 8174 } 8175 8176 // C++ [over.built]p8: 8177 // For every type T, there exist candidate operator functions of 8178 // the form 8179 // 8180 // T* operator+(T*); 8181 void addUnaryPlusPointerOverloads() { 8182 for (BuiltinCandidateTypeSet::iterator 8183 Ptr = CandidateTypes[0].pointer_begin(), 8184 PtrEnd = CandidateTypes[0].pointer_end(); 8185 Ptr != PtrEnd; ++Ptr) { 8186 QualType ParamTy = *Ptr; 8187 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8188 } 8189 } 8190 8191 // C++ [over.built]p10: 8192 // For every promoted integral type T, there exist candidate 8193 // operator functions of the form 8194 // 8195 // T operator~(T); 8196 void addUnaryTildePromotedIntegralOverloads() { 8197 if (!HasArithmeticOrEnumeralCandidateType) 8198 return; 8199 8200 for (unsigned Int = FirstPromotedIntegralType; 8201 Int < LastPromotedIntegralType; ++Int) { 8202 QualType IntTy = ArithmeticTypes[Int]; 8203 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8204 } 8205 8206 // Extension: We also add this operator for vector types. 8207 for (BuiltinCandidateTypeSet::iterator 8208 Vec = CandidateTypes[0].vector_begin(), 8209 VecEnd = CandidateTypes[0].vector_end(); 8210 Vec != VecEnd; ++Vec) { 8211 QualType VecTy = *Vec; 8212 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8213 } 8214 } 8215 8216 // C++ [over.match.oper]p16: 8217 // For every pointer to member type T or type std::nullptr_t, there 8218 // exist candidate operator functions of the form 8219 // 8220 // bool operator==(T,T); 8221 // bool operator!=(T,T); 8222 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8223 /// Set of (canonical) types that we've already handled. 8224 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8225 8226 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8227 for (BuiltinCandidateTypeSet::iterator 8228 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8229 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8230 MemPtr != MemPtrEnd; 8231 ++MemPtr) { 8232 // Don't add the same builtin candidate twice. 8233 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8234 continue; 8235 8236 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8237 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8238 } 8239 8240 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8241 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8242 if (AddedTypes.insert(NullPtrTy).second) { 8243 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8244 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8245 } 8246 } 8247 } 8248 } 8249 8250 // C++ [over.built]p15: 8251 // 8252 // For every T, where T is an enumeration type or a pointer type, 8253 // there exist candidate operator functions of the form 8254 // 8255 // bool operator<(T, T); 8256 // bool operator>(T, T); 8257 // bool operator<=(T, T); 8258 // bool operator>=(T, T); 8259 // bool operator==(T, T); 8260 // bool operator!=(T, T); 8261 // R operator<=>(T, T) 8262 void addGenericBinaryPointerOrEnumeralOverloads() { 8263 // C++ [over.match.oper]p3: 8264 // [...]the built-in candidates include all of the candidate operator 8265 // functions defined in 13.6 that, compared to the given operator, [...] 8266 // do not have the same parameter-type-list as any non-template non-member 8267 // candidate. 8268 // 8269 // Note that in practice, this only affects enumeration types because there 8270 // aren't any built-in candidates of record type, and a user-defined operator 8271 // must have an operand of record or enumeration type. Also, the only other 8272 // overloaded operator with enumeration arguments, operator=, 8273 // cannot be overloaded for enumeration types, so this is the only place 8274 // where we must suppress candidates like this. 8275 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8276 UserDefinedBinaryOperators; 8277 8278 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8279 if (CandidateTypes[ArgIdx].enumeration_begin() != 8280 CandidateTypes[ArgIdx].enumeration_end()) { 8281 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8282 CEnd = CandidateSet.end(); 8283 C != CEnd; ++C) { 8284 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8285 continue; 8286 8287 if (C->Function->isFunctionTemplateSpecialization()) 8288 continue; 8289 8290 // We interpret "same parameter-type-list" as applying to the 8291 // "synthesized candidate, with the order of the two parameters 8292 // reversed", not to the original function. 8293 bool Reversed = C->RewriteKind & CRK_Reversed; 8294 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8295 ->getType() 8296 .getUnqualifiedType(); 8297 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8298 ->getType() 8299 .getUnqualifiedType(); 8300 8301 // Skip if either parameter isn't of enumeral type. 8302 if (!FirstParamType->isEnumeralType() || 8303 !SecondParamType->isEnumeralType()) 8304 continue; 8305 8306 // Add this operator to the set of known user-defined operators. 8307 UserDefinedBinaryOperators.insert( 8308 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8309 S.Context.getCanonicalType(SecondParamType))); 8310 } 8311 } 8312 } 8313 8314 /// Set of (canonical) types that we've already handled. 8315 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8316 8317 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8318 for (BuiltinCandidateTypeSet::iterator 8319 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8320 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8321 Ptr != PtrEnd; ++Ptr) { 8322 // Don't add the same builtin candidate twice. 8323 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8324 continue; 8325 8326 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8327 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8328 } 8329 for (BuiltinCandidateTypeSet::iterator 8330 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8331 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8332 Enum != EnumEnd; ++Enum) { 8333 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8334 8335 // Don't add the same builtin candidate twice, or if a user defined 8336 // candidate exists. 8337 if (!AddedTypes.insert(CanonType).second || 8338 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8339 CanonType))) 8340 continue; 8341 QualType ParamTypes[2] = { *Enum, *Enum }; 8342 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8343 } 8344 } 8345 } 8346 8347 // C++ [over.built]p13: 8348 // 8349 // For every cv-qualified or cv-unqualified object type T 8350 // there exist candidate operator functions of the form 8351 // 8352 // T* operator+(T*, ptrdiff_t); 8353 // T& operator[](T*, ptrdiff_t); [BELOW] 8354 // T* operator-(T*, ptrdiff_t); 8355 // T* operator+(ptrdiff_t, T*); 8356 // T& operator[](ptrdiff_t, T*); [BELOW] 8357 // 8358 // C++ [over.built]p14: 8359 // 8360 // For every T, where T is a pointer to object type, there 8361 // exist candidate operator functions of the form 8362 // 8363 // ptrdiff_t operator-(T, T); 8364 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8365 /// Set of (canonical) types that we've already handled. 8366 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8367 8368 for (int Arg = 0; Arg < 2; ++Arg) { 8369 QualType AsymmetricParamTypes[2] = { 8370 S.Context.getPointerDiffType(), 8371 S.Context.getPointerDiffType(), 8372 }; 8373 for (BuiltinCandidateTypeSet::iterator 8374 Ptr = CandidateTypes[Arg].pointer_begin(), 8375 PtrEnd = CandidateTypes[Arg].pointer_end(); 8376 Ptr != PtrEnd; ++Ptr) { 8377 QualType PointeeTy = (*Ptr)->getPointeeType(); 8378 if (!PointeeTy->isObjectType()) 8379 continue; 8380 8381 AsymmetricParamTypes[Arg] = *Ptr; 8382 if (Arg == 0 || Op == OO_Plus) { 8383 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8384 // T* operator+(ptrdiff_t, T*); 8385 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8386 } 8387 if (Op == OO_Minus) { 8388 // ptrdiff_t operator-(T, T); 8389 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8390 continue; 8391 8392 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8393 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8394 } 8395 } 8396 } 8397 } 8398 8399 // C++ [over.built]p12: 8400 // 8401 // For every pair of promoted arithmetic types L and R, there 8402 // exist candidate operator functions of the form 8403 // 8404 // LR operator*(L, R); 8405 // LR operator/(L, R); 8406 // LR operator+(L, R); 8407 // LR operator-(L, R); 8408 // bool operator<(L, R); 8409 // bool operator>(L, R); 8410 // bool operator<=(L, R); 8411 // bool operator>=(L, R); 8412 // bool operator==(L, R); 8413 // bool operator!=(L, R); 8414 // 8415 // where LR is the result of the usual arithmetic conversions 8416 // between types L and R. 8417 // 8418 // C++ [over.built]p24: 8419 // 8420 // For every pair of promoted arithmetic types L and R, there exist 8421 // candidate operator functions of the form 8422 // 8423 // LR operator?(bool, L, R); 8424 // 8425 // where LR is the result of the usual arithmetic conversions 8426 // between types L and R. 8427 // Our candidates ignore the first parameter. 8428 void addGenericBinaryArithmeticOverloads() { 8429 if (!HasArithmeticOrEnumeralCandidateType) 8430 return; 8431 8432 for (unsigned Left = FirstPromotedArithmeticType; 8433 Left < LastPromotedArithmeticType; ++Left) { 8434 for (unsigned Right = FirstPromotedArithmeticType; 8435 Right < LastPromotedArithmeticType; ++Right) { 8436 QualType LandR[2] = { ArithmeticTypes[Left], 8437 ArithmeticTypes[Right] }; 8438 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8439 } 8440 } 8441 8442 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8443 // conditional operator for vector types. 8444 for (BuiltinCandidateTypeSet::iterator 8445 Vec1 = CandidateTypes[0].vector_begin(), 8446 Vec1End = CandidateTypes[0].vector_end(); 8447 Vec1 != Vec1End; ++Vec1) { 8448 for (BuiltinCandidateTypeSet::iterator 8449 Vec2 = CandidateTypes[1].vector_begin(), 8450 Vec2End = CandidateTypes[1].vector_end(); 8451 Vec2 != Vec2End; ++Vec2) { 8452 QualType LandR[2] = { *Vec1, *Vec2 }; 8453 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8454 } 8455 } 8456 } 8457 8458 // C++2a [over.built]p14: 8459 // 8460 // For every integral type T there exists a candidate operator function 8461 // of the form 8462 // 8463 // std::strong_ordering operator<=>(T, T) 8464 // 8465 // C++2a [over.built]p15: 8466 // 8467 // For every pair of floating-point types L and R, there exists a candidate 8468 // operator function of the form 8469 // 8470 // std::partial_ordering operator<=>(L, R); 8471 // 8472 // FIXME: The current specification for integral types doesn't play nice with 8473 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8474 // comparisons. Under the current spec this can lead to ambiguity during 8475 // overload resolution. For example: 8476 // 8477 // enum A : int {a}; 8478 // auto x = (a <=> (long)42); 8479 // 8480 // error: call is ambiguous for arguments 'A' and 'long'. 8481 // note: candidate operator<=>(int, int) 8482 // note: candidate operator<=>(long, long) 8483 // 8484 // To avoid this error, this function deviates from the specification and adds 8485 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8486 // arithmetic types (the same as the generic relational overloads). 8487 // 8488 // For now this function acts as a placeholder. 8489 void addThreeWayArithmeticOverloads() { 8490 addGenericBinaryArithmeticOverloads(); 8491 } 8492 8493 // C++ [over.built]p17: 8494 // 8495 // For every pair of promoted integral types L and R, there 8496 // exist candidate operator functions of the form 8497 // 8498 // LR operator%(L, R); 8499 // LR operator&(L, R); 8500 // LR operator^(L, R); 8501 // LR operator|(L, R); 8502 // L operator<<(L, R); 8503 // L operator>>(L, R); 8504 // 8505 // where LR is the result of the usual arithmetic conversions 8506 // between types L and R. 8507 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8508 if (!HasArithmeticOrEnumeralCandidateType) 8509 return; 8510 8511 for (unsigned Left = FirstPromotedIntegralType; 8512 Left < LastPromotedIntegralType; ++Left) { 8513 for (unsigned Right = FirstPromotedIntegralType; 8514 Right < LastPromotedIntegralType; ++Right) { 8515 QualType LandR[2] = { ArithmeticTypes[Left], 8516 ArithmeticTypes[Right] }; 8517 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8518 } 8519 } 8520 } 8521 8522 // C++ [over.built]p20: 8523 // 8524 // For every pair (T, VQ), where T is an enumeration or 8525 // pointer to member type and VQ is either volatile or 8526 // empty, there exist candidate operator functions of the form 8527 // 8528 // VQ T& operator=(VQ T&, T); 8529 void addAssignmentMemberPointerOrEnumeralOverloads() { 8530 /// Set of (canonical) types that we've already handled. 8531 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8532 8533 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8534 for (BuiltinCandidateTypeSet::iterator 8535 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8536 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8537 Enum != EnumEnd; ++Enum) { 8538 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8539 continue; 8540 8541 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8542 } 8543 8544 for (BuiltinCandidateTypeSet::iterator 8545 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8546 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8547 MemPtr != MemPtrEnd; ++MemPtr) { 8548 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8549 continue; 8550 8551 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8552 } 8553 } 8554 } 8555 8556 // C++ [over.built]p19: 8557 // 8558 // For every pair (T, VQ), where T is any type and VQ is either 8559 // volatile or empty, there exist candidate operator functions 8560 // of the form 8561 // 8562 // T*VQ& operator=(T*VQ&, T*); 8563 // 8564 // C++ [over.built]p21: 8565 // 8566 // For every pair (T, VQ), where T is a cv-qualified or 8567 // cv-unqualified object type and VQ is either volatile or 8568 // empty, there exist candidate operator functions of the form 8569 // 8570 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8571 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8572 void addAssignmentPointerOverloads(bool isEqualOp) { 8573 /// Set of (canonical) types that we've already handled. 8574 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8575 8576 for (BuiltinCandidateTypeSet::iterator 8577 Ptr = CandidateTypes[0].pointer_begin(), 8578 PtrEnd = CandidateTypes[0].pointer_end(); 8579 Ptr != PtrEnd; ++Ptr) { 8580 // If this is operator=, keep track of the builtin candidates we added. 8581 if (isEqualOp) 8582 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8583 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8584 continue; 8585 8586 // non-volatile version 8587 QualType ParamTypes[2] = { 8588 S.Context.getLValueReferenceType(*Ptr), 8589 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8590 }; 8591 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8592 /*IsAssignmentOperator=*/ isEqualOp); 8593 8594 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8595 VisibleTypeConversionsQuals.hasVolatile(); 8596 if (NeedVolatile) { 8597 // volatile version 8598 ParamTypes[0] = 8599 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8600 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8601 /*IsAssignmentOperator=*/isEqualOp); 8602 } 8603 8604 if (!(*Ptr).isRestrictQualified() && 8605 VisibleTypeConversionsQuals.hasRestrict()) { 8606 // restrict version 8607 ParamTypes[0] 8608 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8609 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8610 /*IsAssignmentOperator=*/isEqualOp); 8611 8612 if (NeedVolatile) { 8613 // volatile restrict version 8614 ParamTypes[0] 8615 = S.Context.getLValueReferenceType( 8616 S.Context.getCVRQualifiedType(*Ptr, 8617 (Qualifiers::Volatile | 8618 Qualifiers::Restrict))); 8619 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8620 /*IsAssignmentOperator=*/isEqualOp); 8621 } 8622 } 8623 } 8624 8625 if (isEqualOp) { 8626 for (BuiltinCandidateTypeSet::iterator 8627 Ptr = CandidateTypes[1].pointer_begin(), 8628 PtrEnd = CandidateTypes[1].pointer_end(); 8629 Ptr != PtrEnd; ++Ptr) { 8630 // Make sure we don't add the same candidate twice. 8631 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8632 continue; 8633 8634 QualType ParamTypes[2] = { 8635 S.Context.getLValueReferenceType(*Ptr), 8636 *Ptr, 8637 }; 8638 8639 // non-volatile version 8640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8641 /*IsAssignmentOperator=*/true); 8642 8643 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8644 VisibleTypeConversionsQuals.hasVolatile(); 8645 if (NeedVolatile) { 8646 // volatile version 8647 ParamTypes[0] = 8648 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8650 /*IsAssignmentOperator=*/true); 8651 } 8652 8653 if (!(*Ptr).isRestrictQualified() && 8654 VisibleTypeConversionsQuals.hasRestrict()) { 8655 // restrict version 8656 ParamTypes[0] 8657 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8658 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8659 /*IsAssignmentOperator=*/true); 8660 8661 if (NeedVolatile) { 8662 // volatile restrict version 8663 ParamTypes[0] 8664 = S.Context.getLValueReferenceType( 8665 S.Context.getCVRQualifiedType(*Ptr, 8666 (Qualifiers::Volatile | 8667 Qualifiers::Restrict))); 8668 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8669 /*IsAssignmentOperator=*/true); 8670 } 8671 } 8672 } 8673 } 8674 } 8675 8676 // C++ [over.built]p18: 8677 // 8678 // For every triple (L, VQ, R), where L is an arithmetic type, 8679 // VQ is either volatile or empty, and R is a promoted 8680 // arithmetic type, there exist candidate operator functions of 8681 // the form 8682 // 8683 // VQ L& operator=(VQ L&, R); 8684 // VQ L& operator*=(VQ L&, R); 8685 // VQ L& operator/=(VQ L&, R); 8686 // VQ L& operator+=(VQ L&, R); 8687 // VQ L& operator-=(VQ L&, R); 8688 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8689 if (!HasArithmeticOrEnumeralCandidateType) 8690 return; 8691 8692 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8693 for (unsigned Right = FirstPromotedArithmeticType; 8694 Right < LastPromotedArithmeticType; ++Right) { 8695 QualType ParamTypes[2]; 8696 ParamTypes[1] = ArithmeticTypes[Right]; 8697 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8698 S, ArithmeticTypes[Left], Args[0]); 8699 // Add this built-in operator as a candidate (VQ is empty). 8700 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8701 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8702 /*IsAssignmentOperator=*/isEqualOp); 8703 8704 // Add this built-in operator as a candidate (VQ is 'volatile'). 8705 if (VisibleTypeConversionsQuals.hasVolatile()) { 8706 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8707 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8708 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8709 /*IsAssignmentOperator=*/isEqualOp); 8710 } 8711 } 8712 } 8713 8714 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8715 for (BuiltinCandidateTypeSet::iterator 8716 Vec1 = CandidateTypes[0].vector_begin(), 8717 Vec1End = CandidateTypes[0].vector_end(); 8718 Vec1 != Vec1End; ++Vec1) { 8719 for (BuiltinCandidateTypeSet::iterator 8720 Vec2 = CandidateTypes[1].vector_begin(), 8721 Vec2End = CandidateTypes[1].vector_end(); 8722 Vec2 != Vec2End; ++Vec2) { 8723 QualType ParamTypes[2]; 8724 ParamTypes[1] = *Vec2; 8725 // Add this built-in operator as a candidate (VQ is empty). 8726 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8727 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8728 /*IsAssignmentOperator=*/isEqualOp); 8729 8730 // Add this built-in operator as a candidate (VQ is 'volatile'). 8731 if (VisibleTypeConversionsQuals.hasVolatile()) { 8732 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8733 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8734 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8735 /*IsAssignmentOperator=*/isEqualOp); 8736 } 8737 } 8738 } 8739 } 8740 8741 // C++ [over.built]p22: 8742 // 8743 // For every triple (L, VQ, R), where L is an integral type, VQ 8744 // is either volatile or empty, and R is a promoted integral 8745 // type, there exist candidate operator functions of the form 8746 // 8747 // VQ L& operator%=(VQ L&, R); 8748 // VQ L& operator<<=(VQ L&, R); 8749 // VQ L& operator>>=(VQ L&, R); 8750 // VQ L& operator&=(VQ L&, R); 8751 // VQ L& operator^=(VQ L&, R); 8752 // VQ L& operator|=(VQ L&, R); 8753 void addAssignmentIntegralOverloads() { 8754 if (!HasArithmeticOrEnumeralCandidateType) 8755 return; 8756 8757 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8758 for (unsigned Right = FirstPromotedIntegralType; 8759 Right < LastPromotedIntegralType; ++Right) { 8760 QualType ParamTypes[2]; 8761 ParamTypes[1] = ArithmeticTypes[Right]; 8762 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8763 S, ArithmeticTypes[Left], Args[0]); 8764 // Add this built-in operator as a candidate (VQ is empty). 8765 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8766 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8767 if (VisibleTypeConversionsQuals.hasVolatile()) { 8768 // Add this built-in operator as a candidate (VQ is 'volatile'). 8769 ParamTypes[0] = LeftBaseTy; 8770 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8771 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8772 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8773 } 8774 } 8775 } 8776 } 8777 8778 // C++ [over.operator]p23: 8779 // 8780 // There also exist candidate operator functions of the form 8781 // 8782 // bool operator!(bool); 8783 // bool operator&&(bool, bool); 8784 // bool operator||(bool, bool); 8785 void addExclaimOverload() { 8786 QualType ParamTy = S.Context.BoolTy; 8787 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8788 /*IsAssignmentOperator=*/false, 8789 /*NumContextualBoolArguments=*/1); 8790 } 8791 void addAmpAmpOrPipePipeOverload() { 8792 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8793 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8794 /*IsAssignmentOperator=*/false, 8795 /*NumContextualBoolArguments=*/2); 8796 } 8797 8798 // C++ [over.built]p13: 8799 // 8800 // For every cv-qualified or cv-unqualified object type T there 8801 // exist candidate operator functions of the form 8802 // 8803 // T* operator+(T*, ptrdiff_t); [ABOVE] 8804 // T& operator[](T*, ptrdiff_t); 8805 // T* operator-(T*, ptrdiff_t); [ABOVE] 8806 // T* operator+(ptrdiff_t, T*); [ABOVE] 8807 // T& operator[](ptrdiff_t, T*); 8808 void addSubscriptOverloads() { 8809 for (BuiltinCandidateTypeSet::iterator 8810 Ptr = CandidateTypes[0].pointer_begin(), 8811 PtrEnd = CandidateTypes[0].pointer_end(); 8812 Ptr != PtrEnd; ++Ptr) { 8813 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8814 QualType PointeeType = (*Ptr)->getPointeeType(); 8815 if (!PointeeType->isObjectType()) 8816 continue; 8817 8818 // T& operator[](T*, ptrdiff_t) 8819 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8820 } 8821 8822 for (BuiltinCandidateTypeSet::iterator 8823 Ptr = CandidateTypes[1].pointer_begin(), 8824 PtrEnd = CandidateTypes[1].pointer_end(); 8825 Ptr != PtrEnd; ++Ptr) { 8826 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8827 QualType PointeeType = (*Ptr)->getPointeeType(); 8828 if (!PointeeType->isObjectType()) 8829 continue; 8830 8831 // T& operator[](ptrdiff_t, T*) 8832 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8833 } 8834 } 8835 8836 // C++ [over.built]p11: 8837 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8838 // C1 is the same type as C2 or is a derived class of C2, T is an object 8839 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8840 // there exist candidate operator functions of the form 8841 // 8842 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8843 // 8844 // where CV12 is the union of CV1 and CV2. 8845 void addArrowStarOverloads() { 8846 for (BuiltinCandidateTypeSet::iterator 8847 Ptr = CandidateTypes[0].pointer_begin(), 8848 PtrEnd = CandidateTypes[0].pointer_end(); 8849 Ptr != PtrEnd; ++Ptr) { 8850 QualType C1Ty = (*Ptr); 8851 QualType C1; 8852 QualifierCollector Q1; 8853 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8854 if (!isa<RecordType>(C1)) 8855 continue; 8856 // heuristic to reduce number of builtin candidates in the set. 8857 // Add volatile/restrict version only if there are conversions to a 8858 // volatile/restrict type. 8859 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8860 continue; 8861 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8862 continue; 8863 for (BuiltinCandidateTypeSet::iterator 8864 MemPtr = CandidateTypes[1].member_pointer_begin(), 8865 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8866 MemPtr != MemPtrEnd; ++MemPtr) { 8867 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8868 QualType C2 = QualType(mptr->getClass(), 0); 8869 C2 = C2.getUnqualifiedType(); 8870 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8871 break; 8872 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8873 // build CV12 T& 8874 QualType T = mptr->getPointeeType(); 8875 if (!VisibleTypeConversionsQuals.hasVolatile() && 8876 T.isVolatileQualified()) 8877 continue; 8878 if (!VisibleTypeConversionsQuals.hasRestrict() && 8879 T.isRestrictQualified()) 8880 continue; 8881 T = Q1.apply(S.Context, T); 8882 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8883 } 8884 } 8885 } 8886 8887 // Note that we don't consider the first argument, since it has been 8888 // contextually converted to bool long ago. The candidates below are 8889 // therefore added as binary. 8890 // 8891 // C++ [over.built]p25: 8892 // For every type T, where T is a pointer, pointer-to-member, or scoped 8893 // enumeration type, there exist candidate operator functions of the form 8894 // 8895 // T operator?(bool, T, T); 8896 // 8897 void addConditionalOperatorOverloads() { 8898 /// Set of (canonical) types that we've already handled. 8899 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8900 8901 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8902 for (BuiltinCandidateTypeSet::iterator 8903 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8904 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8905 Ptr != PtrEnd; ++Ptr) { 8906 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8907 continue; 8908 8909 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8910 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8911 } 8912 8913 for (BuiltinCandidateTypeSet::iterator 8914 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8915 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8916 MemPtr != MemPtrEnd; ++MemPtr) { 8917 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8918 continue; 8919 8920 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8921 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8922 } 8923 8924 if (S.getLangOpts().CPlusPlus11) { 8925 for (BuiltinCandidateTypeSet::iterator 8926 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8927 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8928 Enum != EnumEnd; ++Enum) { 8929 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 8930 continue; 8931 8932 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8933 continue; 8934 8935 QualType ParamTypes[2] = { *Enum, *Enum }; 8936 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8937 } 8938 } 8939 } 8940 } 8941 }; 8942 8943 } // end anonymous namespace 8944 8945 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8946 /// operator overloads to the candidate set (C++ [over.built]), based 8947 /// on the operator @p Op and the arguments given. For example, if the 8948 /// operator is a binary '+', this routine might add "int 8949 /// operator+(int, int)" to cover integer addition. 8950 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8951 SourceLocation OpLoc, 8952 ArrayRef<Expr *> Args, 8953 OverloadCandidateSet &CandidateSet) { 8954 // Find all of the types that the arguments can convert to, but only 8955 // if the operator we're looking at has built-in operator candidates 8956 // that make use of these types. Also record whether we encounter non-record 8957 // candidate types or either arithmetic or enumeral candidate types. 8958 Qualifiers VisibleTypeConversionsQuals; 8959 VisibleTypeConversionsQuals.addConst(); 8960 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8961 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8962 8963 bool HasNonRecordCandidateType = false; 8964 bool HasArithmeticOrEnumeralCandidateType = false; 8965 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8966 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8967 CandidateTypes.emplace_back(*this); 8968 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8969 OpLoc, 8970 true, 8971 (Op == OO_Exclaim || 8972 Op == OO_AmpAmp || 8973 Op == OO_PipePipe), 8974 VisibleTypeConversionsQuals); 8975 HasNonRecordCandidateType = HasNonRecordCandidateType || 8976 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8977 HasArithmeticOrEnumeralCandidateType = 8978 HasArithmeticOrEnumeralCandidateType || 8979 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8980 } 8981 8982 // Exit early when no non-record types have been added to the candidate set 8983 // for any of the arguments to the operator. 8984 // 8985 // We can't exit early for !, ||, or &&, since there we have always have 8986 // 'bool' overloads. 8987 if (!HasNonRecordCandidateType && 8988 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8989 return; 8990 8991 // Setup an object to manage the common state for building overloads. 8992 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8993 VisibleTypeConversionsQuals, 8994 HasArithmeticOrEnumeralCandidateType, 8995 CandidateTypes, CandidateSet); 8996 8997 // Dispatch over the operation to add in only those overloads which apply. 8998 switch (Op) { 8999 case OO_None: 9000 case NUM_OVERLOADED_OPERATORS: 9001 llvm_unreachable("Expected an overloaded operator"); 9002 9003 case OO_New: 9004 case OO_Delete: 9005 case OO_Array_New: 9006 case OO_Array_Delete: 9007 case OO_Call: 9008 llvm_unreachable( 9009 "Special operators don't use AddBuiltinOperatorCandidates"); 9010 9011 case OO_Comma: 9012 case OO_Arrow: 9013 case OO_Coawait: 9014 // C++ [over.match.oper]p3: 9015 // -- For the operator ',', the unary operator '&', the 9016 // operator '->', or the operator 'co_await', the 9017 // built-in candidates set is empty. 9018 break; 9019 9020 case OO_Plus: // '+' is either unary or binary 9021 if (Args.size() == 1) 9022 OpBuilder.addUnaryPlusPointerOverloads(); 9023 LLVM_FALLTHROUGH; 9024 9025 case OO_Minus: // '-' is either unary or binary 9026 if (Args.size() == 1) { 9027 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9028 } else { 9029 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9030 OpBuilder.addGenericBinaryArithmeticOverloads(); 9031 } 9032 break; 9033 9034 case OO_Star: // '*' is either unary or binary 9035 if (Args.size() == 1) 9036 OpBuilder.addUnaryStarPointerOverloads(); 9037 else 9038 OpBuilder.addGenericBinaryArithmeticOverloads(); 9039 break; 9040 9041 case OO_Slash: 9042 OpBuilder.addGenericBinaryArithmeticOverloads(); 9043 break; 9044 9045 case OO_PlusPlus: 9046 case OO_MinusMinus: 9047 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9048 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9049 break; 9050 9051 case OO_EqualEqual: 9052 case OO_ExclaimEqual: 9053 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9054 LLVM_FALLTHROUGH; 9055 9056 case OO_Less: 9057 case OO_Greater: 9058 case OO_LessEqual: 9059 case OO_GreaterEqual: 9060 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9061 OpBuilder.addGenericBinaryArithmeticOverloads(); 9062 break; 9063 9064 case OO_Spaceship: 9065 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9066 OpBuilder.addThreeWayArithmeticOverloads(); 9067 break; 9068 9069 case OO_Percent: 9070 case OO_Caret: 9071 case OO_Pipe: 9072 case OO_LessLess: 9073 case OO_GreaterGreater: 9074 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9075 break; 9076 9077 case OO_Amp: // '&' is either unary or binary 9078 if (Args.size() == 1) 9079 // C++ [over.match.oper]p3: 9080 // -- For the operator ',', the unary operator '&', or the 9081 // operator '->', the built-in candidates set is empty. 9082 break; 9083 9084 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9085 break; 9086 9087 case OO_Tilde: 9088 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9089 break; 9090 9091 case OO_Equal: 9092 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9093 LLVM_FALLTHROUGH; 9094 9095 case OO_PlusEqual: 9096 case OO_MinusEqual: 9097 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9098 LLVM_FALLTHROUGH; 9099 9100 case OO_StarEqual: 9101 case OO_SlashEqual: 9102 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9103 break; 9104 9105 case OO_PercentEqual: 9106 case OO_LessLessEqual: 9107 case OO_GreaterGreaterEqual: 9108 case OO_AmpEqual: 9109 case OO_CaretEqual: 9110 case OO_PipeEqual: 9111 OpBuilder.addAssignmentIntegralOverloads(); 9112 break; 9113 9114 case OO_Exclaim: 9115 OpBuilder.addExclaimOverload(); 9116 break; 9117 9118 case OO_AmpAmp: 9119 case OO_PipePipe: 9120 OpBuilder.addAmpAmpOrPipePipeOverload(); 9121 break; 9122 9123 case OO_Subscript: 9124 OpBuilder.addSubscriptOverloads(); 9125 break; 9126 9127 case OO_ArrowStar: 9128 OpBuilder.addArrowStarOverloads(); 9129 break; 9130 9131 case OO_Conditional: 9132 OpBuilder.addConditionalOperatorOverloads(); 9133 OpBuilder.addGenericBinaryArithmeticOverloads(); 9134 break; 9135 } 9136 } 9137 9138 /// Add function candidates found via argument-dependent lookup 9139 /// to the set of overloading candidates. 9140 /// 9141 /// This routine performs argument-dependent name lookup based on the 9142 /// given function name (which may also be an operator name) and adds 9143 /// all of the overload candidates found by ADL to the overload 9144 /// candidate set (C++ [basic.lookup.argdep]). 9145 void 9146 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9147 SourceLocation Loc, 9148 ArrayRef<Expr *> Args, 9149 TemplateArgumentListInfo *ExplicitTemplateArgs, 9150 OverloadCandidateSet& CandidateSet, 9151 bool PartialOverloading) { 9152 ADLResult Fns; 9153 9154 // FIXME: This approach for uniquing ADL results (and removing 9155 // redundant candidates from the set) relies on pointer-equality, 9156 // which means we need to key off the canonical decl. However, 9157 // always going back to the canonical decl might not get us the 9158 // right set of default arguments. What default arguments are 9159 // we supposed to consider on ADL candidates, anyway? 9160 9161 // FIXME: Pass in the explicit template arguments? 9162 ArgumentDependentLookup(Name, Loc, Args, Fns); 9163 9164 // Erase all of the candidates we already knew about. 9165 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9166 CandEnd = CandidateSet.end(); 9167 Cand != CandEnd; ++Cand) 9168 if (Cand->Function) { 9169 Fns.erase(Cand->Function); 9170 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9171 Fns.erase(FunTmpl); 9172 } 9173 9174 // For each of the ADL candidates we found, add it to the overload 9175 // set. 9176 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9177 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9178 9179 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9180 if (ExplicitTemplateArgs) 9181 continue; 9182 9183 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9184 /*SuppressUserConversions=*/false, PartialOverloading, 9185 /*AllowExplicit*/ true, 9186 /*AllowExplicitConversions*/ false, 9187 ADLCallKind::UsesADL); 9188 } else { 9189 AddTemplateOverloadCandidate( 9190 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9191 CandidateSet, 9192 /*SuppressUserConversions=*/false, PartialOverloading, 9193 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9194 } 9195 } 9196 } 9197 9198 namespace { 9199 enum class Comparison { Equal, Better, Worse }; 9200 } 9201 9202 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9203 /// overload resolution. 9204 /// 9205 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9206 /// Cand1's first N enable_if attributes have precisely the same conditions as 9207 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9208 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9209 /// 9210 /// Note that you can have a pair of candidates such that Cand1's enable_if 9211 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9212 /// worse than Cand1's. 9213 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9214 const FunctionDecl *Cand2) { 9215 // Common case: One (or both) decls don't have enable_if attrs. 9216 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9217 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9218 if (!Cand1Attr || !Cand2Attr) { 9219 if (Cand1Attr == Cand2Attr) 9220 return Comparison::Equal; 9221 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9222 } 9223 9224 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9225 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9226 9227 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9228 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9229 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9230 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9231 9232 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9233 // has fewer enable_if attributes than Cand2, and vice versa. 9234 if (!Cand1A) 9235 return Comparison::Worse; 9236 if (!Cand2A) 9237 return Comparison::Better; 9238 9239 Cand1ID.clear(); 9240 Cand2ID.clear(); 9241 9242 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9243 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9244 if (Cand1ID != Cand2ID) 9245 return Comparison::Worse; 9246 } 9247 9248 return Comparison::Equal; 9249 } 9250 9251 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9252 const OverloadCandidate &Cand2) { 9253 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9254 !Cand2.Function->isMultiVersion()) 9255 return false; 9256 9257 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9258 // is obviously better. 9259 if (Cand1.Function->isInvalidDecl()) return false; 9260 if (Cand2.Function->isInvalidDecl()) return true; 9261 9262 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9263 // cpu_dispatch, else arbitrarily based on the identifiers. 9264 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9265 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9266 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9267 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9268 9269 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9270 return false; 9271 9272 if (Cand1CPUDisp && !Cand2CPUDisp) 9273 return true; 9274 if (Cand2CPUDisp && !Cand1CPUDisp) 9275 return false; 9276 9277 if (Cand1CPUSpec && Cand2CPUSpec) { 9278 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9279 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9280 9281 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9282 FirstDiff = std::mismatch( 9283 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9284 Cand2CPUSpec->cpus_begin(), 9285 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9286 return LHS->getName() == RHS->getName(); 9287 }); 9288 9289 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9290 "Two different cpu-specific versions should not have the same " 9291 "identifier list, otherwise they'd be the same decl!"); 9292 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9293 } 9294 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9295 } 9296 9297 /// isBetterOverloadCandidate - Determines whether the first overload 9298 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9299 bool clang::isBetterOverloadCandidate( 9300 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9301 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9302 // Define viable functions to be better candidates than non-viable 9303 // functions. 9304 if (!Cand2.Viable) 9305 return Cand1.Viable; 9306 else if (!Cand1.Viable) 9307 return false; 9308 9309 // C++ [over.match.best]p1: 9310 // 9311 // -- if F is a static member function, ICS1(F) is defined such 9312 // that ICS1(F) is neither better nor worse than ICS1(G) for 9313 // any function G, and, symmetrically, ICS1(G) is neither 9314 // better nor worse than ICS1(F). 9315 unsigned StartArg = 0; 9316 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9317 StartArg = 1; 9318 9319 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9320 // We don't allow incompatible pointer conversions in C++. 9321 if (!S.getLangOpts().CPlusPlus) 9322 return ICS.isStandard() && 9323 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9324 9325 // The only ill-formed conversion we allow in C++ is the string literal to 9326 // char* conversion, which is only considered ill-formed after C++11. 9327 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9328 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9329 }; 9330 9331 // Define functions that don't require ill-formed conversions for a given 9332 // argument to be better candidates than functions that do. 9333 unsigned NumArgs = Cand1.Conversions.size(); 9334 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9335 bool HasBetterConversion = false; 9336 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9337 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9338 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9339 if (Cand1Bad != Cand2Bad) { 9340 if (Cand1Bad) 9341 return false; 9342 HasBetterConversion = true; 9343 } 9344 } 9345 9346 if (HasBetterConversion) 9347 return true; 9348 9349 // C++ [over.match.best]p1: 9350 // A viable function F1 is defined to be a better function than another 9351 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9352 // conversion sequence than ICSi(F2), and then... 9353 bool HasWorseConversion = false; 9354 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9355 switch (CompareImplicitConversionSequences(S, Loc, 9356 Cand1.Conversions[ArgIdx], 9357 Cand2.Conversions[ArgIdx])) { 9358 case ImplicitConversionSequence::Better: 9359 // Cand1 has a better conversion sequence. 9360 HasBetterConversion = true; 9361 break; 9362 9363 case ImplicitConversionSequence::Worse: 9364 if (Cand1.Function && Cand1.Function == Cand2.Function && 9365 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9366 // Work around large-scale breakage caused by considering reversed 9367 // forms of operator== in C++20: 9368 // 9369 // When comparing a function against its reversed form, if we have a 9370 // better conversion for one argument and a worse conversion for the 9371 // other, we prefer the non-reversed form. 9372 // 9373 // This prevents a conversion function from being considered ambiguous 9374 // with its own reversed form in various where it's only incidentally 9375 // heterogeneous. 9376 // 9377 // We diagnose this as an extension from CreateOverloadedBinOp. 9378 HasWorseConversion = true; 9379 break; 9380 } 9381 9382 // Cand1 can't be better than Cand2. 9383 return false; 9384 9385 case ImplicitConversionSequence::Indistinguishable: 9386 // Do nothing. 9387 break; 9388 } 9389 } 9390 9391 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9392 // ICSj(F2), or, if not that, 9393 if (HasBetterConversion) 9394 return true; 9395 if (HasWorseConversion) 9396 return false; 9397 9398 // -- the context is an initialization by user-defined conversion 9399 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9400 // from the return type of F1 to the destination type (i.e., 9401 // the type of the entity being initialized) is a better 9402 // conversion sequence than the standard conversion sequence 9403 // from the return type of F2 to the destination type. 9404 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9405 Cand1.Function && Cand2.Function && 9406 isa<CXXConversionDecl>(Cand1.Function) && 9407 isa<CXXConversionDecl>(Cand2.Function)) { 9408 // First check whether we prefer one of the conversion functions over the 9409 // other. This only distinguishes the results in non-standard, extension 9410 // cases such as the conversion from a lambda closure type to a function 9411 // pointer or block. 9412 ImplicitConversionSequence::CompareKind Result = 9413 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9414 if (Result == ImplicitConversionSequence::Indistinguishable) 9415 Result = CompareStandardConversionSequences(S, Loc, 9416 Cand1.FinalConversion, 9417 Cand2.FinalConversion); 9418 9419 if (Result != ImplicitConversionSequence::Indistinguishable) 9420 return Result == ImplicitConversionSequence::Better; 9421 9422 // FIXME: Compare kind of reference binding if conversion functions 9423 // convert to a reference type used in direct reference binding, per 9424 // C++14 [over.match.best]p1 section 2 bullet 3. 9425 } 9426 9427 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9428 // as combined with the resolution to CWG issue 243. 9429 // 9430 // When the context is initialization by constructor ([over.match.ctor] or 9431 // either phase of [over.match.list]), a constructor is preferred over 9432 // a conversion function. 9433 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9434 Cand1.Function && Cand2.Function && 9435 isa<CXXConstructorDecl>(Cand1.Function) != 9436 isa<CXXConstructorDecl>(Cand2.Function)) 9437 return isa<CXXConstructorDecl>(Cand1.Function); 9438 9439 // -- F1 is a non-template function and F2 is a function template 9440 // specialization, or, if not that, 9441 bool Cand1IsSpecialization = Cand1.Function && 9442 Cand1.Function->getPrimaryTemplate(); 9443 bool Cand2IsSpecialization = Cand2.Function && 9444 Cand2.Function->getPrimaryTemplate(); 9445 if (Cand1IsSpecialization != Cand2IsSpecialization) 9446 return Cand2IsSpecialization; 9447 9448 // -- F1 and F2 are function template specializations, and the function 9449 // template for F1 is more specialized than the template for F2 9450 // according to the partial ordering rules described in 14.5.5.2, or, 9451 // if not that, 9452 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9453 if (FunctionTemplateDecl *BetterTemplate 9454 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9455 Cand2.Function->getPrimaryTemplate(), 9456 Loc, 9457 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9458 : TPOC_Call, 9459 Cand1.ExplicitCallArguments, 9460 Cand2.ExplicitCallArguments)) 9461 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9462 } 9463 9464 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9465 // class B of D, and for all arguments the corresponding parameters of 9466 // F1 and F2 have the same type. 9467 // FIXME: Implement the "all parameters have the same type" check. 9468 bool Cand1IsInherited = 9469 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9470 bool Cand2IsInherited = 9471 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9472 if (Cand1IsInherited != Cand2IsInherited) 9473 return Cand2IsInherited; 9474 else if (Cand1IsInherited) { 9475 assert(Cand2IsInherited); 9476 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9477 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9478 if (Cand1Class->isDerivedFrom(Cand2Class)) 9479 return true; 9480 if (Cand2Class->isDerivedFrom(Cand1Class)) 9481 return false; 9482 // Inherited from sibling base classes: still ambiguous. 9483 } 9484 9485 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9486 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9487 // with reversed order of parameters and F1 is not 9488 // 9489 // We rank reversed + different operator as worse than just reversed, but 9490 // that comparison can never happen, because we only consider reversing for 9491 // the maximally-rewritten operator (== or <=>). 9492 if (Cand1.RewriteKind != Cand2.RewriteKind) 9493 return Cand1.RewriteKind < Cand2.RewriteKind; 9494 9495 // Check C++17 tie-breakers for deduction guides. 9496 { 9497 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9498 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9499 if (Guide1 && Guide2) { 9500 // -- F1 is generated from a deduction-guide and F2 is not 9501 if (Guide1->isImplicit() != Guide2->isImplicit()) 9502 return Guide2->isImplicit(); 9503 9504 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9505 if (Guide1->isCopyDeductionCandidate()) 9506 return true; 9507 } 9508 } 9509 9510 // Check for enable_if value-based overload resolution. 9511 if (Cand1.Function && Cand2.Function) { 9512 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9513 if (Cmp != Comparison::Equal) 9514 return Cmp == Comparison::Better; 9515 } 9516 9517 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9518 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9519 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9520 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9521 } 9522 9523 bool HasPS1 = Cand1.Function != nullptr && 9524 functionHasPassObjectSizeParams(Cand1.Function); 9525 bool HasPS2 = Cand2.Function != nullptr && 9526 functionHasPassObjectSizeParams(Cand2.Function); 9527 if (HasPS1 != HasPS2 && HasPS1) 9528 return true; 9529 9530 return isBetterMultiversionCandidate(Cand1, Cand2); 9531 } 9532 9533 /// Determine whether two declarations are "equivalent" for the purposes of 9534 /// name lookup and overload resolution. This applies when the same internal/no 9535 /// linkage entity is defined by two modules (probably by textually including 9536 /// the same header). In such a case, we don't consider the declarations to 9537 /// declare the same entity, but we also don't want lookups with both 9538 /// declarations visible to be ambiguous in some cases (this happens when using 9539 /// a modularized libstdc++). 9540 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9541 const NamedDecl *B) { 9542 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9543 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9544 if (!VA || !VB) 9545 return false; 9546 9547 // The declarations must be declaring the same name as an internal linkage 9548 // entity in different modules. 9549 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9550 VB->getDeclContext()->getRedeclContext()) || 9551 getOwningModule(const_cast<ValueDecl *>(VA)) == 9552 getOwningModule(const_cast<ValueDecl *>(VB)) || 9553 VA->isExternallyVisible() || VB->isExternallyVisible()) 9554 return false; 9555 9556 // Check that the declarations appear to be equivalent. 9557 // 9558 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9559 // For constants and functions, we should check the initializer or body is 9560 // the same. For non-constant variables, we shouldn't allow it at all. 9561 if (Context.hasSameType(VA->getType(), VB->getType())) 9562 return true; 9563 9564 // Enum constants within unnamed enumerations will have different types, but 9565 // may still be similar enough to be interchangeable for our purposes. 9566 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9567 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9568 // Only handle anonymous enums. If the enumerations were named and 9569 // equivalent, they would have been merged to the same type. 9570 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9571 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9572 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9573 !Context.hasSameType(EnumA->getIntegerType(), 9574 EnumB->getIntegerType())) 9575 return false; 9576 // Allow this only if the value is the same for both enumerators. 9577 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9578 } 9579 } 9580 9581 // Nothing else is sufficiently similar. 9582 return false; 9583 } 9584 9585 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9586 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9587 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9588 9589 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9590 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9591 << !M << (M ? M->getFullModuleName() : ""); 9592 9593 for (auto *E : Equiv) { 9594 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9595 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9596 << !M << (M ? M->getFullModuleName() : ""); 9597 } 9598 } 9599 9600 /// Computes the best viable function (C++ 13.3.3) 9601 /// within an overload candidate set. 9602 /// 9603 /// \param Loc The location of the function name (or operator symbol) for 9604 /// which overload resolution occurs. 9605 /// 9606 /// \param Best If overload resolution was successful or found a deleted 9607 /// function, \p Best points to the candidate function found. 9608 /// 9609 /// \returns The result of overload resolution. 9610 OverloadingResult 9611 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9612 iterator &Best) { 9613 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9614 std::transform(begin(), end(), std::back_inserter(Candidates), 9615 [](OverloadCandidate &Cand) { return &Cand; }); 9616 9617 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9618 // are accepted by both clang and NVCC. However, during a particular 9619 // compilation mode only one call variant is viable. We need to 9620 // exclude non-viable overload candidates from consideration based 9621 // only on their host/device attributes. Specifically, if one 9622 // candidate call is WrongSide and the other is SameSide, we ignore 9623 // the WrongSide candidate. 9624 if (S.getLangOpts().CUDA) { 9625 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9626 bool ContainsSameSideCandidate = 9627 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9628 // Check viable function only. 9629 return Cand->Viable && Cand->Function && 9630 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9631 Sema::CFP_SameSide; 9632 }); 9633 if (ContainsSameSideCandidate) { 9634 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9635 // Check viable function only to avoid unnecessary data copying/moving. 9636 return Cand->Viable && Cand->Function && 9637 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9638 Sema::CFP_WrongSide; 9639 }; 9640 llvm::erase_if(Candidates, IsWrongSideCandidate); 9641 } 9642 } 9643 9644 // Find the best viable function. 9645 Best = end(); 9646 for (auto *Cand : Candidates) { 9647 Cand->Best = false; 9648 if (Cand->Viable) 9649 if (Best == end() || 9650 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9651 Best = Cand; 9652 } 9653 9654 // If we didn't find any viable functions, abort. 9655 if (Best == end()) 9656 return OR_No_Viable_Function; 9657 9658 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9659 9660 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9661 PendingBest.push_back(&*Best); 9662 Best->Best = true; 9663 9664 // Make sure that this function is better than every other viable 9665 // function. If not, we have an ambiguity. 9666 while (!PendingBest.empty()) { 9667 auto *Curr = PendingBest.pop_back_val(); 9668 for (auto *Cand : Candidates) { 9669 if (Cand->Viable && !Cand->Best && 9670 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9671 PendingBest.push_back(Cand); 9672 Cand->Best = true; 9673 9674 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9675 Curr->Function)) 9676 EquivalentCands.push_back(Cand->Function); 9677 else 9678 Best = end(); 9679 } 9680 } 9681 } 9682 9683 // If we found more than one best candidate, this is ambiguous. 9684 if (Best == end()) 9685 return OR_Ambiguous; 9686 9687 // Best is the best viable function. 9688 if (Best->Function && Best->Function->isDeleted()) 9689 return OR_Deleted; 9690 9691 if (!EquivalentCands.empty()) 9692 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9693 EquivalentCands); 9694 9695 return OR_Success; 9696 } 9697 9698 namespace { 9699 9700 enum OverloadCandidateKind { 9701 oc_function, 9702 oc_method, 9703 oc_reversed_binary_operator, 9704 oc_constructor, 9705 oc_implicit_default_constructor, 9706 oc_implicit_copy_constructor, 9707 oc_implicit_move_constructor, 9708 oc_implicit_copy_assignment, 9709 oc_implicit_move_assignment, 9710 oc_implicit_equality_comparison, 9711 oc_inherited_constructor 9712 }; 9713 9714 enum OverloadCandidateSelect { 9715 ocs_non_template, 9716 ocs_template, 9717 ocs_described_template, 9718 }; 9719 9720 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9721 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9722 OverloadCandidateRewriteKind CRK, 9723 std::string &Description) { 9724 9725 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9726 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9727 isTemplate = true; 9728 Description = S.getTemplateArgumentBindingsText( 9729 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9730 } 9731 9732 OverloadCandidateSelect Select = [&]() { 9733 if (!Description.empty()) 9734 return ocs_described_template; 9735 return isTemplate ? ocs_template : ocs_non_template; 9736 }(); 9737 9738 OverloadCandidateKind Kind = [&]() { 9739 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9740 return oc_implicit_equality_comparison; 9741 9742 if (CRK & CRK_Reversed) 9743 return oc_reversed_binary_operator; 9744 9745 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9746 if (!Ctor->isImplicit()) { 9747 if (isa<ConstructorUsingShadowDecl>(Found)) 9748 return oc_inherited_constructor; 9749 else 9750 return oc_constructor; 9751 } 9752 9753 if (Ctor->isDefaultConstructor()) 9754 return oc_implicit_default_constructor; 9755 9756 if (Ctor->isMoveConstructor()) 9757 return oc_implicit_move_constructor; 9758 9759 assert(Ctor->isCopyConstructor() && 9760 "unexpected sort of implicit constructor"); 9761 return oc_implicit_copy_constructor; 9762 } 9763 9764 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9765 // This actually gets spelled 'candidate function' for now, but 9766 // it doesn't hurt to split it out. 9767 if (!Meth->isImplicit()) 9768 return oc_method; 9769 9770 if (Meth->isMoveAssignmentOperator()) 9771 return oc_implicit_move_assignment; 9772 9773 if (Meth->isCopyAssignmentOperator()) 9774 return oc_implicit_copy_assignment; 9775 9776 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9777 return oc_method; 9778 } 9779 9780 return oc_function; 9781 }(); 9782 9783 return std::make_pair(Kind, Select); 9784 } 9785 9786 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9787 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9788 // set. 9789 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9790 S.Diag(FoundDecl->getLocation(), 9791 diag::note_ovl_candidate_inherited_constructor) 9792 << Shadow->getNominatedBaseClass(); 9793 } 9794 9795 } // end anonymous namespace 9796 9797 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9798 const FunctionDecl *FD) { 9799 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9800 bool AlwaysTrue; 9801 if (EnableIf->getCond()->isValueDependent() || 9802 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9803 return false; 9804 if (!AlwaysTrue) 9805 return false; 9806 } 9807 return true; 9808 } 9809 9810 /// Returns true if we can take the address of the function. 9811 /// 9812 /// \param Complain - If true, we'll emit a diagnostic 9813 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9814 /// we in overload resolution? 9815 /// \param Loc - The location of the statement we're complaining about. Ignored 9816 /// if we're not complaining, or if we're in overload resolution. 9817 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9818 bool Complain, 9819 bool InOverloadResolution, 9820 SourceLocation Loc) { 9821 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9822 if (Complain) { 9823 if (InOverloadResolution) 9824 S.Diag(FD->getBeginLoc(), 9825 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9826 else 9827 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9828 } 9829 return false; 9830 } 9831 9832 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9833 return P->hasAttr<PassObjectSizeAttr>(); 9834 }); 9835 if (I == FD->param_end()) 9836 return true; 9837 9838 if (Complain) { 9839 // Add one to ParamNo because it's user-facing 9840 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9841 if (InOverloadResolution) 9842 S.Diag(FD->getLocation(), 9843 diag::note_ovl_candidate_has_pass_object_size_params) 9844 << ParamNo; 9845 else 9846 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9847 << FD << ParamNo; 9848 } 9849 return false; 9850 } 9851 9852 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9853 const FunctionDecl *FD) { 9854 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9855 /*InOverloadResolution=*/true, 9856 /*Loc=*/SourceLocation()); 9857 } 9858 9859 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9860 bool Complain, 9861 SourceLocation Loc) { 9862 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9863 /*InOverloadResolution=*/false, 9864 Loc); 9865 } 9866 9867 // Notes the location of an overload candidate. 9868 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9869 OverloadCandidateRewriteKind RewriteKind, 9870 QualType DestType, bool TakingAddress) { 9871 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9872 return; 9873 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9874 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9875 return; 9876 9877 std::string FnDesc; 9878 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9879 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 9880 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9881 << (unsigned)KSPair.first << (unsigned)KSPair.second 9882 << Fn << FnDesc; 9883 9884 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9885 Diag(Fn->getLocation(), PD); 9886 MaybeEmitInheritedConstructorNote(*this, Found); 9887 } 9888 9889 // Notes the location of all overload candidates designated through 9890 // OverloadedExpr 9891 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9892 bool TakingAddress) { 9893 assert(OverloadedExpr->getType() == Context.OverloadTy); 9894 9895 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9896 OverloadExpr *OvlExpr = Ovl.Expression; 9897 9898 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9899 IEnd = OvlExpr->decls_end(); 9900 I != IEnd; ++I) { 9901 if (FunctionTemplateDecl *FunTmpl = 9902 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9903 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 9904 TakingAddress); 9905 } else if (FunctionDecl *Fun 9906 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9907 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 9908 } 9909 } 9910 } 9911 9912 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9913 /// "lead" diagnostic; it will be given two arguments, the source and 9914 /// target types of the conversion. 9915 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9916 Sema &S, 9917 SourceLocation CaretLoc, 9918 const PartialDiagnostic &PDiag) const { 9919 S.Diag(CaretLoc, PDiag) 9920 << Ambiguous.getFromType() << Ambiguous.getToType(); 9921 // FIXME: The note limiting machinery is borrowed from 9922 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9923 // refactoring here. 9924 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9925 unsigned CandsShown = 0; 9926 AmbiguousConversionSequence::const_iterator I, E; 9927 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9928 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9929 break; 9930 ++CandsShown; 9931 S.NoteOverloadCandidate(I->first, I->second); 9932 } 9933 if (I != E) 9934 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9935 } 9936 9937 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9938 unsigned I, bool TakingCandidateAddress) { 9939 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9940 assert(Conv.isBad()); 9941 assert(Cand->Function && "for now, candidate must be a function"); 9942 FunctionDecl *Fn = Cand->Function; 9943 9944 // There's a conversion slot for the object argument if this is a 9945 // non-constructor method. Note that 'I' corresponds the 9946 // conversion-slot index. 9947 bool isObjectArgument = false; 9948 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9949 if (I == 0) 9950 isObjectArgument = true; 9951 else 9952 I--; 9953 } 9954 9955 std::string FnDesc; 9956 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9957 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 9958 FnDesc); 9959 9960 Expr *FromExpr = Conv.Bad.FromExpr; 9961 QualType FromTy = Conv.Bad.getFromType(); 9962 QualType ToTy = Conv.Bad.getToType(); 9963 9964 if (FromTy == S.Context.OverloadTy) { 9965 assert(FromExpr && "overload set argument came from implicit argument?"); 9966 Expr *E = FromExpr->IgnoreParens(); 9967 if (isa<UnaryOperator>(E)) 9968 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9969 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9970 9971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9972 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9973 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9974 << Name << I + 1; 9975 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9976 return; 9977 } 9978 9979 // Do some hand-waving analysis to see if the non-viability is due 9980 // to a qualifier mismatch. 9981 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9982 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9983 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9984 CToTy = RT->getPointeeType(); 9985 else { 9986 // TODO: detect and diagnose the full richness of const mismatches. 9987 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9988 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9989 CFromTy = FromPT->getPointeeType(); 9990 CToTy = ToPT->getPointeeType(); 9991 } 9992 } 9993 9994 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9995 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9996 Qualifiers FromQs = CFromTy.getQualifiers(); 9997 Qualifiers ToQs = CToTy.getQualifiers(); 9998 9999 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10000 if (isObjectArgument) 10001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10002 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10003 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10004 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10005 else 10006 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10007 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10008 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10009 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10010 << ToTy->isReferenceType() << I + 1; 10011 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10012 return; 10013 } 10014 10015 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10016 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10017 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10018 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10019 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10020 << (unsigned)isObjectArgument << I + 1; 10021 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10022 return; 10023 } 10024 10025 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10027 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10028 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10029 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10030 << (unsigned)isObjectArgument << I + 1; 10031 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10032 return; 10033 } 10034 10035 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10037 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10038 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10039 << FromQs.hasUnaligned() << I + 1; 10040 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10041 return; 10042 } 10043 10044 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10045 assert(CVR && "unexpected qualifiers mismatch"); 10046 10047 if (isObjectArgument) { 10048 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10049 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10050 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10051 << (CVR - 1); 10052 } else { 10053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10054 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10055 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10056 << (CVR - 1) << I + 1; 10057 } 10058 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10059 return; 10060 } 10061 10062 // Special diagnostic for failure to convert an initializer list, since 10063 // telling the user that it has type void is not useful. 10064 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10065 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10066 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10067 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10068 << ToTy << (unsigned)isObjectArgument << I + 1; 10069 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10070 return; 10071 } 10072 10073 // Diagnose references or pointers to incomplete types differently, 10074 // since it's far from impossible that the incompleteness triggered 10075 // the failure. 10076 QualType TempFromTy = FromTy.getNonReferenceType(); 10077 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10078 TempFromTy = PTy->getPointeeType(); 10079 if (TempFromTy->isIncompleteType()) { 10080 // Emit the generic diagnostic and, optionally, add the hints to it. 10081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10082 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10084 << ToTy << (unsigned)isObjectArgument << I + 1 10085 << (unsigned)(Cand->Fix.Kind); 10086 10087 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10088 return; 10089 } 10090 10091 // Diagnose base -> derived pointer conversions. 10092 unsigned BaseToDerivedConversion = 0; 10093 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10094 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10095 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10096 FromPtrTy->getPointeeType()) && 10097 !FromPtrTy->getPointeeType()->isIncompleteType() && 10098 !ToPtrTy->getPointeeType()->isIncompleteType() && 10099 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10100 FromPtrTy->getPointeeType())) 10101 BaseToDerivedConversion = 1; 10102 } 10103 } else if (const ObjCObjectPointerType *FromPtrTy 10104 = FromTy->getAs<ObjCObjectPointerType>()) { 10105 if (const ObjCObjectPointerType *ToPtrTy 10106 = ToTy->getAs<ObjCObjectPointerType>()) 10107 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10108 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10109 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10110 FromPtrTy->getPointeeType()) && 10111 FromIface->isSuperClassOf(ToIface)) 10112 BaseToDerivedConversion = 2; 10113 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10114 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10115 !FromTy->isIncompleteType() && 10116 !ToRefTy->getPointeeType()->isIncompleteType() && 10117 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10118 BaseToDerivedConversion = 3; 10119 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10120 ToTy.getNonReferenceType().getCanonicalType() == 10121 FromTy.getNonReferenceType().getCanonicalType()) { 10122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10123 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10124 << (unsigned)isObjectArgument << I + 1 10125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10126 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10127 return; 10128 } 10129 } 10130 10131 if (BaseToDerivedConversion) { 10132 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10133 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10134 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10135 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10136 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10137 return; 10138 } 10139 10140 if (isa<ObjCObjectPointerType>(CFromTy) && 10141 isa<PointerType>(CToTy)) { 10142 Qualifiers FromQs = CFromTy.getQualifiers(); 10143 Qualifiers ToQs = CToTy.getQualifiers(); 10144 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10146 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10147 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10148 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10149 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10150 return; 10151 } 10152 } 10153 10154 if (TakingCandidateAddress && 10155 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10156 return; 10157 10158 // Emit the generic diagnostic and, optionally, add the hints to it. 10159 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10160 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10161 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10162 << ToTy << (unsigned)isObjectArgument << I + 1 10163 << (unsigned)(Cand->Fix.Kind); 10164 10165 // If we can fix the conversion, suggest the FixIts. 10166 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10167 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10168 FDiag << *HI; 10169 S.Diag(Fn->getLocation(), FDiag); 10170 10171 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10172 } 10173 10174 /// Additional arity mismatch diagnosis specific to a function overload 10175 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10176 /// over a candidate in any candidate set. 10177 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10178 unsigned NumArgs) { 10179 FunctionDecl *Fn = Cand->Function; 10180 unsigned MinParams = Fn->getMinRequiredArguments(); 10181 10182 // With invalid overloaded operators, it's possible that we think we 10183 // have an arity mismatch when in fact it looks like we have the 10184 // right number of arguments, because only overloaded operators have 10185 // the weird behavior of overloading member and non-member functions. 10186 // Just don't report anything. 10187 if (Fn->isInvalidDecl() && 10188 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10189 return true; 10190 10191 if (NumArgs < MinParams) { 10192 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10193 (Cand->FailureKind == ovl_fail_bad_deduction && 10194 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10195 } else { 10196 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10197 (Cand->FailureKind == ovl_fail_bad_deduction && 10198 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10199 } 10200 10201 return false; 10202 } 10203 10204 /// General arity mismatch diagnosis over a candidate in a candidate set. 10205 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10206 unsigned NumFormalArgs) { 10207 assert(isa<FunctionDecl>(D) && 10208 "The templated declaration should at least be a function" 10209 " when diagnosing bad template argument deduction due to too many" 10210 " or too few arguments"); 10211 10212 FunctionDecl *Fn = cast<FunctionDecl>(D); 10213 10214 // TODO: treat calls to a missing default constructor as a special case 10215 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 10216 unsigned MinParams = Fn->getMinRequiredArguments(); 10217 10218 // at least / at most / exactly 10219 unsigned mode, modeCount; 10220 if (NumFormalArgs < MinParams) { 10221 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10222 FnTy->isTemplateVariadic()) 10223 mode = 0; // "at least" 10224 else 10225 mode = 2; // "exactly" 10226 modeCount = MinParams; 10227 } else { 10228 if (MinParams != FnTy->getNumParams()) 10229 mode = 1; // "at most" 10230 else 10231 mode = 2; // "exactly" 10232 modeCount = FnTy->getNumParams(); 10233 } 10234 10235 std::string Description; 10236 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10237 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10238 10239 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10241 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10242 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10243 else 10244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10245 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10246 << Description << mode << modeCount << NumFormalArgs; 10247 10248 MaybeEmitInheritedConstructorNote(S, Found); 10249 } 10250 10251 /// Arity mismatch diagnosis specific to a function overload candidate. 10252 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10253 unsigned NumFormalArgs) { 10254 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10255 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10256 } 10257 10258 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10259 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10260 return TD; 10261 llvm_unreachable("Unsupported: Getting the described template declaration" 10262 " for bad deduction diagnosis"); 10263 } 10264 10265 /// Diagnose a failed template-argument deduction. 10266 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10267 DeductionFailureInfo &DeductionFailure, 10268 unsigned NumArgs, 10269 bool TakingCandidateAddress) { 10270 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10271 NamedDecl *ParamD; 10272 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10273 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10274 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10275 switch (DeductionFailure.Result) { 10276 case Sema::TDK_Success: 10277 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10278 10279 case Sema::TDK_Incomplete: { 10280 assert(ParamD && "no parameter found for incomplete deduction result"); 10281 S.Diag(Templated->getLocation(), 10282 diag::note_ovl_candidate_incomplete_deduction) 10283 << ParamD->getDeclName(); 10284 MaybeEmitInheritedConstructorNote(S, Found); 10285 return; 10286 } 10287 10288 case Sema::TDK_IncompletePack: { 10289 assert(ParamD && "no parameter found for incomplete deduction result"); 10290 S.Diag(Templated->getLocation(), 10291 diag::note_ovl_candidate_incomplete_deduction_pack) 10292 << ParamD->getDeclName() 10293 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10294 << *DeductionFailure.getFirstArg(); 10295 MaybeEmitInheritedConstructorNote(S, Found); 10296 return; 10297 } 10298 10299 case Sema::TDK_Underqualified: { 10300 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10301 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10302 10303 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10304 10305 // Param will have been canonicalized, but it should just be a 10306 // qualified version of ParamD, so move the qualifiers to that. 10307 QualifierCollector Qs; 10308 Qs.strip(Param); 10309 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10310 assert(S.Context.hasSameType(Param, NonCanonParam)); 10311 10312 // Arg has also been canonicalized, but there's nothing we can do 10313 // about that. It also doesn't matter as much, because it won't 10314 // have any template parameters in it (because deduction isn't 10315 // done on dependent types). 10316 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10317 10318 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10319 << ParamD->getDeclName() << Arg << NonCanonParam; 10320 MaybeEmitInheritedConstructorNote(S, Found); 10321 return; 10322 } 10323 10324 case Sema::TDK_Inconsistent: { 10325 assert(ParamD && "no parameter found for inconsistent deduction result"); 10326 int which = 0; 10327 if (isa<TemplateTypeParmDecl>(ParamD)) 10328 which = 0; 10329 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10330 // Deduction might have failed because we deduced arguments of two 10331 // different types for a non-type template parameter. 10332 // FIXME: Use a different TDK value for this. 10333 QualType T1 = 10334 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10335 QualType T2 = 10336 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10337 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10338 S.Diag(Templated->getLocation(), 10339 diag::note_ovl_candidate_inconsistent_deduction_types) 10340 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10341 << *DeductionFailure.getSecondArg() << T2; 10342 MaybeEmitInheritedConstructorNote(S, Found); 10343 return; 10344 } 10345 10346 which = 1; 10347 } else { 10348 which = 2; 10349 } 10350 10351 S.Diag(Templated->getLocation(), 10352 diag::note_ovl_candidate_inconsistent_deduction) 10353 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10354 << *DeductionFailure.getSecondArg(); 10355 MaybeEmitInheritedConstructorNote(S, Found); 10356 return; 10357 } 10358 10359 case Sema::TDK_InvalidExplicitArguments: 10360 assert(ParamD && "no parameter found for invalid explicit arguments"); 10361 if (ParamD->getDeclName()) 10362 S.Diag(Templated->getLocation(), 10363 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10364 << ParamD->getDeclName(); 10365 else { 10366 int index = 0; 10367 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10368 index = TTP->getIndex(); 10369 else if (NonTypeTemplateParmDecl *NTTP 10370 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10371 index = NTTP->getIndex(); 10372 else 10373 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10374 S.Diag(Templated->getLocation(), 10375 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10376 << (index + 1); 10377 } 10378 MaybeEmitInheritedConstructorNote(S, Found); 10379 return; 10380 10381 case Sema::TDK_ConstraintsNotSatisfied: { 10382 // Format the template argument list into the argument string. 10383 SmallString<128> TemplateArgString; 10384 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10385 TemplateArgString = " "; 10386 TemplateArgString += S.getTemplateArgumentBindingsText( 10387 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10388 S.Diag(Templated->getLocation(), 10389 diag::note_ovl_candidate_unsatisfied_constraints) 10390 << TemplateArgString; 10391 10392 S.DiagnoseUnsatisfiedConstraint( 10393 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10394 return; 10395 } 10396 case Sema::TDK_TooManyArguments: 10397 case Sema::TDK_TooFewArguments: 10398 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10399 return; 10400 10401 case Sema::TDK_InstantiationDepth: 10402 S.Diag(Templated->getLocation(), 10403 diag::note_ovl_candidate_instantiation_depth); 10404 MaybeEmitInheritedConstructorNote(S, Found); 10405 return; 10406 10407 case Sema::TDK_SubstitutionFailure: { 10408 // Format the template argument list into the argument string. 10409 SmallString<128> TemplateArgString; 10410 if (TemplateArgumentList *Args = 10411 DeductionFailure.getTemplateArgumentList()) { 10412 TemplateArgString = " "; 10413 TemplateArgString += S.getTemplateArgumentBindingsText( 10414 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10415 } 10416 10417 // If this candidate was disabled by enable_if, say so. 10418 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10419 if (PDiag && PDiag->second.getDiagID() == 10420 diag::err_typename_nested_not_found_enable_if) { 10421 // FIXME: Use the source range of the condition, and the fully-qualified 10422 // name of the enable_if template. These are both present in PDiag. 10423 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10424 << "'enable_if'" << TemplateArgString; 10425 return; 10426 } 10427 10428 // We found a specific requirement that disabled the enable_if. 10429 if (PDiag && PDiag->second.getDiagID() == 10430 diag::err_typename_nested_not_found_requirement) { 10431 S.Diag(Templated->getLocation(), 10432 diag::note_ovl_candidate_disabled_by_requirement) 10433 << PDiag->second.getStringArg(0) << TemplateArgString; 10434 return; 10435 } 10436 10437 // Format the SFINAE diagnostic into the argument string. 10438 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10439 // formatted message in another diagnostic. 10440 SmallString<128> SFINAEArgString; 10441 SourceRange R; 10442 if (PDiag) { 10443 SFINAEArgString = ": "; 10444 R = SourceRange(PDiag->first, PDiag->first); 10445 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10446 } 10447 10448 S.Diag(Templated->getLocation(), 10449 diag::note_ovl_candidate_substitution_failure) 10450 << TemplateArgString << SFINAEArgString << R; 10451 MaybeEmitInheritedConstructorNote(S, Found); 10452 return; 10453 } 10454 10455 case Sema::TDK_DeducedMismatch: 10456 case Sema::TDK_DeducedMismatchNested: { 10457 // Format the template argument list into the argument string. 10458 SmallString<128> TemplateArgString; 10459 if (TemplateArgumentList *Args = 10460 DeductionFailure.getTemplateArgumentList()) { 10461 TemplateArgString = " "; 10462 TemplateArgString += S.getTemplateArgumentBindingsText( 10463 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10464 } 10465 10466 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10467 << (*DeductionFailure.getCallArgIndex() + 1) 10468 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10469 << TemplateArgString 10470 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10471 break; 10472 } 10473 10474 case Sema::TDK_NonDeducedMismatch: { 10475 // FIXME: Provide a source location to indicate what we couldn't match. 10476 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10477 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10478 if (FirstTA.getKind() == TemplateArgument::Template && 10479 SecondTA.getKind() == TemplateArgument::Template) { 10480 TemplateName FirstTN = FirstTA.getAsTemplate(); 10481 TemplateName SecondTN = SecondTA.getAsTemplate(); 10482 if (FirstTN.getKind() == TemplateName::Template && 10483 SecondTN.getKind() == TemplateName::Template) { 10484 if (FirstTN.getAsTemplateDecl()->getName() == 10485 SecondTN.getAsTemplateDecl()->getName()) { 10486 // FIXME: This fixes a bad diagnostic where both templates are named 10487 // the same. This particular case is a bit difficult since: 10488 // 1) It is passed as a string to the diagnostic printer. 10489 // 2) The diagnostic printer only attempts to find a better 10490 // name for types, not decls. 10491 // Ideally, this should folded into the diagnostic printer. 10492 S.Diag(Templated->getLocation(), 10493 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10494 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10495 return; 10496 } 10497 } 10498 } 10499 10500 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10501 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10502 return; 10503 10504 // FIXME: For generic lambda parameters, check if the function is a lambda 10505 // call operator, and if so, emit a prettier and more informative 10506 // diagnostic that mentions 'auto' and lambda in addition to 10507 // (or instead of?) the canonical template type parameters. 10508 S.Diag(Templated->getLocation(), 10509 diag::note_ovl_candidate_non_deduced_mismatch) 10510 << FirstTA << SecondTA; 10511 return; 10512 } 10513 // TODO: diagnose these individually, then kill off 10514 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10515 case Sema::TDK_MiscellaneousDeductionFailure: 10516 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10517 MaybeEmitInheritedConstructorNote(S, Found); 10518 return; 10519 case Sema::TDK_CUDATargetMismatch: 10520 S.Diag(Templated->getLocation(), 10521 diag::note_cuda_ovl_candidate_target_mismatch); 10522 return; 10523 } 10524 } 10525 10526 /// Diagnose a failed template-argument deduction, for function calls. 10527 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10528 unsigned NumArgs, 10529 bool TakingCandidateAddress) { 10530 unsigned TDK = Cand->DeductionFailure.Result; 10531 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10532 if (CheckArityMismatch(S, Cand, NumArgs)) 10533 return; 10534 } 10535 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10536 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10537 } 10538 10539 /// CUDA: diagnose an invalid call across targets. 10540 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10541 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10542 FunctionDecl *Callee = Cand->Function; 10543 10544 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10545 CalleeTarget = S.IdentifyCUDATarget(Callee); 10546 10547 std::string FnDesc; 10548 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10549 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10550 Cand->getRewriteKind(), FnDesc); 10551 10552 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10553 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10554 << FnDesc /* Ignored */ 10555 << CalleeTarget << CallerTarget; 10556 10557 // This could be an implicit constructor for which we could not infer the 10558 // target due to a collsion. Diagnose that case. 10559 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10560 if (Meth != nullptr && Meth->isImplicit()) { 10561 CXXRecordDecl *ParentClass = Meth->getParent(); 10562 Sema::CXXSpecialMember CSM; 10563 10564 switch (FnKindPair.first) { 10565 default: 10566 return; 10567 case oc_implicit_default_constructor: 10568 CSM = Sema::CXXDefaultConstructor; 10569 break; 10570 case oc_implicit_copy_constructor: 10571 CSM = Sema::CXXCopyConstructor; 10572 break; 10573 case oc_implicit_move_constructor: 10574 CSM = Sema::CXXMoveConstructor; 10575 break; 10576 case oc_implicit_copy_assignment: 10577 CSM = Sema::CXXCopyAssignment; 10578 break; 10579 case oc_implicit_move_assignment: 10580 CSM = Sema::CXXMoveAssignment; 10581 break; 10582 }; 10583 10584 bool ConstRHS = false; 10585 if (Meth->getNumParams()) { 10586 if (const ReferenceType *RT = 10587 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10588 ConstRHS = RT->getPointeeType().isConstQualified(); 10589 } 10590 } 10591 10592 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10593 /* ConstRHS */ ConstRHS, 10594 /* Diagnose */ true); 10595 } 10596 } 10597 10598 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10599 FunctionDecl *Callee = Cand->Function; 10600 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10601 10602 S.Diag(Callee->getLocation(), 10603 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10604 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10605 } 10606 10607 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10608 ExplicitSpecifier ES; 10609 const char *DeclName; 10610 switch (Cand->Function->getDeclKind()) { 10611 case Decl::Kind::CXXConstructor: 10612 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10613 DeclName = "constructor"; 10614 break; 10615 case Decl::Kind::CXXConversion: 10616 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10617 DeclName = "conversion operator"; 10618 break; 10619 case Decl::Kind::CXXDeductionGuide: 10620 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10621 DeclName = "deductiong guide"; 10622 break; 10623 default: 10624 llvm_unreachable("invalid Decl"); 10625 } 10626 assert(ES.getExpr() && "null expression should be handled before"); 10627 S.Diag(Cand->Function->getLocation(), 10628 diag::note_ovl_candidate_explicit_forbidden) 10629 << DeclName; 10630 S.Diag(ES.getExpr()->getBeginLoc(), 10631 diag::note_explicit_bool_resolved_to_true); 10632 } 10633 10634 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10635 FunctionDecl *Callee = Cand->Function; 10636 10637 S.Diag(Callee->getLocation(), 10638 diag::note_ovl_candidate_disabled_by_extension) 10639 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10640 } 10641 10642 /// Generates a 'note' diagnostic for an overload candidate. We've 10643 /// already generated a primary error at the call site. 10644 /// 10645 /// It really does need to be a single diagnostic with its caret 10646 /// pointed at the candidate declaration. Yes, this creates some 10647 /// major challenges of technical writing. Yes, this makes pointing 10648 /// out problems with specific arguments quite awkward. It's still 10649 /// better than generating twenty screens of text for every failed 10650 /// overload. 10651 /// 10652 /// It would be great to be able to express per-candidate problems 10653 /// more richly for those diagnostic clients that cared, but we'd 10654 /// still have to be just as careful with the default diagnostics. 10655 /// \param CtorDestAS Addr space of object being constructed (for ctor 10656 /// candidates only). 10657 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10658 unsigned NumArgs, 10659 bool TakingCandidateAddress, 10660 LangAS CtorDestAS = LangAS::Default) { 10661 FunctionDecl *Fn = Cand->Function; 10662 10663 // Note deleted candidates, but only if they're viable. 10664 if (Cand->Viable) { 10665 if (Fn->isDeleted()) { 10666 std::string FnDesc; 10667 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10668 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10669 Cand->getRewriteKind(), FnDesc); 10670 10671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10672 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10673 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10674 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10675 return; 10676 } 10677 10678 // We don't really have anything else to say about viable candidates. 10679 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10680 return; 10681 } 10682 10683 switch (Cand->FailureKind) { 10684 case ovl_fail_too_many_arguments: 10685 case ovl_fail_too_few_arguments: 10686 return DiagnoseArityMismatch(S, Cand, NumArgs); 10687 10688 case ovl_fail_bad_deduction: 10689 return DiagnoseBadDeduction(S, Cand, NumArgs, 10690 TakingCandidateAddress); 10691 10692 case ovl_fail_illegal_constructor: { 10693 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10694 << (Fn->getPrimaryTemplate() ? 1 : 0); 10695 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10696 return; 10697 } 10698 10699 case ovl_fail_object_addrspace_mismatch: { 10700 Qualifiers QualsForPrinting; 10701 QualsForPrinting.setAddressSpace(CtorDestAS); 10702 S.Diag(Fn->getLocation(), 10703 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10704 << QualsForPrinting; 10705 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10706 return; 10707 } 10708 10709 case ovl_fail_trivial_conversion: 10710 case ovl_fail_bad_final_conversion: 10711 case ovl_fail_final_conversion_not_exact: 10712 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10713 10714 case ovl_fail_bad_conversion: { 10715 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10716 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10717 if (Cand->Conversions[I].isBad()) 10718 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10719 10720 // FIXME: this currently happens when we're called from SemaInit 10721 // when user-conversion overload fails. Figure out how to handle 10722 // those conditions and diagnose them well. 10723 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10724 } 10725 10726 case ovl_fail_bad_target: 10727 return DiagnoseBadTarget(S, Cand); 10728 10729 case ovl_fail_enable_if: 10730 return DiagnoseFailedEnableIfAttr(S, Cand); 10731 10732 case ovl_fail_explicit_resolved: 10733 return DiagnoseFailedExplicitSpec(S, Cand); 10734 10735 case ovl_fail_ext_disabled: 10736 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10737 10738 case ovl_fail_inhctor_slice: 10739 // It's generally not interesting to note copy/move constructors here. 10740 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10741 return; 10742 S.Diag(Fn->getLocation(), 10743 diag::note_ovl_candidate_inherited_constructor_slice) 10744 << (Fn->getPrimaryTemplate() ? 1 : 0) 10745 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10746 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10747 return; 10748 10749 case ovl_fail_addr_not_available: { 10750 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10751 (void)Available; 10752 assert(!Available); 10753 break; 10754 } 10755 case ovl_non_default_multiversion_function: 10756 // Do nothing, these should simply be ignored. 10757 break; 10758 } 10759 } 10760 10761 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10762 // Desugar the type of the surrogate down to a function type, 10763 // retaining as many typedefs as possible while still showing 10764 // the function type (and, therefore, its parameter types). 10765 QualType FnType = Cand->Surrogate->getConversionType(); 10766 bool isLValueReference = false; 10767 bool isRValueReference = false; 10768 bool isPointer = false; 10769 if (const LValueReferenceType *FnTypeRef = 10770 FnType->getAs<LValueReferenceType>()) { 10771 FnType = FnTypeRef->getPointeeType(); 10772 isLValueReference = true; 10773 } else if (const RValueReferenceType *FnTypeRef = 10774 FnType->getAs<RValueReferenceType>()) { 10775 FnType = FnTypeRef->getPointeeType(); 10776 isRValueReference = true; 10777 } 10778 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10779 FnType = FnTypePtr->getPointeeType(); 10780 isPointer = true; 10781 } 10782 // Desugar down to a function type. 10783 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10784 // Reconstruct the pointer/reference as appropriate. 10785 if (isPointer) FnType = S.Context.getPointerType(FnType); 10786 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10787 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10788 10789 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10790 << FnType; 10791 } 10792 10793 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10794 SourceLocation OpLoc, 10795 OverloadCandidate *Cand) { 10796 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10797 std::string TypeStr("operator"); 10798 TypeStr += Opc; 10799 TypeStr += "("; 10800 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10801 if (Cand->Conversions.size() == 1) { 10802 TypeStr += ")"; 10803 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10804 } else { 10805 TypeStr += ", "; 10806 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10807 TypeStr += ")"; 10808 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10809 } 10810 } 10811 10812 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10813 OverloadCandidate *Cand) { 10814 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10815 if (ICS.isBad()) break; // all meaningless after first invalid 10816 if (!ICS.isAmbiguous()) continue; 10817 10818 ICS.DiagnoseAmbiguousConversion( 10819 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10820 } 10821 } 10822 10823 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10824 if (Cand->Function) 10825 return Cand->Function->getLocation(); 10826 if (Cand->IsSurrogate) 10827 return Cand->Surrogate->getLocation(); 10828 return SourceLocation(); 10829 } 10830 10831 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10832 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10833 case Sema::TDK_Success: 10834 case Sema::TDK_NonDependentConversionFailure: 10835 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10836 10837 case Sema::TDK_Invalid: 10838 case Sema::TDK_Incomplete: 10839 case Sema::TDK_IncompletePack: 10840 return 1; 10841 10842 case Sema::TDK_Underqualified: 10843 case Sema::TDK_Inconsistent: 10844 return 2; 10845 10846 case Sema::TDK_SubstitutionFailure: 10847 case Sema::TDK_DeducedMismatch: 10848 case Sema::TDK_ConstraintsNotSatisfied: 10849 case Sema::TDK_DeducedMismatchNested: 10850 case Sema::TDK_NonDeducedMismatch: 10851 case Sema::TDK_MiscellaneousDeductionFailure: 10852 case Sema::TDK_CUDATargetMismatch: 10853 return 3; 10854 10855 case Sema::TDK_InstantiationDepth: 10856 return 4; 10857 10858 case Sema::TDK_InvalidExplicitArguments: 10859 return 5; 10860 10861 case Sema::TDK_TooManyArguments: 10862 case Sema::TDK_TooFewArguments: 10863 return 6; 10864 } 10865 llvm_unreachable("Unhandled deduction result"); 10866 } 10867 10868 namespace { 10869 struct CompareOverloadCandidatesForDisplay { 10870 Sema &S; 10871 SourceLocation Loc; 10872 size_t NumArgs; 10873 OverloadCandidateSet::CandidateSetKind CSK; 10874 10875 CompareOverloadCandidatesForDisplay( 10876 Sema &S, SourceLocation Loc, size_t NArgs, 10877 OverloadCandidateSet::CandidateSetKind CSK) 10878 : S(S), NumArgs(NArgs), CSK(CSK) {} 10879 10880 bool operator()(const OverloadCandidate *L, 10881 const OverloadCandidate *R) { 10882 // Fast-path this check. 10883 if (L == R) return false; 10884 10885 // Order first by viability. 10886 if (L->Viable) { 10887 if (!R->Viable) return true; 10888 10889 // TODO: introduce a tri-valued comparison for overload 10890 // candidates. Would be more worthwhile if we had a sort 10891 // that could exploit it. 10892 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10893 return true; 10894 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10895 return false; 10896 } else if (R->Viable) 10897 return false; 10898 10899 assert(L->Viable == R->Viable); 10900 10901 // Criteria by which we can sort non-viable candidates: 10902 if (!L->Viable) { 10903 // 1. Arity mismatches come after other candidates. 10904 if (L->FailureKind == ovl_fail_too_many_arguments || 10905 L->FailureKind == ovl_fail_too_few_arguments) { 10906 if (R->FailureKind == ovl_fail_too_many_arguments || 10907 R->FailureKind == ovl_fail_too_few_arguments) { 10908 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10909 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10910 if (LDist == RDist) { 10911 if (L->FailureKind == R->FailureKind) 10912 // Sort non-surrogates before surrogates. 10913 return !L->IsSurrogate && R->IsSurrogate; 10914 // Sort candidates requiring fewer parameters than there were 10915 // arguments given after candidates requiring more parameters 10916 // than there were arguments given. 10917 return L->FailureKind == ovl_fail_too_many_arguments; 10918 } 10919 return LDist < RDist; 10920 } 10921 return false; 10922 } 10923 if (R->FailureKind == ovl_fail_too_many_arguments || 10924 R->FailureKind == ovl_fail_too_few_arguments) 10925 return true; 10926 10927 // 2. Bad conversions come first and are ordered by the number 10928 // of bad conversions and quality of good conversions. 10929 if (L->FailureKind == ovl_fail_bad_conversion) { 10930 if (R->FailureKind != ovl_fail_bad_conversion) 10931 return true; 10932 10933 // The conversion that can be fixed with a smaller number of changes, 10934 // comes first. 10935 unsigned numLFixes = L->Fix.NumConversionsFixed; 10936 unsigned numRFixes = R->Fix.NumConversionsFixed; 10937 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10938 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10939 if (numLFixes != numRFixes) { 10940 return numLFixes < numRFixes; 10941 } 10942 10943 // If there's any ordering between the defined conversions... 10944 // FIXME: this might not be transitive. 10945 assert(L->Conversions.size() == R->Conversions.size()); 10946 10947 int leftBetter = 0; 10948 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10949 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10950 switch (CompareImplicitConversionSequences(S, Loc, 10951 L->Conversions[I], 10952 R->Conversions[I])) { 10953 case ImplicitConversionSequence::Better: 10954 leftBetter++; 10955 break; 10956 10957 case ImplicitConversionSequence::Worse: 10958 leftBetter--; 10959 break; 10960 10961 case ImplicitConversionSequence::Indistinguishable: 10962 break; 10963 } 10964 } 10965 if (leftBetter > 0) return true; 10966 if (leftBetter < 0) return false; 10967 10968 } else if (R->FailureKind == ovl_fail_bad_conversion) 10969 return false; 10970 10971 if (L->FailureKind == ovl_fail_bad_deduction) { 10972 if (R->FailureKind != ovl_fail_bad_deduction) 10973 return true; 10974 10975 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10976 return RankDeductionFailure(L->DeductionFailure) 10977 < RankDeductionFailure(R->DeductionFailure); 10978 } else if (R->FailureKind == ovl_fail_bad_deduction) 10979 return false; 10980 10981 // TODO: others? 10982 } 10983 10984 // Sort everything else by location. 10985 SourceLocation LLoc = GetLocationForCandidate(L); 10986 SourceLocation RLoc = GetLocationForCandidate(R); 10987 10988 // Put candidates without locations (e.g. builtins) at the end. 10989 if (LLoc.isInvalid()) return false; 10990 if (RLoc.isInvalid()) return true; 10991 10992 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10993 } 10994 }; 10995 } 10996 10997 /// CompleteNonViableCandidate - Normally, overload resolution only 10998 /// computes up to the first bad conversion. Produces the FixIt set if 10999 /// possible. 11000 static void 11001 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11002 ArrayRef<Expr *> Args, 11003 OverloadCandidateSet::CandidateSetKind CSK) { 11004 assert(!Cand->Viable); 11005 11006 // Don't do anything on failures other than bad conversion. 11007 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 11008 11009 // We only want the FixIts if all the arguments can be corrected. 11010 bool Unfixable = false; 11011 // Use a implicit copy initialization to check conversion fixes. 11012 Cand->Fix.setConversionChecker(TryCopyInitialization); 11013 11014 // Attempt to fix the bad conversion. 11015 unsigned ConvCount = Cand->Conversions.size(); 11016 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11017 ++ConvIdx) { 11018 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11019 if (Cand->Conversions[ConvIdx].isInitialized() && 11020 Cand->Conversions[ConvIdx].isBad()) { 11021 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11022 break; 11023 } 11024 } 11025 11026 // FIXME: this should probably be preserved from the overload 11027 // operation somehow. 11028 bool SuppressUserConversions = false; 11029 11030 unsigned ConvIdx = 0; 11031 unsigned ArgIdx = 0; 11032 ArrayRef<QualType> ParamTypes; 11033 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11034 11035 if (Cand->IsSurrogate) { 11036 QualType ConvType 11037 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11038 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11039 ConvType = ConvPtrType->getPointeeType(); 11040 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11041 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11042 ConvIdx = 1; 11043 } else if (Cand->Function) { 11044 ParamTypes = 11045 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11046 if (isa<CXXMethodDecl>(Cand->Function) && 11047 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11048 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11049 ConvIdx = 1; 11050 if (CSK == OverloadCandidateSet::CSK_Operator && 11051 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11052 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11053 ArgIdx = 1; 11054 } 11055 } else { 11056 // Builtin operator. 11057 assert(ConvCount <= 3); 11058 ParamTypes = Cand->BuiltinParamTypes; 11059 } 11060 11061 // Fill in the rest of the conversions. 11062 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11063 ConvIdx != ConvCount; 11064 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11065 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11066 if (Cand->Conversions[ConvIdx].isInitialized()) { 11067 // We've already checked this conversion. 11068 } else if (ParamIdx < ParamTypes.size()) { 11069 if (ParamTypes[ParamIdx]->isDependentType()) 11070 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11071 Args[ArgIdx]->getType()); 11072 else { 11073 Cand->Conversions[ConvIdx] = 11074 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11075 SuppressUserConversions, 11076 /*InOverloadResolution=*/true, 11077 /*AllowObjCWritebackConversion=*/ 11078 S.getLangOpts().ObjCAutoRefCount); 11079 // Store the FixIt in the candidate if it exists. 11080 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11081 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11082 } 11083 } else 11084 Cand->Conversions[ConvIdx].setEllipsis(); 11085 } 11086 } 11087 11088 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11089 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11090 SourceLocation OpLoc, 11091 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11092 // Sort the candidates by viability and position. Sorting directly would 11093 // be prohibitive, so we make a set of pointers and sort those. 11094 SmallVector<OverloadCandidate*, 32> Cands; 11095 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11096 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11097 if (!Filter(*Cand)) 11098 continue; 11099 switch (OCD) { 11100 case OCD_AllCandidates: 11101 if (!Cand->Viable) { 11102 if (!Cand->Function && !Cand->IsSurrogate) { 11103 // This a non-viable builtin candidate. We do not, in general, 11104 // want to list every possible builtin candidate. 11105 continue; 11106 } 11107 CompleteNonViableCandidate(S, Cand, Args, Kind); 11108 } 11109 break; 11110 11111 case OCD_ViableCandidates: 11112 if (!Cand->Viable) 11113 continue; 11114 break; 11115 11116 case OCD_AmbiguousCandidates: 11117 if (!Cand->Best) 11118 continue; 11119 break; 11120 } 11121 11122 Cands.push_back(Cand); 11123 } 11124 11125 llvm::stable_sort( 11126 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11127 11128 return Cands; 11129 } 11130 11131 /// When overload resolution fails, prints diagnostic messages containing the 11132 /// candidates in the candidate set. 11133 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11134 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11135 StringRef Opc, SourceLocation OpLoc, 11136 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11137 11138 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11139 11140 S.Diag(PD.first, PD.second); 11141 11142 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11143 } 11144 11145 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11146 ArrayRef<OverloadCandidate *> Cands, 11147 StringRef Opc, SourceLocation OpLoc) { 11148 bool ReportedAmbiguousConversions = false; 11149 11150 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11151 unsigned CandsShown = 0; 11152 auto I = Cands.begin(), E = Cands.end(); 11153 for (; I != E; ++I) { 11154 OverloadCandidate *Cand = *I; 11155 11156 // Set an arbitrary limit on the number of candidate functions we'll spam 11157 // the user with. FIXME: This limit should depend on details of the 11158 // candidate list. 11159 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11160 break; 11161 } 11162 ++CandsShown; 11163 11164 if (Cand->Function) 11165 NoteFunctionCandidate(S, Cand, Args.size(), 11166 /*TakingCandidateAddress=*/false, DestAS); 11167 else if (Cand->IsSurrogate) 11168 NoteSurrogateCandidate(S, Cand); 11169 else { 11170 assert(Cand->Viable && 11171 "Non-viable built-in candidates are not added to Cands."); 11172 // Generally we only see ambiguities including viable builtin 11173 // operators if overload resolution got screwed up by an 11174 // ambiguous user-defined conversion. 11175 // 11176 // FIXME: It's quite possible for different conversions to see 11177 // different ambiguities, though. 11178 if (!ReportedAmbiguousConversions) { 11179 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11180 ReportedAmbiguousConversions = true; 11181 } 11182 11183 // If this is a viable builtin, print it. 11184 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11185 } 11186 } 11187 11188 if (I != E) 11189 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11190 } 11191 11192 static SourceLocation 11193 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11194 return Cand->Specialization ? Cand->Specialization->getLocation() 11195 : SourceLocation(); 11196 } 11197 11198 namespace { 11199 struct CompareTemplateSpecCandidatesForDisplay { 11200 Sema &S; 11201 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11202 11203 bool operator()(const TemplateSpecCandidate *L, 11204 const TemplateSpecCandidate *R) { 11205 // Fast-path this check. 11206 if (L == R) 11207 return false; 11208 11209 // Assuming that both candidates are not matches... 11210 11211 // Sort by the ranking of deduction failures. 11212 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11213 return RankDeductionFailure(L->DeductionFailure) < 11214 RankDeductionFailure(R->DeductionFailure); 11215 11216 // Sort everything else by location. 11217 SourceLocation LLoc = GetLocationForCandidate(L); 11218 SourceLocation RLoc = GetLocationForCandidate(R); 11219 11220 // Put candidates without locations (e.g. builtins) at the end. 11221 if (LLoc.isInvalid()) 11222 return false; 11223 if (RLoc.isInvalid()) 11224 return true; 11225 11226 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11227 } 11228 }; 11229 } 11230 11231 /// Diagnose a template argument deduction failure. 11232 /// We are treating these failures as overload failures due to bad 11233 /// deductions. 11234 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11235 bool ForTakingAddress) { 11236 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11237 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11238 } 11239 11240 void TemplateSpecCandidateSet::destroyCandidates() { 11241 for (iterator i = begin(), e = end(); i != e; ++i) { 11242 i->DeductionFailure.Destroy(); 11243 } 11244 } 11245 11246 void TemplateSpecCandidateSet::clear() { 11247 destroyCandidates(); 11248 Candidates.clear(); 11249 } 11250 11251 /// NoteCandidates - When no template specialization match is found, prints 11252 /// diagnostic messages containing the non-matching specializations that form 11253 /// the candidate set. 11254 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11255 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11256 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11257 // Sort the candidates by position (assuming no candidate is a match). 11258 // Sorting directly would be prohibitive, so we make a set of pointers 11259 // and sort those. 11260 SmallVector<TemplateSpecCandidate *, 32> Cands; 11261 Cands.reserve(size()); 11262 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11263 if (Cand->Specialization) 11264 Cands.push_back(Cand); 11265 // Otherwise, this is a non-matching builtin candidate. We do not, 11266 // in general, want to list every possible builtin candidate. 11267 } 11268 11269 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11270 11271 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11272 // for generalization purposes (?). 11273 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11274 11275 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11276 unsigned CandsShown = 0; 11277 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11278 TemplateSpecCandidate *Cand = *I; 11279 11280 // Set an arbitrary limit on the number of candidates we'll spam 11281 // the user with. FIXME: This limit should depend on details of the 11282 // candidate list. 11283 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11284 break; 11285 ++CandsShown; 11286 11287 assert(Cand->Specialization && 11288 "Non-matching built-in candidates are not added to Cands."); 11289 Cand->NoteDeductionFailure(S, ForTakingAddress); 11290 } 11291 11292 if (I != E) 11293 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11294 } 11295 11296 // [PossiblyAFunctionType] --> [Return] 11297 // NonFunctionType --> NonFunctionType 11298 // R (A) --> R(A) 11299 // R (*)(A) --> R (A) 11300 // R (&)(A) --> R (A) 11301 // R (S::*)(A) --> R (A) 11302 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11303 QualType Ret = PossiblyAFunctionType; 11304 if (const PointerType *ToTypePtr = 11305 PossiblyAFunctionType->getAs<PointerType>()) 11306 Ret = ToTypePtr->getPointeeType(); 11307 else if (const ReferenceType *ToTypeRef = 11308 PossiblyAFunctionType->getAs<ReferenceType>()) 11309 Ret = ToTypeRef->getPointeeType(); 11310 else if (const MemberPointerType *MemTypePtr = 11311 PossiblyAFunctionType->getAs<MemberPointerType>()) 11312 Ret = MemTypePtr->getPointeeType(); 11313 Ret = 11314 Context.getCanonicalType(Ret).getUnqualifiedType(); 11315 return Ret; 11316 } 11317 11318 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11319 bool Complain = true) { 11320 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11321 S.DeduceReturnType(FD, Loc, Complain)) 11322 return true; 11323 11324 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11325 if (S.getLangOpts().CPlusPlus17 && 11326 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11327 !S.ResolveExceptionSpec(Loc, FPT)) 11328 return true; 11329 11330 return false; 11331 } 11332 11333 namespace { 11334 // A helper class to help with address of function resolution 11335 // - allows us to avoid passing around all those ugly parameters 11336 class AddressOfFunctionResolver { 11337 Sema& S; 11338 Expr* SourceExpr; 11339 const QualType& TargetType; 11340 QualType TargetFunctionType; // Extracted function type from target type 11341 11342 bool Complain; 11343 //DeclAccessPair& ResultFunctionAccessPair; 11344 ASTContext& Context; 11345 11346 bool TargetTypeIsNonStaticMemberFunction; 11347 bool FoundNonTemplateFunction; 11348 bool StaticMemberFunctionFromBoundPointer; 11349 bool HasComplained; 11350 11351 OverloadExpr::FindResult OvlExprInfo; 11352 OverloadExpr *OvlExpr; 11353 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11354 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11355 TemplateSpecCandidateSet FailedCandidates; 11356 11357 public: 11358 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11359 const QualType &TargetType, bool Complain) 11360 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11361 Complain(Complain), Context(S.getASTContext()), 11362 TargetTypeIsNonStaticMemberFunction( 11363 !!TargetType->getAs<MemberPointerType>()), 11364 FoundNonTemplateFunction(false), 11365 StaticMemberFunctionFromBoundPointer(false), 11366 HasComplained(false), 11367 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11368 OvlExpr(OvlExprInfo.Expression), 11369 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11370 ExtractUnqualifiedFunctionTypeFromTargetType(); 11371 11372 if (TargetFunctionType->isFunctionType()) { 11373 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11374 if (!UME->isImplicitAccess() && 11375 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11376 StaticMemberFunctionFromBoundPointer = true; 11377 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11378 DeclAccessPair dap; 11379 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11380 OvlExpr, false, &dap)) { 11381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11382 if (!Method->isStatic()) { 11383 // If the target type is a non-function type and the function found 11384 // is a non-static member function, pretend as if that was the 11385 // target, it's the only possible type to end up with. 11386 TargetTypeIsNonStaticMemberFunction = true; 11387 11388 // And skip adding the function if its not in the proper form. 11389 // We'll diagnose this due to an empty set of functions. 11390 if (!OvlExprInfo.HasFormOfMemberPointer) 11391 return; 11392 } 11393 11394 Matches.push_back(std::make_pair(dap, Fn)); 11395 } 11396 return; 11397 } 11398 11399 if (OvlExpr->hasExplicitTemplateArgs()) 11400 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11401 11402 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11403 // C++ [over.over]p4: 11404 // If more than one function is selected, [...] 11405 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11406 if (FoundNonTemplateFunction) 11407 EliminateAllTemplateMatches(); 11408 else 11409 EliminateAllExceptMostSpecializedTemplate(); 11410 } 11411 } 11412 11413 if (S.getLangOpts().CUDA && Matches.size() > 1) 11414 EliminateSuboptimalCudaMatches(); 11415 } 11416 11417 bool hasComplained() const { return HasComplained; } 11418 11419 private: 11420 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11421 QualType Discard; 11422 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11423 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11424 } 11425 11426 /// \return true if A is considered a better overload candidate for the 11427 /// desired type than B. 11428 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11429 // If A doesn't have exactly the correct type, we don't want to classify it 11430 // as "better" than anything else. This way, the user is required to 11431 // disambiguate for us if there are multiple candidates and no exact match. 11432 return candidateHasExactlyCorrectType(A) && 11433 (!candidateHasExactlyCorrectType(B) || 11434 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11435 } 11436 11437 /// \return true if we were able to eliminate all but one overload candidate, 11438 /// false otherwise. 11439 bool eliminiateSuboptimalOverloadCandidates() { 11440 // Same algorithm as overload resolution -- one pass to pick the "best", 11441 // another pass to be sure that nothing is better than the best. 11442 auto Best = Matches.begin(); 11443 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11444 if (isBetterCandidate(I->second, Best->second)) 11445 Best = I; 11446 11447 const FunctionDecl *BestFn = Best->second; 11448 auto IsBestOrInferiorToBest = [this, BestFn]( 11449 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11450 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11451 }; 11452 11453 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11454 // option, so we can potentially give the user a better error 11455 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11456 return false; 11457 Matches[0] = *Best; 11458 Matches.resize(1); 11459 return true; 11460 } 11461 11462 bool isTargetTypeAFunction() const { 11463 return TargetFunctionType->isFunctionType(); 11464 } 11465 11466 // [ToType] [Return] 11467 11468 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11469 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11470 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11471 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11472 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11473 } 11474 11475 // return true if any matching specializations were found 11476 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11477 const DeclAccessPair& CurAccessFunPair) { 11478 if (CXXMethodDecl *Method 11479 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11480 // Skip non-static function templates when converting to pointer, and 11481 // static when converting to member pointer. 11482 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11483 return false; 11484 } 11485 else if (TargetTypeIsNonStaticMemberFunction) 11486 return false; 11487 11488 // C++ [over.over]p2: 11489 // If the name is a function template, template argument deduction is 11490 // done (14.8.2.2), and if the argument deduction succeeds, the 11491 // resulting template argument list is used to generate a single 11492 // function template specialization, which is added to the set of 11493 // overloaded functions considered. 11494 FunctionDecl *Specialization = nullptr; 11495 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11496 if (Sema::TemplateDeductionResult Result 11497 = S.DeduceTemplateArguments(FunctionTemplate, 11498 &OvlExplicitTemplateArgs, 11499 TargetFunctionType, Specialization, 11500 Info, /*IsAddressOfFunction*/true)) { 11501 // Make a note of the failed deduction for diagnostics. 11502 FailedCandidates.addCandidate() 11503 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11504 MakeDeductionFailureInfo(Context, Result, Info)); 11505 return false; 11506 } 11507 11508 // Template argument deduction ensures that we have an exact match or 11509 // compatible pointer-to-function arguments that would be adjusted by ICS. 11510 // This function template specicalization works. 11511 assert(S.isSameOrCompatibleFunctionType( 11512 Context.getCanonicalType(Specialization->getType()), 11513 Context.getCanonicalType(TargetFunctionType))); 11514 11515 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11516 return false; 11517 11518 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11519 return true; 11520 } 11521 11522 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11523 const DeclAccessPair& CurAccessFunPair) { 11524 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11525 // Skip non-static functions when converting to pointer, and static 11526 // when converting to member pointer. 11527 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11528 return false; 11529 } 11530 else if (TargetTypeIsNonStaticMemberFunction) 11531 return false; 11532 11533 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11534 if (S.getLangOpts().CUDA) 11535 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11536 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11537 return false; 11538 if (FunDecl->isMultiVersion()) { 11539 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11540 if (TA && !TA->isDefaultVersion()) 11541 return false; 11542 } 11543 11544 // If any candidate has a placeholder return type, trigger its deduction 11545 // now. 11546 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11547 Complain)) { 11548 HasComplained |= Complain; 11549 return false; 11550 } 11551 11552 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11553 return false; 11554 11555 // If we're in C, we need to support types that aren't exactly identical. 11556 if (!S.getLangOpts().CPlusPlus || 11557 candidateHasExactlyCorrectType(FunDecl)) { 11558 Matches.push_back(std::make_pair( 11559 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11560 FoundNonTemplateFunction = true; 11561 return true; 11562 } 11563 } 11564 11565 return false; 11566 } 11567 11568 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11569 bool Ret = false; 11570 11571 // If the overload expression doesn't have the form of a pointer to 11572 // member, don't try to convert it to a pointer-to-member type. 11573 if (IsInvalidFormOfPointerToMemberFunction()) 11574 return false; 11575 11576 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11577 E = OvlExpr->decls_end(); 11578 I != E; ++I) { 11579 // Look through any using declarations to find the underlying function. 11580 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11581 11582 // C++ [over.over]p3: 11583 // Non-member functions and static member functions match 11584 // targets of type "pointer-to-function" or "reference-to-function." 11585 // Nonstatic member functions match targets of 11586 // type "pointer-to-member-function." 11587 // Note that according to DR 247, the containing class does not matter. 11588 if (FunctionTemplateDecl *FunctionTemplate 11589 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11590 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11591 Ret = true; 11592 } 11593 // If we have explicit template arguments supplied, skip non-templates. 11594 else if (!OvlExpr->hasExplicitTemplateArgs() && 11595 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11596 Ret = true; 11597 } 11598 assert(Ret || Matches.empty()); 11599 return Ret; 11600 } 11601 11602 void EliminateAllExceptMostSpecializedTemplate() { 11603 // [...] and any given function template specialization F1 is 11604 // eliminated if the set contains a second function template 11605 // specialization whose function template is more specialized 11606 // than the function template of F1 according to the partial 11607 // ordering rules of 14.5.5.2. 11608 11609 // The algorithm specified above is quadratic. We instead use a 11610 // two-pass algorithm (similar to the one used to identify the 11611 // best viable function in an overload set) that identifies the 11612 // best function template (if it exists). 11613 11614 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11615 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11616 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11617 11618 // TODO: It looks like FailedCandidates does not serve much purpose 11619 // here, since the no_viable diagnostic has index 0. 11620 UnresolvedSetIterator Result = S.getMostSpecialized( 11621 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11622 SourceExpr->getBeginLoc(), S.PDiag(), 11623 S.PDiag(diag::err_addr_ovl_ambiguous) 11624 << Matches[0].second->getDeclName(), 11625 S.PDiag(diag::note_ovl_candidate) 11626 << (unsigned)oc_function << (unsigned)ocs_described_template, 11627 Complain, TargetFunctionType); 11628 11629 if (Result != MatchesCopy.end()) { 11630 // Make it the first and only element 11631 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11632 Matches[0].second = cast<FunctionDecl>(*Result); 11633 Matches.resize(1); 11634 } else 11635 HasComplained |= Complain; 11636 } 11637 11638 void EliminateAllTemplateMatches() { 11639 // [...] any function template specializations in the set are 11640 // eliminated if the set also contains a non-template function, [...] 11641 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11642 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11643 ++I; 11644 else { 11645 Matches[I] = Matches[--N]; 11646 Matches.resize(N); 11647 } 11648 } 11649 } 11650 11651 void EliminateSuboptimalCudaMatches() { 11652 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11653 } 11654 11655 public: 11656 void ComplainNoMatchesFound() const { 11657 assert(Matches.empty()); 11658 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11659 << OvlExpr->getName() << TargetFunctionType 11660 << OvlExpr->getSourceRange(); 11661 if (FailedCandidates.empty()) 11662 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11663 /*TakingAddress=*/true); 11664 else { 11665 // We have some deduction failure messages. Use them to diagnose 11666 // the function templates, and diagnose the non-template candidates 11667 // normally. 11668 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11669 IEnd = OvlExpr->decls_end(); 11670 I != IEnd; ++I) 11671 if (FunctionDecl *Fun = 11672 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11673 if (!functionHasPassObjectSizeParams(Fun)) 11674 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11675 /*TakingAddress=*/true); 11676 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11677 } 11678 } 11679 11680 bool IsInvalidFormOfPointerToMemberFunction() const { 11681 return TargetTypeIsNonStaticMemberFunction && 11682 !OvlExprInfo.HasFormOfMemberPointer; 11683 } 11684 11685 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11686 // TODO: Should we condition this on whether any functions might 11687 // have matched, or is it more appropriate to do that in callers? 11688 // TODO: a fixit wouldn't hurt. 11689 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11690 << TargetType << OvlExpr->getSourceRange(); 11691 } 11692 11693 bool IsStaticMemberFunctionFromBoundPointer() const { 11694 return StaticMemberFunctionFromBoundPointer; 11695 } 11696 11697 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11698 S.Diag(OvlExpr->getBeginLoc(), 11699 diag::err_invalid_form_pointer_member_function) 11700 << OvlExpr->getSourceRange(); 11701 } 11702 11703 void ComplainOfInvalidConversion() const { 11704 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11705 << OvlExpr->getName() << TargetType; 11706 } 11707 11708 void ComplainMultipleMatchesFound() const { 11709 assert(Matches.size() > 1); 11710 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11711 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11712 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11713 /*TakingAddress=*/true); 11714 } 11715 11716 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11717 11718 int getNumMatches() const { return Matches.size(); } 11719 11720 FunctionDecl* getMatchingFunctionDecl() const { 11721 if (Matches.size() != 1) return nullptr; 11722 return Matches[0].second; 11723 } 11724 11725 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11726 if (Matches.size() != 1) return nullptr; 11727 return &Matches[0].first; 11728 } 11729 }; 11730 } 11731 11732 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11733 /// an overloaded function (C++ [over.over]), where @p From is an 11734 /// expression with overloaded function type and @p ToType is the type 11735 /// we're trying to resolve to. For example: 11736 /// 11737 /// @code 11738 /// int f(double); 11739 /// int f(int); 11740 /// 11741 /// int (*pfd)(double) = f; // selects f(double) 11742 /// @endcode 11743 /// 11744 /// This routine returns the resulting FunctionDecl if it could be 11745 /// resolved, and NULL otherwise. When @p Complain is true, this 11746 /// routine will emit diagnostics if there is an error. 11747 FunctionDecl * 11748 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11749 QualType TargetType, 11750 bool Complain, 11751 DeclAccessPair &FoundResult, 11752 bool *pHadMultipleCandidates) { 11753 assert(AddressOfExpr->getType() == Context.OverloadTy); 11754 11755 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11756 Complain); 11757 int NumMatches = Resolver.getNumMatches(); 11758 FunctionDecl *Fn = nullptr; 11759 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11760 if (NumMatches == 0 && ShouldComplain) { 11761 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11762 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11763 else 11764 Resolver.ComplainNoMatchesFound(); 11765 } 11766 else if (NumMatches > 1 && ShouldComplain) 11767 Resolver.ComplainMultipleMatchesFound(); 11768 else if (NumMatches == 1) { 11769 Fn = Resolver.getMatchingFunctionDecl(); 11770 assert(Fn); 11771 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11772 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11773 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11774 if (Complain) { 11775 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11776 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11777 else 11778 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11779 } 11780 } 11781 11782 if (pHadMultipleCandidates) 11783 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11784 return Fn; 11785 } 11786 11787 /// Given an expression that refers to an overloaded function, try to 11788 /// resolve that function to a single function that can have its address taken. 11789 /// This will modify `Pair` iff it returns non-null. 11790 /// 11791 /// This routine can only realistically succeed if all but one candidates in the 11792 /// overload set for SrcExpr cannot have their addresses taken. 11793 FunctionDecl * 11794 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11795 DeclAccessPair &Pair) { 11796 OverloadExpr::FindResult R = OverloadExpr::find(E); 11797 OverloadExpr *Ovl = R.Expression; 11798 FunctionDecl *Result = nullptr; 11799 DeclAccessPair DAP; 11800 // Don't use the AddressOfResolver because we're specifically looking for 11801 // cases where we have one overload candidate that lacks 11802 // enable_if/pass_object_size/... 11803 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11804 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11805 if (!FD) 11806 return nullptr; 11807 11808 if (!checkAddressOfFunctionIsAvailable(FD)) 11809 continue; 11810 11811 // We have more than one result; quit. 11812 if (Result) 11813 return nullptr; 11814 DAP = I.getPair(); 11815 Result = FD; 11816 } 11817 11818 if (Result) 11819 Pair = DAP; 11820 return Result; 11821 } 11822 11823 /// Given an overloaded function, tries to turn it into a non-overloaded 11824 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11825 /// will perform access checks, diagnose the use of the resultant decl, and, if 11826 /// requested, potentially perform a function-to-pointer decay. 11827 /// 11828 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11829 /// Otherwise, returns true. This may emit diagnostics and return true. 11830 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11831 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11832 Expr *E = SrcExpr.get(); 11833 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11834 11835 DeclAccessPair DAP; 11836 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11837 if (!Found || Found->isCPUDispatchMultiVersion() || 11838 Found->isCPUSpecificMultiVersion()) 11839 return false; 11840 11841 // Emitting multiple diagnostics for a function that is both inaccessible and 11842 // unavailable is consistent with our behavior elsewhere. So, always check 11843 // for both. 11844 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11845 CheckAddressOfMemberAccess(E, DAP); 11846 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11847 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11848 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11849 else 11850 SrcExpr = Fixed; 11851 return true; 11852 } 11853 11854 /// Given an expression that refers to an overloaded function, try to 11855 /// resolve that overloaded function expression down to a single function. 11856 /// 11857 /// This routine can only resolve template-ids that refer to a single function 11858 /// template, where that template-id refers to a single template whose template 11859 /// arguments are either provided by the template-id or have defaults, 11860 /// as described in C++0x [temp.arg.explicit]p3. 11861 /// 11862 /// If no template-ids are found, no diagnostics are emitted and NULL is 11863 /// returned. 11864 FunctionDecl * 11865 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11866 bool Complain, 11867 DeclAccessPair *FoundResult) { 11868 // C++ [over.over]p1: 11869 // [...] [Note: any redundant set of parentheses surrounding the 11870 // overloaded function name is ignored (5.1). ] 11871 // C++ [over.over]p1: 11872 // [...] The overloaded function name can be preceded by the & 11873 // operator. 11874 11875 // If we didn't actually find any template-ids, we're done. 11876 if (!ovl->hasExplicitTemplateArgs()) 11877 return nullptr; 11878 11879 TemplateArgumentListInfo ExplicitTemplateArgs; 11880 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11881 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11882 11883 // Look through all of the overloaded functions, searching for one 11884 // whose type matches exactly. 11885 FunctionDecl *Matched = nullptr; 11886 for (UnresolvedSetIterator I = ovl->decls_begin(), 11887 E = ovl->decls_end(); I != E; ++I) { 11888 // C++0x [temp.arg.explicit]p3: 11889 // [...] In contexts where deduction is done and fails, or in contexts 11890 // where deduction is not done, if a template argument list is 11891 // specified and it, along with any default template arguments, 11892 // identifies a single function template specialization, then the 11893 // template-id is an lvalue for the function template specialization. 11894 FunctionTemplateDecl *FunctionTemplate 11895 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11896 11897 // C++ [over.over]p2: 11898 // If the name is a function template, template argument deduction is 11899 // done (14.8.2.2), and if the argument deduction succeeds, the 11900 // resulting template argument list is used to generate a single 11901 // function template specialization, which is added to the set of 11902 // overloaded functions considered. 11903 FunctionDecl *Specialization = nullptr; 11904 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11905 if (TemplateDeductionResult Result 11906 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11907 Specialization, Info, 11908 /*IsAddressOfFunction*/true)) { 11909 // Make a note of the failed deduction for diagnostics. 11910 // TODO: Actually use the failed-deduction info? 11911 FailedCandidates.addCandidate() 11912 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11913 MakeDeductionFailureInfo(Context, Result, Info)); 11914 continue; 11915 } 11916 11917 assert(Specialization && "no specialization and no error?"); 11918 11919 // Multiple matches; we can't resolve to a single declaration. 11920 if (Matched) { 11921 if (Complain) { 11922 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11923 << ovl->getName(); 11924 NoteAllOverloadCandidates(ovl); 11925 } 11926 return nullptr; 11927 } 11928 11929 Matched = Specialization; 11930 if (FoundResult) *FoundResult = I.getPair(); 11931 } 11932 11933 if (Matched && 11934 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11935 return nullptr; 11936 11937 return Matched; 11938 } 11939 11940 // Resolve and fix an overloaded expression that can be resolved 11941 // because it identifies a single function template specialization. 11942 // 11943 // Last three arguments should only be supplied if Complain = true 11944 // 11945 // Return true if it was logically possible to so resolve the 11946 // expression, regardless of whether or not it succeeded. Always 11947 // returns true if 'complain' is set. 11948 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11949 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11950 bool complain, SourceRange OpRangeForComplaining, 11951 QualType DestTypeForComplaining, 11952 unsigned DiagIDForComplaining) { 11953 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11954 11955 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11956 11957 DeclAccessPair found; 11958 ExprResult SingleFunctionExpression; 11959 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11960 ovl.Expression, /*complain*/ false, &found)) { 11961 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11962 SrcExpr = ExprError(); 11963 return true; 11964 } 11965 11966 // It is only correct to resolve to an instance method if we're 11967 // resolving a form that's permitted to be a pointer to member. 11968 // Otherwise we'll end up making a bound member expression, which 11969 // is illegal in all the contexts we resolve like this. 11970 if (!ovl.HasFormOfMemberPointer && 11971 isa<CXXMethodDecl>(fn) && 11972 cast<CXXMethodDecl>(fn)->isInstance()) { 11973 if (!complain) return false; 11974 11975 Diag(ovl.Expression->getExprLoc(), 11976 diag::err_bound_member_function) 11977 << 0 << ovl.Expression->getSourceRange(); 11978 11979 // TODO: I believe we only end up here if there's a mix of 11980 // static and non-static candidates (otherwise the expression 11981 // would have 'bound member' type, not 'overload' type). 11982 // Ideally we would note which candidate was chosen and why 11983 // the static candidates were rejected. 11984 SrcExpr = ExprError(); 11985 return true; 11986 } 11987 11988 // Fix the expression to refer to 'fn'. 11989 SingleFunctionExpression = 11990 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11991 11992 // If desired, do function-to-pointer decay. 11993 if (doFunctionPointerConverion) { 11994 SingleFunctionExpression = 11995 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11996 if (SingleFunctionExpression.isInvalid()) { 11997 SrcExpr = ExprError(); 11998 return true; 11999 } 12000 } 12001 } 12002 12003 if (!SingleFunctionExpression.isUsable()) { 12004 if (complain) { 12005 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12006 << ovl.Expression->getName() 12007 << DestTypeForComplaining 12008 << OpRangeForComplaining 12009 << ovl.Expression->getQualifierLoc().getSourceRange(); 12010 NoteAllOverloadCandidates(SrcExpr.get()); 12011 12012 SrcExpr = ExprError(); 12013 return true; 12014 } 12015 12016 return false; 12017 } 12018 12019 SrcExpr = SingleFunctionExpression; 12020 return true; 12021 } 12022 12023 /// Add a single candidate to the overload set. 12024 static void AddOverloadedCallCandidate(Sema &S, 12025 DeclAccessPair FoundDecl, 12026 TemplateArgumentListInfo *ExplicitTemplateArgs, 12027 ArrayRef<Expr *> Args, 12028 OverloadCandidateSet &CandidateSet, 12029 bool PartialOverloading, 12030 bool KnownValid) { 12031 NamedDecl *Callee = FoundDecl.getDecl(); 12032 if (isa<UsingShadowDecl>(Callee)) 12033 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12034 12035 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12036 if (ExplicitTemplateArgs) { 12037 assert(!KnownValid && "Explicit template arguments?"); 12038 return; 12039 } 12040 // Prevent ill-formed function decls to be added as overload candidates. 12041 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12042 return; 12043 12044 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12045 /*SuppressUserConversions=*/false, 12046 PartialOverloading); 12047 return; 12048 } 12049 12050 if (FunctionTemplateDecl *FuncTemplate 12051 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12052 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12053 ExplicitTemplateArgs, Args, CandidateSet, 12054 /*SuppressUserConversions=*/false, 12055 PartialOverloading); 12056 return; 12057 } 12058 12059 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12060 } 12061 12062 /// Add the overload candidates named by callee and/or found by argument 12063 /// dependent lookup to the given overload set. 12064 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12065 ArrayRef<Expr *> Args, 12066 OverloadCandidateSet &CandidateSet, 12067 bool PartialOverloading) { 12068 12069 #ifndef NDEBUG 12070 // Verify that ArgumentDependentLookup is consistent with the rules 12071 // in C++0x [basic.lookup.argdep]p3: 12072 // 12073 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12074 // and let Y be the lookup set produced by argument dependent 12075 // lookup (defined as follows). If X contains 12076 // 12077 // -- a declaration of a class member, or 12078 // 12079 // -- a block-scope function declaration that is not a 12080 // using-declaration, or 12081 // 12082 // -- a declaration that is neither a function or a function 12083 // template 12084 // 12085 // then Y is empty. 12086 12087 if (ULE->requiresADL()) { 12088 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12089 E = ULE->decls_end(); I != E; ++I) { 12090 assert(!(*I)->getDeclContext()->isRecord()); 12091 assert(isa<UsingShadowDecl>(*I) || 12092 !(*I)->getDeclContext()->isFunctionOrMethod()); 12093 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12094 } 12095 } 12096 #endif 12097 12098 // It would be nice to avoid this copy. 12099 TemplateArgumentListInfo TABuffer; 12100 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12101 if (ULE->hasExplicitTemplateArgs()) { 12102 ULE->copyTemplateArgumentsInto(TABuffer); 12103 ExplicitTemplateArgs = &TABuffer; 12104 } 12105 12106 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12107 E = ULE->decls_end(); I != E; ++I) 12108 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12109 CandidateSet, PartialOverloading, 12110 /*KnownValid*/ true); 12111 12112 if (ULE->requiresADL()) 12113 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12114 Args, ExplicitTemplateArgs, 12115 CandidateSet, PartialOverloading); 12116 } 12117 12118 /// Determine whether a declaration with the specified name could be moved into 12119 /// a different namespace. 12120 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12121 switch (Name.getCXXOverloadedOperator()) { 12122 case OO_New: case OO_Array_New: 12123 case OO_Delete: case OO_Array_Delete: 12124 return false; 12125 12126 default: 12127 return true; 12128 } 12129 } 12130 12131 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12132 /// template, where the non-dependent name was declared after the template 12133 /// was defined. This is common in code written for a compilers which do not 12134 /// correctly implement two-stage name lookup. 12135 /// 12136 /// Returns true if a viable candidate was found and a diagnostic was issued. 12137 static bool 12138 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12139 const CXXScopeSpec &SS, LookupResult &R, 12140 OverloadCandidateSet::CandidateSetKind CSK, 12141 TemplateArgumentListInfo *ExplicitTemplateArgs, 12142 ArrayRef<Expr *> Args, 12143 bool *DoDiagnoseEmptyLookup = nullptr) { 12144 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12145 return false; 12146 12147 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12148 if (DC->isTransparentContext()) 12149 continue; 12150 12151 SemaRef.LookupQualifiedName(R, DC); 12152 12153 if (!R.empty()) { 12154 R.suppressDiagnostics(); 12155 12156 if (isa<CXXRecordDecl>(DC)) { 12157 // Don't diagnose names we find in classes; we get much better 12158 // diagnostics for these from DiagnoseEmptyLookup. 12159 R.clear(); 12160 if (DoDiagnoseEmptyLookup) 12161 *DoDiagnoseEmptyLookup = true; 12162 return false; 12163 } 12164 12165 OverloadCandidateSet Candidates(FnLoc, CSK); 12166 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12167 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12168 ExplicitTemplateArgs, Args, 12169 Candidates, false, /*KnownValid*/ false); 12170 12171 OverloadCandidateSet::iterator Best; 12172 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12173 // No viable functions. Don't bother the user with notes for functions 12174 // which don't work and shouldn't be found anyway. 12175 R.clear(); 12176 return false; 12177 } 12178 12179 // Find the namespaces where ADL would have looked, and suggest 12180 // declaring the function there instead. 12181 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12182 Sema::AssociatedClassSet AssociatedClasses; 12183 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12184 AssociatedNamespaces, 12185 AssociatedClasses); 12186 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12187 if (canBeDeclaredInNamespace(R.getLookupName())) { 12188 DeclContext *Std = SemaRef.getStdNamespace(); 12189 for (Sema::AssociatedNamespaceSet::iterator 12190 it = AssociatedNamespaces.begin(), 12191 end = AssociatedNamespaces.end(); it != end; ++it) { 12192 // Never suggest declaring a function within namespace 'std'. 12193 if (Std && Std->Encloses(*it)) 12194 continue; 12195 12196 // Never suggest declaring a function within a namespace with a 12197 // reserved name, like __gnu_cxx. 12198 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12199 if (NS && 12200 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12201 continue; 12202 12203 SuggestedNamespaces.insert(*it); 12204 } 12205 } 12206 12207 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12208 << R.getLookupName(); 12209 if (SuggestedNamespaces.empty()) { 12210 SemaRef.Diag(Best->Function->getLocation(), 12211 diag::note_not_found_by_two_phase_lookup) 12212 << R.getLookupName() << 0; 12213 } else if (SuggestedNamespaces.size() == 1) { 12214 SemaRef.Diag(Best->Function->getLocation(), 12215 diag::note_not_found_by_two_phase_lookup) 12216 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12217 } else { 12218 // FIXME: It would be useful to list the associated namespaces here, 12219 // but the diagnostics infrastructure doesn't provide a way to produce 12220 // a localized representation of a list of items. 12221 SemaRef.Diag(Best->Function->getLocation(), 12222 diag::note_not_found_by_two_phase_lookup) 12223 << R.getLookupName() << 2; 12224 } 12225 12226 // Try to recover by calling this function. 12227 return true; 12228 } 12229 12230 R.clear(); 12231 } 12232 12233 return false; 12234 } 12235 12236 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12237 /// template, where the non-dependent operator was declared after the template 12238 /// was defined. 12239 /// 12240 /// Returns true if a viable candidate was found and a diagnostic was issued. 12241 static bool 12242 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12243 SourceLocation OpLoc, 12244 ArrayRef<Expr *> Args) { 12245 DeclarationName OpName = 12246 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12247 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12248 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12249 OverloadCandidateSet::CSK_Operator, 12250 /*ExplicitTemplateArgs=*/nullptr, Args); 12251 } 12252 12253 namespace { 12254 class BuildRecoveryCallExprRAII { 12255 Sema &SemaRef; 12256 public: 12257 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12258 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12259 SemaRef.IsBuildingRecoveryCallExpr = true; 12260 } 12261 12262 ~BuildRecoveryCallExprRAII() { 12263 SemaRef.IsBuildingRecoveryCallExpr = false; 12264 } 12265 }; 12266 12267 } 12268 12269 /// Attempts to recover from a call where no functions were found. 12270 /// 12271 /// Returns true if new candidates were found. 12272 static ExprResult 12273 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12274 UnresolvedLookupExpr *ULE, 12275 SourceLocation LParenLoc, 12276 MutableArrayRef<Expr *> Args, 12277 SourceLocation RParenLoc, 12278 bool EmptyLookup, bool AllowTypoCorrection) { 12279 // Do not try to recover if it is already building a recovery call. 12280 // This stops infinite loops for template instantiations like 12281 // 12282 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12283 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12284 // 12285 if (SemaRef.IsBuildingRecoveryCallExpr) 12286 return ExprError(); 12287 BuildRecoveryCallExprRAII RCE(SemaRef); 12288 12289 CXXScopeSpec SS; 12290 SS.Adopt(ULE->getQualifierLoc()); 12291 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12292 12293 TemplateArgumentListInfo TABuffer; 12294 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12295 if (ULE->hasExplicitTemplateArgs()) { 12296 ULE->copyTemplateArgumentsInto(TABuffer); 12297 ExplicitTemplateArgs = &TABuffer; 12298 } 12299 12300 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12301 Sema::LookupOrdinaryName); 12302 bool DoDiagnoseEmptyLookup = EmptyLookup; 12303 if (!DiagnoseTwoPhaseLookup( 12304 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12305 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12306 NoTypoCorrectionCCC NoTypoValidator{}; 12307 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12308 ExplicitTemplateArgs != nullptr, 12309 dyn_cast<MemberExpr>(Fn)); 12310 CorrectionCandidateCallback &Validator = 12311 AllowTypoCorrection 12312 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12313 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12314 if (!DoDiagnoseEmptyLookup || 12315 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12316 Args)) 12317 return ExprError(); 12318 } 12319 12320 assert(!R.empty() && "lookup results empty despite recovery"); 12321 12322 // If recovery created an ambiguity, just bail out. 12323 if (R.isAmbiguous()) { 12324 R.suppressDiagnostics(); 12325 return ExprError(); 12326 } 12327 12328 // Build an implicit member call if appropriate. Just drop the 12329 // casts and such from the call, we don't really care. 12330 ExprResult NewFn = ExprError(); 12331 if ((*R.begin())->isCXXClassMember()) 12332 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12333 ExplicitTemplateArgs, S); 12334 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12335 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12336 ExplicitTemplateArgs); 12337 else 12338 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12339 12340 if (NewFn.isInvalid()) 12341 return ExprError(); 12342 12343 // This shouldn't cause an infinite loop because we're giving it 12344 // an expression with viable lookup results, which should never 12345 // end up here. 12346 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12347 MultiExprArg(Args.data(), Args.size()), 12348 RParenLoc); 12349 } 12350 12351 /// Constructs and populates an OverloadedCandidateSet from 12352 /// the given function. 12353 /// \returns true when an the ExprResult output parameter has been set. 12354 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12355 UnresolvedLookupExpr *ULE, 12356 MultiExprArg Args, 12357 SourceLocation RParenLoc, 12358 OverloadCandidateSet *CandidateSet, 12359 ExprResult *Result) { 12360 #ifndef NDEBUG 12361 if (ULE->requiresADL()) { 12362 // To do ADL, we must have found an unqualified name. 12363 assert(!ULE->getQualifier() && "qualified name with ADL"); 12364 12365 // We don't perform ADL for implicit declarations of builtins. 12366 // Verify that this was correctly set up. 12367 FunctionDecl *F; 12368 if (ULE->decls_begin() != ULE->decls_end() && 12369 ULE->decls_begin() + 1 == ULE->decls_end() && 12370 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12371 F->getBuiltinID() && F->isImplicit()) 12372 llvm_unreachable("performing ADL for builtin"); 12373 12374 // We don't perform ADL in C. 12375 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12376 } 12377 #endif 12378 12379 UnbridgedCastsSet UnbridgedCasts; 12380 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12381 *Result = ExprError(); 12382 return true; 12383 } 12384 12385 // Add the functions denoted by the callee to the set of candidate 12386 // functions, including those from argument-dependent lookup. 12387 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12388 12389 if (getLangOpts().MSVCCompat && 12390 CurContext->isDependentContext() && !isSFINAEContext() && 12391 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12392 12393 OverloadCandidateSet::iterator Best; 12394 if (CandidateSet->empty() || 12395 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12396 OR_No_Viable_Function) { 12397 // In Microsoft mode, if we are inside a template class member function 12398 // then create a type dependent CallExpr. The goal is to postpone name 12399 // lookup to instantiation time to be able to search into type dependent 12400 // base classes. 12401 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12402 VK_RValue, RParenLoc); 12403 CE->setTypeDependent(true); 12404 CE->setValueDependent(true); 12405 CE->setInstantiationDependent(true); 12406 *Result = CE; 12407 return true; 12408 } 12409 } 12410 12411 if (CandidateSet->empty()) 12412 return false; 12413 12414 UnbridgedCasts.restore(); 12415 return false; 12416 } 12417 12418 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12419 /// the completed call expression. If overload resolution fails, emits 12420 /// diagnostics and returns ExprError() 12421 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12422 UnresolvedLookupExpr *ULE, 12423 SourceLocation LParenLoc, 12424 MultiExprArg Args, 12425 SourceLocation RParenLoc, 12426 Expr *ExecConfig, 12427 OverloadCandidateSet *CandidateSet, 12428 OverloadCandidateSet::iterator *Best, 12429 OverloadingResult OverloadResult, 12430 bool AllowTypoCorrection) { 12431 if (CandidateSet->empty()) 12432 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12433 RParenLoc, /*EmptyLookup=*/true, 12434 AllowTypoCorrection); 12435 12436 switch (OverloadResult) { 12437 case OR_Success: { 12438 FunctionDecl *FDecl = (*Best)->Function; 12439 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12440 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12441 return ExprError(); 12442 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12443 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12444 ExecConfig, /*IsExecConfig=*/false, 12445 (*Best)->IsADLCandidate); 12446 } 12447 12448 case OR_No_Viable_Function: { 12449 // Try to recover by looking for viable functions which the user might 12450 // have meant to call. 12451 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12452 Args, RParenLoc, 12453 /*EmptyLookup=*/false, 12454 AllowTypoCorrection); 12455 if (!Recovery.isInvalid()) 12456 return Recovery; 12457 12458 // If the user passes in a function that we can't take the address of, we 12459 // generally end up emitting really bad error messages. Here, we attempt to 12460 // emit better ones. 12461 for (const Expr *Arg : Args) { 12462 if (!Arg->getType()->isFunctionType()) 12463 continue; 12464 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12465 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12466 if (FD && 12467 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12468 Arg->getExprLoc())) 12469 return ExprError(); 12470 } 12471 } 12472 12473 CandidateSet->NoteCandidates( 12474 PartialDiagnosticAt( 12475 Fn->getBeginLoc(), 12476 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12477 << ULE->getName() << Fn->getSourceRange()), 12478 SemaRef, OCD_AllCandidates, Args); 12479 break; 12480 } 12481 12482 case OR_Ambiguous: 12483 CandidateSet->NoteCandidates( 12484 PartialDiagnosticAt(Fn->getBeginLoc(), 12485 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12486 << ULE->getName() << Fn->getSourceRange()), 12487 SemaRef, OCD_AmbiguousCandidates, Args); 12488 break; 12489 12490 case OR_Deleted: { 12491 CandidateSet->NoteCandidates( 12492 PartialDiagnosticAt(Fn->getBeginLoc(), 12493 SemaRef.PDiag(diag::err_ovl_deleted_call) 12494 << ULE->getName() << Fn->getSourceRange()), 12495 SemaRef, OCD_AllCandidates, Args); 12496 12497 // We emitted an error for the unavailable/deleted function call but keep 12498 // the call in the AST. 12499 FunctionDecl *FDecl = (*Best)->Function; 12500 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12501 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12502 ExecConfig, /*IsExecConfig=*/false, 12503 (*Best)->IsADLCandidate); 12504 } 12505 } 12506 12507 // Overload resolution failed. 12508 return ExprError(); 12509 } 12510 12511 static void markUnaddressableCandidatesUnviable(Sema &S, 12512 OverloadCandidateSet &CS) { 12513 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12514 if (I->Viable && 12515 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12516 I->Viable = false; 12517 I->FailureKind = ovl_fail_addr_not_available; 12518 } 12519 } 12520 } 12521 12522 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12523 /// (which eventually refers to the declaration Func) and the call 12524 /// arguments Args/NumArgs, attempt to resolve the function call down 12525 /// to a specific function. If overload resolution succeeds, returns 12526 /// the call expression produced by overload resolution. 12527 /// Otherwise, emits diagnostics and returns ExprError. 12528 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12529 UnresolvedLookupExpr *ULE, 12530 SourceLocation LParenLoc, 12531 MultiExprArg Args, 12532 SourceLocation RParenLoc, 12533 Expr *ExecConfig, 12534 bool AllowTypoCorrection, 12535 bool CalleesAddressIsTaken) { 12536 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12537 OverloadCandidateSet::CSK_Normal); 12538 ExprResult result; 12539 12540 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12541 &result)) 12542 return result; 12543 12544 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12545 // functions that aren't addressible are considered unviable. 12546 if (CalleesAddressIsTaken) 12547 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12548 12549 OverloadCandidateSet::iterator Best; 12550 OverloadingResult OverloadResult = 12551 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12552 12553 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12554 ExecConfig, &CandidateSet, &Best, 12555 OverloadResult, AllowTypoCorrection); 12556 } 12557 12558 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12559 return Functions.size() > 1 || 12560 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12561 } 12562 12563 /// Create a unary operation that may resolve to an overloaded 12564 /// operator. 12565 /// 12566 /// \param OpLoc The location of the operator itself (e.g., '*'). 12567 /// 12568 /// \param Opc The UnaryOperatorKind that describes this operator. 12569 /// 12570 /// \param Fns The set of non-member functions that will be 12571 /// considered by overload resolution. The caller needs to build this 12572 /// set based on the context using, e.g., 12573 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12574 /// set should not contain any member functions; those will be added 12575 /// by CreateOverloadedUnaryOp(). 12576 /// 12577 /// \param Input The input argument. 12578 ExprResult 12579 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12580 const UnresolvedSetImpl &Fns, 12581 Expr *Input, bool PerformADL) { 12582 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12583 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12584 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12585 // TODO: provide better source location info. 12586 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12587 12588 if (checkPlaceholderForOverload(*this, Input)) 12589 return ExprError(); 12590 12591 Expr *Args[2] = { Input, nullptr }; 12592 unsigned NumArgs = 1; 12593 12594 // For post-increment and post-decrement, add the implicit '0' as 12595 // the second argument, so that we know this is a post-increment or 12596 // post-decrement. 12597 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12598 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12599 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12600 SourceLocation()); 12601 NumArgs = 2; 12602 } 12603 12604 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12605 12606 if (Input->isTypeDependent()) { 12607 if (Fns.empty()) 12608 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12609 VK_RValue, OK_Ordinary, OpLoc, false); 12610 12611 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12612 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12613 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12614 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12615 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12616 Context.DependentTy, VK_RValue, OpLoc, 12617 FPOptions()); 12618 } 12619 12620 // Build an empty overload set. 12621 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12622 12623 // Add the candidates from the given function set. 12624 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12625 12626 // Add operator candidates that are member functions. 12627 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12628 12629 // Add candidates from ADL. 12630 if (PerformADL) { 12631 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12632 /*ExplicitTemplateArgs*/nullptr, 12633 CandidateSet); 12634 } 12635 12636 // Add builtin operator candidates. 12637 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12638 12639 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12640 12641 // Perform overload resolution. 12642 OverloadCandidateSet::iterator Best; 12643 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12644 case OR_Success: { 12645 // We found a built-in operator or an overloaded operator. 12646 FunctionDecl *FnDecl = Best->Function; 12647 12648 if (FnDecl) { 12649 Expr *Base = nullptr; 12650 // We matched an overloaded operator. Build a call to that 12651 // operator. 12652 12653 // Convert the arguments. 12654 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12655 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12656 12657 ExprResult InputRes = 12658 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12659 Best->FoundDecl, Method); 12660 if (InputRes.isInvalid()) 12661 return ExprError(); 12662 Base = Input = InputRes.get(); 12663 } else { 12664 // Convert the arguments. 12665 ExprResult InputInit 12666 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12667 Context, 12668 FnDecl->getParamDecl(0)), 12669 SourceLocation(), 12670 Input); 12671 if (InputInit.isInvalid()) 12672 return ExprError(); 12673 Input = InputInit.get(); 12674 } 12675 12676 // Build the actual expression node. 12677 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12678 Base, HadMultipleCandidates, 12679 OpLoc); 12680 if (FnExpr.isInvalid()) 12681 return ExprError(); 12682 12683 // Determine the result type. 12684 QualType ResultTy = FnDecl->getReturnType(); 12685 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12686 ResultTy = ResultTy.getNonLValueExprType(Context); 12687 12688 Args[0] = Input; 12689 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12690 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12691 FPOptions(), Best->IsADLCandidate); 12692 12693 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12694 return ExprError(); 12695 12696 if (CheckFunctionCall(FnDecl, TheCall, 12697 FnDecl->getType()->castAs<FunctionProtoType>())) 12698 return ExprError(); 12699 12700 return MaybeBindToTemporary(TheCall); 12701 } else { 12702 // We matched a built-in operator. Convert the arguments, then 12703 // break out so that we will build the appropriate built-in 12704 // operator node. 12705 ExprResult InputRes = PerformImplicitConversion( 12706 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12707 CCK_ForBuiltinOverloadedOp); 12708 if (InputRes.isInvalid()) 12709 return ExprError(); 12710 Input = InputRes.get(); 12711 break; 12712 } 12713 } 12714 12715 case OR_No_Viable_Function: 12716 // This is an erroneous use of an operator which can be overloaded by 12717 // a non-member function. Check for non-member operators which were 12718 // defined too late to be candidates. 12719 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12720 // FIXME: Recover by calling the found function. 12721 return ExprError(); 12722 12723 // No viable function; fall through to handling this as a 12724 // built-in operator, which will produce an error message for us. 12725 break; 12726 12727 case OR_Ambiguous: 12728 CandidateSet.NoteCandidates( 12729 PartialDiagnosticAt(OpLoc, 12730 PDiag(diag::err_ovl_ambiguous_oper_unary) 12731 << UnaryOperator::getOpcodeStr(Opc) 12732 << Input->getType() << Input->getSourceRange()), 12733 *this, OCD_AmbiguousCandidates, ArgsArray, 12734 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12735 return ExprError(); 12736 12737 case OR_Deleted: 12738 CandidateSet.NoteCandidates( 12739 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12740 << UnaryOperator::getOpcodeStr(Opc) 12741 << Input->getSourceRange()), 12742 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12743 OpLoc); 12744 return ExprError(); 12745 } 12746 12747 // Either we found no viable overloaded operator or we matched a 12748 // built-in operator. In either case, fall through to trying to 12749 // build a built-in operation. 12750 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12751 } 12752 12753 /// Perform lookup for an overloaded binary operator. 12754 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 12755 OverloadedOperatorKind Op, 12756 const UnresolvedSetImpl &Fns, 12757 ArrayRef<Expr *> Args, bool PerformADL) { 12758 SourceLocation OpLoc = CandidateSet.getLocation(); 12759 12760 OverloadedOperatorKind ExtraOp = 12761 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 12762 ? getRewrittenOverloadedOperator(Op) 12763 : OO_None; 12764 12765 // Add the candidates from the given function set. This also adds the 12766 // rewritten candidates using these functions if necessary. 12767 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 12768 12769 // Add operator candidates that are member functions. 12770 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12771 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 12772 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 12773 OverloadCandidateParamOrder::Reversed); 12774 12775 // In C++20, also add any rewritten member candidates. 12776 if (ExtraOp) { 12777 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 12778 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 12779 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 12780 CandidateSet, 12781 OverloadCandidateParamOrder::Reversed); 12782 } 12783 12784 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12785 // performed for an assignment operator (nor for operator[] nor operator->, 12786 // which don't get here). 12787 if (Op != OO_Equal && PerformADL) { 12788 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12789 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12790 /*ExplicitTemplateArgs*/ nullptr, 12791 CandidateSet); 12792 if (ExtraOp) { 12793 DeclarationName ExtraOpName = 12794 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 12795 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 12796 /*ExplicitTemplateArgs*/ nullptr, 12797 CandidateSet); 12798 } 12799 } 12800 12801 // Add builtin operator candidates. 12802 // 12803 // FIXME: We don't add any rewritten candidates here. This is strictly 12804 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 12805 // resulting in our selecting a rewritten builtin candidate. For example: 12806 // 12807 // enum class E { e }; 12808 // bool operator!=(E, E) requires false; 12809 // bool k = E::e != E::e; 12810 // 12811 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 12812 // it seems unreasonable to consider rewritten builtin candidates. A core 12813 // issue has been filed proposing to removed this requirement. 12814 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12815 } 12816 12817 /// Create a binary operation that may resolve to an overloaded 12818 /// operator. 12819 /// 12820 /// \param OpLoc The location of the operator itself (e.g., '+'). 12821 /// 12822 /// \param Opc The BinaryOperatorKind that describes this operator. 12823 /// 12824 /// \param Fns The set of non-member functions that will be 12825 /// considered by overload resolution. The caller needs to build this 12826 /// set based on the context using, e.g., 12827 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12828 /// set should not contain any member functions; those will be added 12829 /// by CreateOverloadedBinOp(). 12830 /// 12831 /// \param LHS Left-hand argument. 12832 /// \param RHS Right-hand argument. 12833 /// \param PerformADL Whether to consider operator candidates found by ADL. 12834 /// \param AllowRewrittenCandidates Whether to consider candidates found by 12835 /// C++20 operator rewrites. 12836 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 12837 /// the function in question. Such a function is never a candidate in 12838 /// our overload resolution. This also enables synthesizing a three-way 12839 /// comparison from < and == as described in C++20 [class.spaceship]p1. 12840 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12841 BinaryOperatorKind Opc, 12842 const UnresolvedSetImpl &Fns, Expr *LHS, 12843 Expr *RHS, bool PerformADL, 12844 bool AllowRewrittenCandidates, 12845 FunctionDecl *DefaultedFn) { 12846 Expr *Args[2] = { LHS, RHS }; 12847 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12848 12849 if (!getLangOpts().CPlusPlus2a) 12850 AllowRewrittenCandidates = false; 12851 12852 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12853 12854 // If either side is type-dependent, create an appropriate dependent 12855 // expression. 12856 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12857 if (Fns.empty()) { 12858 // If there are no functions to store, just build a dependent 12859 // BinaryOperator or CompoundAssignment. 12860 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12861 return new (Context) BinaryOperator( 12862 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12863 OpLoc, FPFeatures); 12864 12865 return new (Context) CompoundAssignOperator( 12866 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12867 Context.DependentTy, Context.DependentTy, OpLoc, 12868 FPFeatures); 12869 } 12870 12871 // FIXME: save results of ADL from here? 12872 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12873 // TODO: provide better source location info in DNLoc component. 12874 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12875 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12876 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12877 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12878 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12879 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12880 Context.DependentTy, VK_RValue, OpLoc, 12881 FPFeatures); 12882 } 12883 12884 // Always do placeholder-like conversions on the RHS. 12885 if (checkPlaceholderForOverload(*this, Args[1])) 12886 return ExprError(); 12887 12888 // Do placeholder-like conversion on the LHS; note that we should 12889 // not get here with a PseudoObject LHS. 12890 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12891 if (checkPlaceholderForOverload(*this, Args[0])) 12892 return ExprError(); 12893 12894 // If this is the assignment operator, we only perform overload resolution 12895 // if the left-hand side is a class or enumeration type. This is actually 12896 // a hack. The standard requires that we do overload resolution between the 12897 // various built-in candidates, but as DR507 points out, this can lead to 12898 // problems. So we do it this way, which pretty much follows what GCC does. 12899 // Note that we go the traditional code path for compound assignment forms. 12900 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12901 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12902 12903 // If this is the .* operator, which is not overloadable, just 12904 // create a built-in binary operator. 12905 if (Opc == BO_PtrMemD) 12906 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12907 12908 // Build the overload set. 12909 OverloadCandidateSet CandidateSet( 12910 OpLoc, OverloadCandidateSet::CSK_Operator, 12911 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 12912 if (DefaultedFn) 12913 CandidateSet.exclude(DefaultedFn); 12914 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 12915 12916 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12917 12918 // Perform overload resolution. 12919 OverloadCandidateSet::iterator Best; 12920 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12921 case OR_Success: { 12922 // We found a built-in operator or an overloaded operator. 12923 FunctionDecl *FnDecl = Best->Function; 12924 12925 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 12926 if (IsReversed) 12927 std::swap(Args[0], Args[1]); 12928 12929 if (FnDecl) { 12930 Expr *Base = nullptr; 12931 // We matched an overloaded operator. Build a call to that 12932 // operator. 12933 12934 OverloadedOperatorKind ChosenOp = 12935 FnDecl->getDeclName().getCXXOverloadedOperator(); 12936 12937 // C++2a [over.match.oper]p9: 12938 // If a rewritten operator== candidate is selected by overload 12939 // resolution for an operator@, its return type shall be cv bool 12940 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 12941 !FnDecl->getReturnType()->isBooleanType()) { 12942 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 12943 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 12944 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12945 Diag(FnDecl->getLocation(), diag::note_declared_at); 12946 return ExprError(); 12947 } 12948 12949 if (AllowRewrittenCandidates && !IsReversed && 12950 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 12951 // We could have reversed this operator, but didn't. Check if the 12952 // reversed form was a viable candidate, and if so, if it had a 12953 // better conversion for either parameter. If so, this call is 12954 // formally ambiguous, and allowing it is an extension. 12955 for (OverloadCandidate &Cand : CandidateSet) { 12956 if (Cand.Viable && Cand.Function == FnDecl && 12957 Cand.RewriteKind & CRK_Reversed) { 12958 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 12959 if (CompareImplicitConversionSequences( 12960 *this, OpLoc, Cand.Conversions[ArgIdx], 12961 Best->Conversions[ArgIdx]) == 12962 ImplicitConversionSequence::Better) { 12963 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 12964 << BinaryOperator::getOpcodeStr(Opc) 12965 << Args[0]->getType() << Args[1]->getType() 12966 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12967 Diag(FnDecl->getLocation(), 12968 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 12969 } 12970 } 12971 break; 12972 } 12973 } 12974 } 12975 12976 // Convert the arguments. 12977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12978 // Best->Access is only meaningful for class members. 12979 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12980 12981 ExprResult Arg1 = 12982 PerformCopyInitialization( 12983 InitializedEntity::InitializeParameter(Context, 12984 FnDecl->getParamDecl(0)), 12985 SourceLocation(), Args[1]); 12986 if (Arg1.isInvalid()) 12987 return ExprError(); 12988 12989 ExprResult Arg0 = 12990 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12991 Best->FoundDecl, Method); 12992 if (Arg0.isInvalid()) 12993 return ExprError(); 12994 Base = Args[0] = Arg0.getAs<Expr>(); 12995 Args[1] = RHS = Arg1.getAs<Expr>(); 12996 } else { 12997 // Convert the arguments. 12998 ExprResult Arg0 = PerformCopyInitialization( 12999 InitializedEntity::InitializeParameter(Context, 13000 FnDecl->getParamDecl(0)), 13001 SourceLocation(), Args[0]); 13002 if (Arg0.isInvalid()) 13003 return ExprError(); 13004 13005 ExprResult Arg1 = 13006 PerformCopyInitialization( 13007 InitializedEntity::InitializeParameter(Context, 13008 FnDecl->getParamDecl(1)), 13009 SourceLocation(), Args[1]); 13010 if (Arg1.isInvalid()) 13011 return ExprError(); 13012 Args[0] = LHS = Arg0.getAs<Expr>(); 13013 Args[1] = RHS = Arg1.getAs<Expr>(); 13014 } 13015 13016 // Build the actual expression node. 13017 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13018 Best->FoundDecl, Base, 13019 HadMultipleCandidates, OpLoc); 13020 if (FnExpr.isInvalid()) 13021 return ExprError(); 13022 13023 // Determine the result type. 13024 QualType ResultTy = FnDecl->getReturnType(); 13025 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13026 ResultTy = ResultTy.getNonLValueExprType(Context); 13027 13028 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13029 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13030 FPFeatures, Best->IsADLCandidate); 13031 13032 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13033 FnDecl)) 13034 return ExprError(); 13035 13036 ArrayRef<const Expr *> ArgsArray(Args, 2); 13037 const Expr *ImplicitThis = nullptr; 13038 // Cut off the implicit 'this'. 13039 if (isa<CXXMethodDecl>(FnDecl)) { 13040 ImplicitThis = ArgsArray[0]; 13041 ArgsArray = ArgsArray.slice(1); 13042 } 13043 13044 // Check for a self move. 13045 if (Op == OO_Equal) 13046 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13047 13048 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13049 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13050 VariadicDoesNotApply); 13051 13052 ExprResult R = MaybeBindToTemporary(TheCall); 13053 if (R.isInvalid()) 13054 return ExprError(); 13055 13056 // For a rewritten candidate, we've already reversed the arguments 13057 // if needed. Perform the rest of the rewrite now. 13058 if ((Best->RewriteKind & CRK_DifferentOperator) || 13059 (Op == OO_Spaceship && IsReversed)) { 13060 if (Op == OO_ExclaimEqual) { 13061 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13062 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13063 } else { 13064 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13065 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13066 Expr *ZeroLiteral = 13067 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13068 13069 Sema::CodeSynthesisContext Ctx; 13070 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13071 Ctx.Entity = FnDecl; 13072 pushCodeSynthesisContext(Ctx); 13073 13074 R = CreateOverloadedBinOp( 13075 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13076 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13077 /*AllowRewrittenCandidates=*/false); 13078 13079 popCodeSynthesisContext(); 13080 } 13081 if (R.isInvalid()) 13082 return ExprError(); 13083 } else { 13084 assert(ChosenOp == Op && "unexpected operator name"); 13085 } 13086 13087 // Make a note in the AST if we did any rewriting. 13088 if (Best->RewriteKind != CRK_None) 13089 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13090 13091 return R; 13092 } else { 13093 // We matched a built-in operator. Convert the arguments, then 13094 // break out so that we will build the appropriate built-in 13095 // operator node. 13096 ExprResult ArgsRes0 = PerformImplicitConversion( 13097 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13098 AA_Passing, CCK_ForBuiltinOverloadedOp); 13099 if (ArgsRes0.isInvalid()) 13100 return ExprError(); 13101 Args[0] = ArgsRes0.get(); 13102 13103 ExprResult ArgsRes1 = PerformImplicitConversion( 13104 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13105 AA_Passing, CCK_ForBuiltinOverloadedOp); 13106 if (ArgsRes1.isInvalid()) 13107 return ExprError(); 13108 Args[1] = ArgsRes1.get(); 13109 break; 13110 } 13111 } 13112 13113 case OR_No_Viable_Function: { 13114 // C++ [over.match.oper]p9: 13115 // If the operator is the operator , [...] and there are no 13116 // viable functions, then the operator is assumed to be the 13117 // built-in operator and interpreted according to clause 5. 13118 if (Opc == BO_Comma) 13119 break; 13120 13121 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13122 // compare result using '==' and '<'. 13123 if (DefaultedFn && Opc == BO_Cmp) { 13124 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13125 Args[1], DefaultedFn); 13126 if (E.isInvalid() || E.isUsable()) 13127 return E; 13128 } 13129 13130 // For class as left operand for assignment or compound assignment 13131 // operator do not fall through to handling in built-in, but report that 13132 // no overloaded assignment operator found 13133 ExprResult Result = ExprError(); 13134 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13135 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13136 Args, OpLoc); 13137 if (Args[0]->getType()->isRecordType() && 13138 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13139 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13140 << BinaryOperator::getOpcodeStr(Opc) 13141 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13142 if (Args[0]->getType()->isIncompleteType()) { 13143 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13144 << Args[0]->getType() 13145 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13146 } 13147 } else { 13148 // This is an erroneous use of an operator which can be overloaded by 13149 // a non-member function. Check for non-member operators which were 13150 // defined too late to be candidates. 13151 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13152 // FIXME: Recover by calling the found function. 13153 return ExprError(); 13154 13155 // No viable function; try to create a built-in operation, which will 13156 // produce an error. Then, show the non-viable candidates. 13157 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13158 } 13159 assert(Result.isInvalid() && 13160 "C++ binary operator overloading is missing candidates!"); 13161 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13162 return Result; 13163 } 13164 13165 case OR_Ambiguous: 13166 CandidateSet.NoteCandidates( 13167 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13168 << BinaryOperator::getOpcodeStr(Opc) 13169 << Args[0]->getType() 13170 << Args[1]->getType() 13171 << Args[0]->getSourceRange() 13172 << Args[1]->getSourceRange()), 13173 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13174 OpLoc); 13175 return ExprError(); 13176 13177 case OR_Deleted: 13178 if (isImplicitlyDeleted(Best->Function)) { 13179 FunctionDecl *DeletedFD = Best->Function; 13180 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13181 if (DFK.isSpecialMember()) { 13182 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13183 << Args[0]->getType() << DFK.asSpecialMember(); 13184 } else { 13185 assert(DFK.isComparison()); 13186 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13187 << Args[0]->getType() << DeletedFD; 13188 } 13189 13190 // The user probably meant to call this special member. Just 13191 // explain why it's deleted. 13192 NoteDeletedFunction(DeletedFD); 13193 return ExprError(); 13194 } 13195 CandidateSet.NoteCandidates( 13196 PartialDiagnosticAt( 13197 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13198 << getOperatorSpelling(Best->Function->getDeclName() 13199 .getCXXOverloadedOperator()) 13200 << Args[0]->getSourceRange() 13201 << Args[1]->getSourceRange()), 13202 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13203 OpLoc); 13204 return ExprError(); 13205 } 13206 13207 // We matched a built-in operator; build it. 13208 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13209 } 13210 13211 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13212 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13213 FunctionDecl *DefaultedFn) { 13214 const ComparisonCategoryInfo *Info = 13215 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13216 // If we're not producing a known comparison category type, we can't 13217 // synthesize a three-way comparison. Let the caller diagnose this. 13218 if (!Info) 13219 return ExprResult((Expr*)nullptr); 13220 13221 // If we ever want to perform this synthesis more generally, we will need to 13222 // apply the temporary materialization conversion to the operands. 13223 assert(LHS->isGLValue() && RHS->isGLValue() && 13224 "cannot use prvalue expressions more than once"); 13225 Expr *OrigLHS = LHS; 13226 Expr *OrigRHS = RHS; 13227 13228 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13229 // each of them multiple times below. 13230 LHS = new (Context) 13231 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13232 LHS->getObjectKind(), LHS); 13233 RHS = new (Context) 13234 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13235 RHS->getObjectKind(), RHS); 13236 13237 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13238 DefaultedFn); 13239 if (Eq.isInvalid()) 13240 return ExprError(); 13241 13242 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13243 true, DefaultedFn); 13244 if (Less.isInvalid()) 13245 return ExprError(); 13246 13247 ExprResult Greater; 13248 if (Info->isPartial()) { 13249 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13250 DefaultedFn); 13251 if (Greater.isInvalid()) 13252 return ExprError(); 13253 } 13254 13255 // Form the list of comparisons we're going to perform. 13256 struct Comparison { 13257 ExprResult Cmp; 13258 ComparisonCategoryResult Result; 13259 } Comparisons[4] = 13260 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13261 : ComparisonCategoryResult::Equivalent}, 13262 {Less, ComparisonCategoryResult::Less}, 13263 {Greater, ComparisonCategoryResult::Greater}, 13264 {ExprResult(), ComparisonCategoryResult::Unordered}, 13265 }; 13266 13267 int I = Info->isPartial() ? 3 : 2; 13268 13269 // Combine the comparisons with suitable conditional expressions. 13270 ExprResult Result; 13271 for (; I >= 0; --I) { 13272 // Build a reference to the comparison category constant. 13273 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13274 // FIXME: Missing a constant for a comparison category. Diagnose this? 13275 if (!VI) 13276 return ExprResult((Expr*)nullptr); 13277 ExprResult ThisResult = 13278 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13279 if (ThisResult.isInvalid()) 13280 return ExprError(); 13281 13282 // Build a conditional unless this is the final case. 13283 if (Result.get()) { 13284 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13285 ThisResult.get(), Result.get()); 13286 if (Result.isInvalid()) 13287 return ExprError(); 13288 } else { 13289 Result = ThisResult; 13290 } 13291 } 13292 13293 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13294 // bind the OpaqueValueExprs before they're (repeatedly) used. 13295 Expr *SyntacticForm = new (Context) 13296 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13297 Result.get()->getValueKind(), 13298 Result.get()->getObjectKind(), OpLoc, FPFeatures); 13299 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13300 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13301 } 13302 13303 ExprResult 13304 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13305 SourceLocation RLoc, 13306 Expr *Base, Expr *Idx) { 13307 Expr *Args[2] = { Base, Idx }; 13308 DeclarationName OpName = 13309 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13310 13311 // If either side is type-dependent, create an appropriate dependent 13312 // expression. 13313 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13314 13315 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13316 // CHECKME: no 'operator' keyword? 13317 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13318 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13319 UnresolvedLookupExpr *Fn 13320 = UnresolvedLookupExpr::Create(Context, NamingClass, 13321 NestedNameSpecifierLoc(), OpNameInfo, 13322 /*ADL*/ true, /*Overloaded*/ false, 13323 UnresolvedSetIterator(), 13324 UnresolvedSetIterator()); 13325 // Can't add any actual overloads yet 13326 13327 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13328 Context.DependentTy, VK_RValue, RLoc, 13329 FPOptions()); 13330 } 13331 13332 // Handle placeholders on both operands. 13333 if (checkPlaceholderForOverload(*this, Args[0])) 13334 return ExprError(); 13335 if (checkPlaceholderForOverload(*this, Args[1])) 13336 return ExprError(); 13337 13338 // Build an empty overload set. 13339 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13340 13341 // Subscript can only be overloaded as a member function. 13342 13343 // Add operator candidates that are member functions. 13344 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13345 13346 // Add builtin operator candidates. 13347 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13348 13349 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13350 13351 // Perform overload resolution. 13352 OverloadCandidateSet::iterator Best; 13353 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13354 case OR_Success: { 13355 // We found a built-in operator or an overloaded operator. 13356 FunctionDecl *FnDecl = Best->Function; 13357 13358 if (FnDecl) { 13359 // We matched an overloaded operator. Build a call to that 13360 // operator. 13361 13362 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13363 13364 // Convert the arguments. 13365 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13366 ExprResult Arg0 = 13367 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13368 Best->FoundDecl, Method); 13369 if (Arg0.isInvalid()) 13370 return ExprError(); 13371 Args[0] = Arg0.get(); 13372 13373 // Convert the arguments. 13374 ExprResult InputInit 13375 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13376 Context, 13377 FnDecl->getParamDecl(0)), 13378 SourceLocation(), 13379 Args[1]); 13380 if (InputInit.isInvalid()) 13381 return ExprError(); 13382 13383 Args[1] = InputInit.getAs<Expr>(); 13384 13385 // Build the actual expression node. 13386 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13387 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13388 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13389 Best->FoundDecl, 13390 Base, 13391 HadMultipleCandidates, 13392 OpLocInfo.getLoc(), 13393 OpLocInfo.getInfo()); 13394 if (FnExpr.isInvalid()) 13395 return ExprError(); 13396 13397 // Determine the result type 13398 QualType ResultTy = FnDecl->getReturnType(); 13399 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13400 ResultTy = ResultTy.getNonLValueExprType(Context); 13401 13402 CXXOperatorCallExpr *TheCall = 13403 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13404 Args, ResultTy, VK, RLoc, FPOptions()); 13405 13406 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13407 return ExprError(); 13408 13409 if (CheckFunctionCall(Method, TheCall, 13410 Method->getType()->castAs<FunctionProtoType>())) 13411 return ExprError(); 13412 13413 return MaybeBindToTemporary(TheCall); 13414 } else { 13415 // We matched a built-in operator. Convert the arguments, then 13416 // break out so that we will build the appropriate built-in 13417 // operator node. 13418 ExprResult ArgsRes0 = PerformImplicitConversion( 13419 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13420 AA_Passing, CCK_ForBuiltinOverloadedOp); 13421 if (ArgsRes0.isInvalid()) 13422 return ExprError(); 13423 Args[0] = ArgsRes0.get(); 13424 13425 ExprResult ArgsRes1 = PerformImplicitConversion( 13426 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13427 AA_Passing, CCK_ForBuiltinOverloadedOp); 13428 if (ArgsRes1.isInvalid()) 13429 return ExprError(); 13430 Args[1] = ArgsRes1.get(); 13431 13432 break; 13433 } 13434 } 13435 13436 case OR_No_Viable_Function: { 13437 PartialDiagnostic PD = CandidateSet.empty() 13438 ? (PDiag(diag::err_ovl_no_oper) 13439 << Args[0]->getType() << /*subscript*/ 0 13440 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13441 : (PDiag(diag::err_ovl_no_viable_subscript) 13442 << Args[0]->getType() << Args[0]->getSourceRange() 13443 << Args[1]->getSourceRange()); 13444 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13445 OCD_AllCandidates, Args, "[]", LLoc); 13446 return ExprError(); 13447 } 13448 13449 case OR_Ambiguous: 13450 CandidateSet.NoteCandidates( 13451 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13452 << "[]" << Args[0]->getType() 13453 << Args[1]->getType() 13454 << Args[0]->getSourceRange() 13455 << Args[1]->getSourceRange()), 13456 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13457 return ExprError(); 13458 13459 case OR_Deleted: 13460 CandidateSet.NoteCandidates( 13461 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13462 << "[]" << Args[0]->getSourceRange() 13463 << Args[1]->getSourceRange()), 13464 *this, OCD_AllCandidates, Args, "[]", LLoc); 13465 return ExprError(); 13466 } 13467 13468 // We matched a built-in operator; build it. 13469 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13470 } 13471 13472 /// BuildCallToMemberFunction - Build a call to a member 13473 /// function. MemExpr is the expression that refers to the member 13474 /// function (and includes the object parameter), Args/NumArgs are the 13475 /// arguments to the function call (not including the object 13476 /// parameter). The caller needs to validate that the member 13477 /// expression refers to a non-static member function or an overloaded 13478 /// member function. 13479 ExprResult 13480 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13481 SourceLocation LParenLoc, 13482 MultiExprArg Args, 13483 SourceLocation RParenLoc) { 13484 assert(MemExprE->getType() == Context.BoundMemberTy || 13485 MemExprE->getType() == Context.OverloadTy); 13486 13487 // Dig out the member expression. This holds both the object 13488 // argument and the member function we're referring to. 13489 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13490 13491 // Determine whether this is a call to a pointer-to-member function. 13492 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13493 assert(op->getType() == Context.BoundMemberTy); 13494 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13495 13496 QualType fnType = 13497 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13498 13499 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13500 QualType resultType = proto->getCallResultType(Context); 13501 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13502 13503 // Check that the object type isn't more qualified than the 13504 // member function we're calling. 13505 Qualifiers funcQuals = proto->getMethodQuals(); 13506 13507 QualType objectType = op->getLHS()->getType(); 13508 if (op->getOpcode() == BO_PtrMemI) 13509 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13510 Qualifiers objectQuals = objectType.getQualifiers(); 13511 13512 Qualifiers difference = objectQuals - funcQuals; 13513 difference.removeObjCGCAttr(); 13514 difference.removeAddressSpace(); 13515 if (difference) { 13516 std::string qualsString = difference.getAsString(); 13517 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13518 << fnType.getUnqualifiedType() 13519 << qualsString 13520 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13521 } 13522 13523 CXXMemberCallExpr *call = 13524 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13525 valueKind, RParenLoc, proto->getNumParams()); 13526 13527 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13528 call, nullptr)) 13529 return ExprError(); 13530 13531 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13532 return ExprError(); 13533 13534 if (CheckOtherCall(call, proto)) 13535 return ExprError(); 13536 13537 return MaybeBindToTemporary(call); 13538 } 13539 13540 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13541 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13542 RParenLoc); 13543 13544 UnbridgedCastsSet UnbridgedCasts; 13545 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13546 return ExprError(); 13547 13548 MemberExpr *MemExpr; 13549 CXXMethodDecl *Method = nullptr; 13550 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13551 NestedNameSpecifier *Qualifier = nullptr; 13552 if (isa<MemberExpr>(NakedMemExpr)) { 13553 MemExpr = cast<MemberExpr>(NakedMemExpr); 13554 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13555 FoundDecl = MemExpr->getFoundDecl(); 13556 Qualifier = MemExpr->getQualifier(); 13557 UnbridgedCasts.restore(); 13558 } else { 13559 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13560 Qualifier = UnresExpr->getQualifier(); 13561 13562 QualType ObjectType = UnresExpr->getBaseType(); 13563 Expr::Classification ObjectClassification 13564 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13565 : UnresExpr->getBase()->Classify(Context); 13566 13567 // Add overload candidates 13568 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13569 OverloadCandidateSet::CSK_Normal); 13570 13571 // FIXME: avoid copy. 13572 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13573 if (UnresExpr->hasExplicitTemplateArgs()) { 13574 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13575 TemplateArgs = &TemplateArgsBuffer; 13576 } 13577 13578 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13579 E = UnresExpr->decls_end(); I != E; ++I) { 13580 13581 NamedDecl *Func = *I; 13582 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13583 if (isa<UsingShadowDecl>(Func)) 13584 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13585 13586 13587 // Microsoft supports direct constructor calls. 13588 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13589 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13590 CandidateSet, 13591 /*SuppressUserConversions*/ false); 13592 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13593 // If explicit template arguments were provided, we can't call a 13594 // non-template member function. 13595 if (TemplateArgs) 13596 continue; 13597 13598 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13599 ObjectClassification, Args, CandidateSet, 13600 /*SuppressUserConversions=*/false); 13601 } else { 13602 AddMethodTemplateCandidate( 13603 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13604 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13605 /*SuppressUserConversions=*/false); 13606 } 13607 } 13608 13609 DeclarationName DeclName = UnresExpr->getMemberName(); 13610 13611 UnbridgedCasts.restore(); 13612 13613 OverloadCandidateSet::iterator Best; 13614 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13615 Best)) { 13616 case OR_Success: 13617 Method = cast<CXXMethodDecl>(Best->Function); 13618 FoundDecl = Best->FoundDecl; 13619 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13620 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13621 return ExprError(); 13622 // If FoundDecl is different from Method (such as if one is a template 13623 // and the other a specialization), make sure DiagnoseUseOfDecl is 13624 // called on both. 13625 // FIXME: This would be more comprehensively addressed by modifying 13626 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13627 // being used. 13628 if (Method != FoundDecl.getDecl() && 13629 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13630 return ExprError(); 13631 break; 13632 13633 case OR_No_Viable_Function: 13634 CandidateSet.NoteCandidates( 13635 PartialDiagnosticAt( 13636 UnresExpr->getMemberLoc(), 13637 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13638 << DeclName << MemExprE->getSourceRange()), 13639 *this, OCD_AllCandidates, Args); 13640 // FIXME: Leaking incoming expressions! 13641 return ExprError(); 13642 13643 case OR_Ambiguous: 13644 CandidateSet.NoteCandidates( 13645 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13646 PDiag(diag::err_ovl_ambiguous_member_call) 13647 << DeclName << MemExprE->getSourceRange()), 13648 *this, OCD_AmbiguousCandidates, Args); 13649 // FIXME: Leaking incoming expressions! 13650 return ExprError(); 13651 13652 case OR_Deleted: 13653 CandidateSet.NoteCandidates( 13654 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13655 PDiag(diag::err_ovl_deleted_member_call) 13656 << DeclName << MemExprE->getSourceRange()), 13657 *this, OCD_AllCandidates, Args); 13658 // FIXME: Leaking incoming expressions! 13659 return ExprError(); 13660 } 13661 13662 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13663 13664 // If overload resolution picked a static member, build a 13665 // non-member call based on that function. 13666 if (Method->isStatic()) { 13667 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13668 RParenLoc); 13669 } 13670 13671 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13672 } 13673 13674 QualType ResultType = Method->getReturnType(); 13675 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13676 ResultType = ResultType.getNonLValueExprType(Context); 13677 13678 assert(Method && "Member call to something that isn't a method?"); 13679 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13680 CXXMemberCallExpr *TheCall = 13681 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13682 RParenLoc, Proto->getNumParams()); 13683 13684 // Check for a valid return type. 13685 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13686 TheCall, Method)) 13687 return ExprError(); 13688 13689 // Convert the object argument (for a non-static member function call). 13690 // We only need to do this if there was actually an overload; otherwise 13691 // it was done at lookup. 13692 if (!Method->isStatic()) { 13693 ExprResult ObjectArg = 13694 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13695 FoundDecl, Method); 13696 if (ObjectArg.isInvalid()) 13697 return ExprError(); 13698 MemExpr->setBase(ObjectArg.get()); 13699 } 13700 13701 // Convert the rest of the arguments 13702 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13703 RParenLoc)) 13704 return ExprError(); 13705 13706 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13707 13708 if (CheckFunctionCall(Method, TheCall, Proto)) 13709 return ExprError(); 13710 13711 // In the case the method to call was not selected by the overloading 13712 // resolution process, we still need to handle the enable_if attribute. Do 13713 // that here, so it will not hide previous -- and more relevant -- errors. 13714 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13715 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13716 Diag(MemE->getMemberLoc(), 13717 diag::err_ovl_no_viable_member_function_in_call) 13718 << Method << Method->getSourceRange(); 13719 Diag(Method->getLocation(), 13720 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13721 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13722 return ExprError(); 13723 } 13724 } 13725 13726 if ((isa<CXXConstructorDecl>(CurContext) || 13727 isa<CXXDestructorDecl>(CurContext)) && 13728 TheCall->getMethodDecl()->isPure()) { 13729 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13730 13731 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13732 MemExpr->performsVirtualDispatch(getLangOpts())) { 13733 Diag(MemExpr->getBeginLoc(), 13734 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13735 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13736 << MD->getParent()->getDeclName(); 13737 13738 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13739 if (getLangOpts().AppleKext) 13740 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13741 << MD->getParent()->getDeclName() << MD->getDeclName(); 13742 } 13743 } 13744 13745 if (CXXDestructorDecl *DD = 13746 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13747 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13748 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13749 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13750 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13751 MemExpr->getMemberLoc()); 13752 } 13753 13754 return MaybeBindToTemporary(TheCall); 13755 } 13756 13757 /// BuildCallToObjectOfClassType - Build a call to an object of class 13758 /// type (C++ [over.call.object]), which can end up invoking an 13759 /// overloaded function call operator (@c operator()) or performing a 13760 /// user-defined conversion on the object argument. 13761 ExprResult 13762 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13763 SourceLocation LParenLoc, 13764 MultiExprArg Args, 13765 SourceLocation RParenLoc) { 13766 if (checkPlaceholderForOverload(*this, Obj)) 13767 return ExprError(); 13768 ExprResult Object = Obj; 13769 13770 UnbridgedCastsSet UnbridgedCasts; 13771 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13772 return ExprError(); 13773 13774 assert(Object.get()->getType()->isRecordType() && 13775 "Requires object type argument"); 13776 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13777 13778 // C++ [over.call.object]p1: 13779 // If the primary-expression E in the function call syntax 13780 // evaluates to a class object of type "cv T", then the set of 13781 // candidate functions includes at least the function call 13782 // operators of T. The function call operators of T are obtained by 13783 // ordinary lookup of the name operator() in the context of 13784 // (E).operator(). 13785 OverloadCandidateSet CandidateSet(LParenLoc, 13786 OverloadCandidateSet::CSK_Operator); 13787 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13788 13789 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13790 diag::err_incomplete_object_call, Object.get())) 13791 return true; 13792 13793 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13794 LookupQualifiedName(R, Record->getDecl()); 13795 R.suppressDiagnostics(); 13796 13797 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13798 Oper != OperEnd; ++Oper) { 13799 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13800 Object.get()->Classify(Context), Args, CandidateSet, 13801 /*SuppressUserConversion=*/false); 13802 } 13803 13804 // C++ [over.call.object]p2: 13805 // In addition, for each (non-explicit in C++0x) conversion function 13806 // declared in T of the form 13807 // 13808 // operator conversion-type-id () cv-qualifier; 13809 // 13810 // where cv-qualifier is the same cv-qualification as, or a 13811 // greater cv-qualification than, cv, and where conversion-type-id 13812 // denotes the type "pointer to function of (P1,...,Pn) returning 13813 // R", or the type "reference to pointer to function of 13814 // (P1,...,Pn) returning R", or the type "reference to function 13815 // of (P1,...,Pn) returning R", a surrogate call function [...] 13816 // is also considered as a candidate function. Similarly, 13817 // surrogate call functions are added to the set of candidate 13818 // functions for each conversion function declared in an 13819 // accessible base class provided the function is not hidden 13820 // within T by another intervening declaration. 13821 const auto &Conversions = 13822 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13823 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13824 NamedDecl *D = *I; 13825 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13826 if (isa<UsingShadowDecl>(D)) 13827 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13828 13829 // Skip over templated conversion functions; they aren't 13830 // surrogates. 13831 if (isa<FunctionTemplateDecl>(D)) 13832 continue; 13833 13834 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13835 if (!Conv->isExplicit()) { 13836 // Strip the reference type (if any) and then the pointer type (if 13837 // any) to get down to what might be a function type. 13838 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13839 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13840 ConvType = ConvPtrType->getPointeeType(); 13841 13842 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13843 { 13844 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13845 Object.get(), Args, CandidateSet); 13846 } 13847 } 13848 } 13849 13850 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13851 13852 // Perform overload resolution. 13853 OverloadCandidateSet::iterator Best; 13854 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13855 Best)) { 13856 case OR_Success: 13857 // Overload resolution succeeded; we'll build the appropriate call 13858 // below. 13859 break; 13860 13861 case OR_No_Viable_Function: { 13862 PartialDiagnostic PD = 13863 CandidateSet.empty() 13864 ? (PDiag(diag::err_ovl_no_oper) 13865 << Object.get()->getType() << /*call*/ 1 13866 << Object.get()->getSourceRange()) 13867 : (PDiag(diag::err_ovl_no_viable_object_call) 13868 << Object.get()->getType() << Object.get()->getSourceRange()); 13869 CandidateSet.NoteCandidates( 13870 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13871 OCD_AllCandidates, Args); 13872 break; 13873 } 13874 case OR_Ambiguous: 13875 CandidateSet.NoteCandidates( 13876 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13877 PDiag(diag::err_ovl_ambiguous_object_call) 13878 << Object.get()->getType() 13879 << Object.get()->getSourceRange()), 13880 *this, OCD_AmbiguousCandidates, Args); 13881 break; 13882 13883 case OR_Deleted: 13884 CandidateSet.NoteCandidates( 13885 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13886 PDiag(diag::err_ovl_deleted_object_call) 13887 << Object.get()->getType() 13888 << Object.get()->getSourceRange()), 13889 *this, OCD_AllCandidates, Args); 13890 break; 13891 } 13892 13893 if (Best == CandidateSet.end()) 13894 return true; 13895 13896 UnbridgedCasts.restore(); 13897 13898 if (Best->Function == nullptr) { 13899 // Since there is no function declaration, this is one of the 13900 // surrogate candidates. Dig out the conversion function. 13901 CXXConversionDecl *Conv 13902 = cast<CXXConversionDecl>( 13903 Best->Conversions[0].UserDefined.ConversionFunction); 13904 13905 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13906 Best->FoundDecl); 13907 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13908 return ExprError(); 13909 assert(Conv == Best->FoundDecl.getDecl() && 13910 "Found Decl & conversion-to-functionptr should be same, right?!"); 13911 // We selected one of the surrogate functions that converts the 13912 // object parameter to a function pointer. Perform the conversion 13913 // on the object argument, then let BuildCallExpr finish the job. 13914 13915 // Create an implicit member expr to refer to the conversion operator. 13916 // and then call it. 13917 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13918 Conv, HadMultipleCandidates); 13919 if (Call.isInvalid()) 13920 return ExprError(); 13921 // Record usage of conversion in an implicit cast. 13922 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13923 CK_UserDefinedConversion, Call.get(), 13924 nullptr, VK_RValue); 13925 13926 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13927 } 13928 13929 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13930 13931 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13932 // that calls this method, using Object for the implicit object 13933 // parameter and passing along the remaining arguments. 13934 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13935 13936 // An error diagnostic has already been printed when parsing the declaration. 13937 if (Method->isInvalidDecl()) 13938 return ExprError(); 13939 13940 const FunctionProtoType *Proto = 13941 Method->getType()->getAs<FunctionProtoType>(); 13942 13943 unsigned NumParams = Proto->getNumParams(); 13944 13945 DeclarationNameInfo OpLocInfo( 13946 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13947 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13948 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13949 Obj, HadMultipleCandidates, 13950 OpLocInfo.getLoc(), 13951 OpLocInfo.getInfo()); 13952 if (NewFn.isInvalid()) 13953 return true; 13954 13955 // The number of argument slots to allocate in the call. If we have default 13956 // arguments we need to allocate space for them as well. We additionally 13957 // need one more slot for the object parameter. 13958 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13959 13960 // Build the full argument list for the method call (the implicit object 13961 // parameter is placed at the beginning of the list). 13962 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13963 13964 bool IsError = false; 13965 13966 // Initialize the implicit object parameter. 13967 ExprResult ObjRes = 13968 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13969 Best->FoundDecl, Method); 13970 if (ObjRes.isInvalid()) 13971 IsError = true; 13972 else 13973 Object = ObjRes; 13974 MethodArgs[0] = Object.get(); 13975 13976 // Check the argument types. 13977 for (unsigned i = 0; i != NumParams; i++) { 13978 Expr *Arg; 13979 if (i < Args.size()) { 13980 Arg = Args[i]; 13981 13982 // Pass the argument. 13983 13984 ExprResult InputInit 13985 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13986 Context, 13987 Method->getParamDecl(i)), 13988 SourceLocation(), Arg); 13989 13990 IsError |= InputInit.isInvalid(); 13991 Arg = InputInit.getAs<Expr>(); 13992 } else { 13993 ExprResult DefArg 13994 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13995 if (DefArg.isInvalid()) { 13996 IsError = true; 13997 break; 13998 } 13999 14000 Arg = DefArg.getAs<Expr>(); 14001 } 14002 14003 MethodArgs[i + 1] = Arg; 14004 } 14005 14006 // If this is a variadic call, handle args passed through "...". 14007 if (Proto->isVariadic()) { 14008 // Promote the arguments (C99 6.5.2.2p7). 14009 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14010 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14011 nullptr); 14012 IsError |= Arg.isInvalid(); 14013 MethodArgs[i + 1] = Arg.get(); 14014 } 14015 } 14016 14017 if (IsError) 14018 return true; 14019 14020 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14021 14022 // Once we've built TheCall, all of the expressions are properly owned. 14023 QualType ResultTy = Method->getReturnType(); 14024 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14025 ResultTy = ResultTy.getNonLValueExprType(Context); 14026 14027 CXXOperatorCallExpr *TheCall = 14028 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14029 ResultTy, VK, RParenLoc, FPOptions()); 14030 14031 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14032 return true; 14033 14034 if (CheckFunctionCall(Method, TheCall, Proto)) 14035 return true; 14036 14037 return MaybeBindToTemporary(TheCall); 14038 } 14039 14040 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14041 /// (if one exists), where @c Base is an expression of class type and 14042 /// @c Member is the name of the member we're trying to find. 14043 ExprResult 14044 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14045 bool *NoArrowOperatorFound) { 14046 assert(Base->getType()->isRecordType() && 14047 "left-hand side must have class type"); 14048 14049 if (checkPlaceholderForOverload(*this, Base)) 14050 return ExprError(); 14051 14052 SourceLocation Loc = Base->getExprLoc(); 14053 14054 // C++ [over.ref]p1: 14055 // 14056 // [...] An expression x->m is interpreted as (x.operator->())->m 14057 // for a class object x of type T if T::operator->() exists and if 14058 // the operator is selected as the best match function by the 14059 // overload resolution mechanism (13.3). 14060 DeclarationName OpName = 14061 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14062 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14063 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 14064 14065 if (RequireCompleteType(Loc, Base->getType(), 14066 diag::err_typecheck_incomplete_tag, Base)) 14067 return ExprError(); 14068 14069 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14070 LookupQualifiedName(R, BaseRecord->getDecl()); 14071 R.suppressDiagnostics(); 14072 14073 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14074 Oper != OperEnd; ++Oper) { 14075 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14076 None, CandidateSet, /*SuppressUserConversion=*/false); 14077 } 14078 14079 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14080 14081 // Perform overload resolution. 14082 OverloadCandidateSet::iterator Best; 14083 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14084 case OR_Success: 14085 // Overload resolution succeeded; we'll build the call below. 14086 break; 14087 14088 case OR_No_Viable_Function: { 14089 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14090 if (CandidateSet.empty()) { 14091 QualType BaseType = Base->getType(); 14092 if (NoArrowOperatorFound) { 14093 // Report this specific error to the caller instead of emitting a 14094 // diagnostic, as requested. 14095 *NoArrowOperatorFound = true; 14096 return ExprError(); 14097 } 14098 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14099 << BaseType << Base->getSourceRange(); 14100 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14101 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14102 << FixItHint::CreateReplacement(OpLoc, "."); 14103 } 14104 } else 14105 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14106 << "operator->" << Base->getSourceRange(); 14107 CandidateSet.NoteCandidates(*this, Base, Cands); 14108 return ExprError(); 14109 } 14110 case OR_Ambiguous: 14111 CandidateSet.NoteCandidates( 14112 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14113 << "->" << Base->getType() 14114 << Base->getSourceRange()), 14115 *this, OCD_AmbiguousCandidates, Base); 14116 return ExprError(); 14117 14118 case OR_Deleted: 14119 CandidateSet.NoteCandidates( 14120 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14121 << "->" << Base->getSourceRange()), 14122 *this, OCD_AllCandidates, Base); 14123 return ExprError(); 14124 } 14125 14126 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14127 14128 // Convert the object parameter. 14129 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14130 ExprResult BaseResult = 14131 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14132 Best->FoundDecl, Method); 14133 if (BaseResult.isInvalid()) 14134 return ExprError(); 14135 Base = BaseResult.get(); 14136 14137 // Build the operator call. 14138 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14139 Base, HadMultipleCandidates, OpLoc); 14140 if (FnExpr.isInvalid()) 14141 return ExprError(); 14142 14143 QualType ResultTy = Method->getReturnType(); 14144 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14145 ResultTy = ResultTy.getNonLValueExprType(Context); 14146 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14147 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 14148 14149 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14150 return ExprError(); 14151 14152 if (CheckFunctionCall(Method, TheCall, 14153 Method->getType()->castAs<FunctionProtoType>())) 14154 return ExprError(); 14155 14156 return MaybeBindToTemporary(TheCall); 14157 } 14158 14159 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14160 /// a literal operator described by the provided lookup results. 14161 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14162 DeclarationNameInfo &SuffixInfo, 14163 ArrayRef<Expr*> Args, 14164 SourceLocation LitEndLoc, 14165 TemplateArgumentListInfo *TemplateArgs) { 14166 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14167 14168 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14169 OverloadCandidateSet::CSK_Normal); 14170 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14171 TemplateArgs); 14172 14173 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14174 14175 // Perform overload resolution. This will usually be trivial, but might need 14176 // to perform substitutions for a literal operator template. 14177 OverloadCandidateSet::iterator Best; 14178 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14179 case OR_Success: 14180 case OR_Deleted: 14181 break; 14182 14183 case OR_No_Viable_Function: 14184 CandidateSet.NoteCandidates( 14185 PartialDiagnosticAt(UDSuffixLoc, 14186 PDiag(diag::err_ovl_no_viable_function_in_call) 14187 << R.getLookupName()), 14188 *this, OCD_AllCandidates, Args); 14189 return ExprError(); 14190 14191 case OR_Ambiguous: 14192 CandidateSet.NoteCandidates( 14193 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14194 << R.getLookupName()), 14195 *this, OCD_AmbiguousCandidates, Args); 14196 return ExprError(); 14197 } 14198 14199 FunctionDecl *FD = Best->Function; 14200 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14201 nullptr, HadMultipleCandidates, 14202 SuffixInfo.getLoc(), 14203 SuffixInfo.getInfo()); 14204 if (Fn.isInvalid()) 14205 return true; 14206 14207 // Check the argument types. This should almost always be a no-op, except 14208 // that array-to-pointer decay is applied to string literals. 14209 Expr *ConvArgs[2]; 14210 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14211 ExprResult InputInit = PerformCopyInitialization( 14212 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14213 SourceLocation(), Args[ArgIdx]); 14214 if (InputInit.isInvalid()) 14215 return true; 14216 ConvArgs[ArgIdx] = InputInit.get(); 14217 } 14218 14219 QualType ResultTy = FD->getReturnType(); 14220 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14221 ResultTy = ResultTy.getNonLValueExprType(Context); 14222 14223 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14224 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14225 VK, LitEndLoc, UDSuffixLoc); 14226 14227 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14228 return ExprError(); 14229 14230 if (CheckFunctionCall(FD, UDL, nullptr)) 14231 return ExprError(); 14232 14233 return MaybeBindToTemporary(UDL); 14234 } 14235 14236 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14237 /// given LookupResult is non-empty, it is assumed to describe a member which 14238 /// will be invoked. Otherwise, the function will be found via argument 14239 /// dependent lookup. 14240 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14241 /// otherwise CallExpr is set to ExprError() and some non-success value 14242 /// is returned. 14243 Sema::ForRangeStatus 14244 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14245 SourceLocation RangeLoc, 14246 const DeclarationNameInfo &NameInfo, 14247 LookupResult &MemberLookup, 14248 OverloadCandidateSet *CandidateSet, 14249 Expr *Range, ExprResult *CallExpr) { 14250 Scope *S = nullptr; 14251 14252 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14253 if (!MemberLookup.empty()) { 14254 ExprResult MemberRef = 14255 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14256 /*IsPtr=*/false, CXXScopeSpec(), 14257 /*TemplateKWLoc=*/SourceLocation(), 14258 /*FirstQualifierInScope=*/nullptr, 14259 MemberLookup, 14260 /*TemplateArgs=*/nullptr, S); 14261 if (MemberRef.isInvalid()) { 14262 *CallExpr = ExprError(); 14263 return FRS_DiagnosticIssued; 14264 } 14265 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14266 if (CallExpr->isInvalid()) { 14267 *CallExpr = ExprError(); 14268 return FRS_DiagnosticIssued; 14269 } 14270 } else { 14271 UnresolvedSet<0> FoundNames; 14272 UnresolvedLookupExpr *Fn = 14273 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14274 NestedNameSpecifierLoc(), NameInfo, 14275 /*NeedsADL=*/true, /*Overloaded=*/false, 14276 FoundNames.begin(), FoundNames.end()); 14277 14278 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14279 CandidateSet, CallExpr); 14280 if (CandidateSet->empty() || CandidateSetError) { 14281 *CallExpr = ExprError(); 14282 return FRS_NoViableFunction; 14283 } 14284 OverloadCandidateSet::iterator Best; 14285 OverloadingResult OverloadResult = 14286 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14287 14288 if (OverloadResult == OR_No_Viable_Function) { 14289 *CallExpr = ExprError(); 14290 return FRS_NoViableFunction; 14291 } 14292 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14293 Loc, nullptr, CandidateSet, &Best, 14294 OverloadResult, 14295 /*AllowTypoCorrection=*/false); 14296 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14297 *CallExpr = ExprError(); 14298 return FRS_DiagnosticIssued; 14299 } 14300 } 14301 return FRS_Success; 14302 } 14303 14304 14305 /// FixOverloadedFunctionReference - E is an expression that refers to 14306 /// a C++ overloaded function (possibly with some parentheses and 14307 /// perhaps a '&' around it). We have resolved the overloaded function 14308 /// to the function declaration Fn, so patch up the expression E to 14309 /// refer (possibly indirectly) to Fn. Returns the new expr. 14310 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14311 FunctionDecl *Fn) { 14312 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14313 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14314 Found, Fn); 14315 if (SubExpr == PE->getSubExpr()) 14316 return PE; 14317 14318 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14319 } 14320 14321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14322 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14323 Found, Fn); 14324 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14325 SubExpr->getType()) && 14326 "Implicit cast type cannot be determined from overload"); 14327 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14328 if (SubExpr == ICE->getSubExpr()) 14329 return ICE; 14330 14331 return ImplicitCastExpr::Create(Context, ICE->getType(), 14332 ICE->getCastKind(), 14333 SubExpr, nullptr, 14334 ICE->getValueKind()); 14335 } 14336 14337 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14338 if (!GSE->isResultDependent()) { 14339 Expr *SubExpr = 14340 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14341 if (SubExpr == GSE->getResultExpr()) 14342 return GSE; 14343 14344 // Replace the resulting type information before rebuilding the generic 14345 // selection expression. 14346 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14347 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14348 unsigned ResultIdx = GSE->getResultIndex(); 14349 AssocExprs[ResultIdx] = SubExpr; 14350 14351 return GenericSelectionExpr::Create( 14352 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14353 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14354 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14355 ResultIdx); 14356 } 14357 // Rather than fall through to the unreachable, return the original generic 14358 // selection expression. 14359 return GSE; 14360 } 14361 14362 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14363 assert(UnOp->getOpcode() == UO_AddrOf && 14364 "Can only take the address of an overloaded function"); 14365 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14366 if (Method->isStatic()) { 14367 // Do nothing: static member functions aren't any different 14368 // from non-member functions. 14369 } else { 14370 // Fix the subexpression, which really has to be an 14371 // UnresolvedLookupExpr holding an overloaded member function 14372 // or template. 14373 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14374 Found, Fn); 14375 if (SubExpr == UnOp->getSubExpr()) 14376 return UnOp; 14377 14378 assert(isa<DeclRefExpr>(SubExpr) 14379 && "fixed to something other than a decl ref"); 14380 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14381 && "fixed to a member ref with no nested name qualifier"); 14382 14383 // We have taken the address of a pointer to member 14384 // function. Perform the computation here so that we get the 14385 // appropriate pointer to member type. 14386 QualType ClassType 14387 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14388 QualType MemPtrType 14389 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14390 // Under the MS ABI, lock down the inheritance model now. 14391 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14392 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14393 14394 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14395 VK_RValue, OK_Ordinary, 14396 UnOp->getOperatorLoc(), false); 14397 } 14398 } 14399 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14400 Found, Fn); 14401 if (SubExpr == UnOp->getSubExpr()) 14402 return UnOp; 14403 14404 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14405 Context.getPointerType(SubExpr->getType()), 14406 VK_RValue, OK_Ordinary, 14407 UnOp->getOperatorLoc(), false); 14408 } 14409 14410 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14411 // FIXME: avoid copy. 14412 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14413 if (ULE->hasExplicitTemplateArgs()) { 14414 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14415 TemplateArgs = &TemplateArgsBuffer; 14416 } 14417 14418 DeclRefExpr *DRE = 14419 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14420 ULE->getQualifierLoc(), Found.getDecl(), 14421 ULE->getTemplateKeywordLoc(), TemplateArgs); 14422 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14423 return DRE; 14424 } 14425 14426 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14427 // FIXME: avoid copy. 14428 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14429 if (MemExpr->hasExplicitTemplateArgs()) { 14430 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14431 TemplateArgs = &TemplateArgsBuffer; 14432 } 14433 14434 Expr *Base; 14435 14436 // If we're filling in a static method where we used to have an 14437 // implicit member access, rewrite to a simple decl ref. 14438 if (MemExpr->isImplicitAccess()) { 14439 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14440 DeclRefExpr *DRE = BuildDeclRefExpr( 14441 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14442 MemExpr->getQualifierLoc(), Found.getDecl(), 14443 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14444 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14445 return DRE; 14446 } else { 14447 SourceLocation Loc = MemExpr->getMemberLoc(); 14448 if (MemExpr->getQualifier()) 14449 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14450 Base = 14451 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14452 } 14453 } else 14454 Base = MemExpr->getBase(); 14455 14456 ExprValueKind valueKind; 14457 QualType type; 14458 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14459 valueKind = VK_LValue; 14460 type = Fn->getType(); 14461 } else { 14462 valueKind = VK_RValue; 14463 type = Context.BoundMemberTy; 14464 } 14465 14466 return BuildMemberExpr( 14467 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14468 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14469 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14470 type, valueKind, OK_Ordinary, TemplateArgs); 14471 } 14472 14473 llvm_unreachable("Invalid reference to overloaded function"); 14474 } 14475 14476 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14477 DeclAccessPair Found, 14478 FunctionDecl *Fn) { 14479 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14480 } 14481